mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat(sdk): add typed Optimize previews
This commit is contained in:
@@ -639,6 +639,35 @@ await table.enableRTE({
|
||||
|
||||
***
|
||||
|
||||
### explainOptimize()
|
||||
|
||||
```ts
|
||||
explainOptimize(_options?): Promise<OptimizePlan>
|
||||
```
|
||||
|
||||
Preview Enterprise data rewriting using the same flat settings as optimizeAsync().
|
||||
Requires structured SQL preview support, table Ownership and parent Usage.
|
||||
Creates no maintenance job and does not poll job APIs. Cleanup, separate index
|
||||
maintenance, Embedded and historical-version handles are unsupported.
|
||||
A later submission plans its own snapshot.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **\_options?**: [`OptimizeOptions`](../interfaces/OptimizeOptions.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`OptimizePlan`](../interfaces/OptimizePlan.md)>
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
const plan = await table.explainOptimize({ maxSourceRows: 1_000_000 });
|
||||
console.log(plan.sourceVersion, plan.plannedSourceRows);
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### explainPrewarmData()
|
||||
|
||||
```ts
|
||||
|
||||
@@ -128,6 +128,8 @@
|
||||
- [OAuthConfig](interfaces/OAuthConfig.md)
|
||||
- [OpenTableOptions](interfaces/OpenTableOptions.md)
|
||||
- [OptimizeOptions](interfaces/OptimizeOptions.md)
|
||||
- [OptimizePlan](interfaces/OptimizePlan.md)
|
||||
- [OptimizeResolvedOptions](interfaces/OptimizeResolvedOptions.md)
|
||||
- [OptimizeResult](interfaces/OptimizeResult.md)
|
||||
- [OptimizeStats](interfaces/OptimizeStats.md)
|
||||
- [PrewarmDataOptions](interfaces/PrewarmDataOptions.md)
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / OptimizePlan
|
||||
|
||||
# Interface: OptimizePlan
|
||||
|
||||
Data-rewrite preview without creating a maintenance job.
|
||||
Counts describe planned work, not committed results, runtime, or memory use.
|
||||
A later submission chooses its own snapshot and may select different work.
|
||||
|
||||
## Properties
|
||||
|
||||
### branch
|
||||
|
||||
```ts
|
||||
branch: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### effectiveOptions
|
||||
|
||||
```ts
|
||||
effectiveOptions: OptimizeResolvedOptions;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### moreWork
|
||||
|
||||
```ts
|
||||
moreWork: boolean;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### namespace
|
||||
|
||||
```ts
|
||||
namespace: string[];
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### operation
|
||||
|
||||
```ts
|
||||
operation: "rewrite_data";
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### plannedFragments
|
||||
|
||||
```ts
|
||||
plannedFragments: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### plannedGroups
|
||||
|
||||
```ts
|
||||
plannedGroups: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### plannedSourceRows
|
||||
|
||||
```ts
|
||||
plannedSourceRows: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### sourceVersion
|
||||
|
||||
```ts
|
||||
sourceVersion: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### table
|
||||
|
||||
```ts
|
||||
table: string;
|
||||
```
|
||||
@@ -0,0 +1,43 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / OptimizeResolvedOptions
|
||||
|
||||
# Interface: OptimizeResolvedOptions
|
||||
|
||||
Effective settings after Enterprise policy resolution.
|
||||
|
||||
## Properties
|
||||
|
||||
### batchSize
|
||||
|
||||
```ts
|
||||
batchSize: null | number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### ioBufferSize
|
||||
|
||||
```ts
|
||||
ioBufferSize: null | number;
|
||||
```
|
||||
|
||||
Zero disables byte-based I/O backpressure; null uses the worker default.
|
||||
|
||||
***
|
||||
|
||||
### maxSourceRows
|
||||
|
||||
```ts
|
||||
maxSourceRows: null | number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### targetRowsPerFragment
|
||||
|
||||
```ts
|
||||
targetRowsPerFragment: number;
|
||||
```
|
||||
@@ -1520,6 +1520,10 @@ that accepts `python_bundle.resources`.
|
||||
Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or
|
||||
`conda=` for platform-specific dependencies and `models=` for large model snapshots.
|
||||
|
||||
::: lancedb.optimize.OptimizePlan
|
||||
|
||||
::: lancedb.optimize.OptimizeResolvedOptions
|
||||
|
||||
::: lancedb.optimize.OptimizeResult
|
||||
|
||||
::: lancedb.prewarm.PrewarmDataResult
|
||||
|
||||
@@ -238,6 +238,11 @@ EXPLAIN OPTIMIZE events REWRITE DATA WITH (
|
||||
max_source_rows = 1000000
|
||||
);
|
||||
|
||||
EXPLAIN (FORMAT JSON) OPTIMIZE events REWRITE DATA WITH (
|
||||
target_rows_per_fragment = 100000,
|
||||
max_source_rows = 1000000
|
||||
);
|
||||
|
||||
DESCRIBE JOB '<job_id>' FORMAT JSON;
|
||||
```
|
||||
|
||||
@@ -245,6 +250,48 @@ The preview uses the execution planner to report the source version, resolved
|
||||
options, planned groups/fragments/rows, and whether more eligible work remains.
|
||||
It creates no job. Submission plans against its own snapshot, so concurrent
|
||||
writes can change the work after a preview. `EXPLAIN ANALYZE` is unsupported.
|
||||
The explicit JSON form returns a versioned response with `operation: "rewrite_data"`;
|
||||
plain EXPLAIN retains its existing output. PREWARM uses the same explicit format syntax.
|
||||
|
||||
The SDK helpers return a typed `OptimizePlan` using the same flat rewrite settings
|
||||
as durable submission:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Python">
|
||||
```python
|
||||
plan = table.explain_optimize(max_source_rows=1_000_000, io_buffer_size=0)
|
||||
print(plan.source_version, plan.planned_source_rows, plan.more_work)
|
||||
```
|
||||
Async Python uses `await table.explain_optimize(...)` with the same settings.
|
||||
</Tab>
|
||||
<Tab title="TypeScript">
|
||||
```typescript
|
||||
const plan = await table.explainOptimize({ maxSourceRows: 1_000_000, ioBufferSize: 0 });
|
||||
console.log(plan.sourceVersion, plan.plannedSourceRows, plan.moreWork);
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Rust">
|
||||
```rust
|
||||
use lancedb::table::optimize::OptimizeOptions;
|
||||
|
||||
let plan = table.explain_optimize(OptimizeOptions {
|
||||
max_source_rows: Some(1_000_000),
|
||||
io_buffer_size: Some(0),
|
||||
..Default::default()
|
||||
}).await?;
|
||||
println!("{} {}", plan.source_version, plan.planned_source_rows);
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
`effective_options` (`effectiveOptions` in TypeScript) contains the resolved
|
||||
fragment target, source-row budget, I/O buffer size, and batch size. Counts describe
|
||||
planned work, not committed results, runtime, or a memory estimate. A null optional
|
||||
setting retains the worker default; an explicit zero I/O buffer remains zero.
|
||||
Preview covers only data rewriting. Cleanup, separate index maintenance,
|
||||
Embedded tables, and historical-version handles are unsupported. The helper
|
||||
requires a server supporting the explicit JSON syntax and fails without falling
|
||||
back to text parsing, REST, or execution.
|
||||
|
||||
JSON job diagnostics include reported maintenance progress and the completed
|
||||
operation result alongside the existing time profile. While a job runs, its
|
||||
|
||||
@@ -6174,3 +6174,77 @@ it("rejects the removed dataOptions wrapper before submission", async () => {
|
||||
).rejects.toThrow("Unsupported Optimize option: dataOptions");
|
||||
expect(optimize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe("Optimize preview", () => {
|
||||
it.each([false, true])(
|
||||
"decodes a typed preview with legacy wrapper=%p",
|
||||
async (legacy) => {
|
||||
const explainOptimize = jest.fn().mockResolvedValue(
|
||||
JSON.parse(`{
|
||||
"operation":"rewrite_data", "table":"events", "namespace":["team"], "branch":"main",
|
||||
"source_version":42, "planned_groups":0, "planned_fragments":0, "planned_source_rows":0,
|
||||
"more_work":false,
|
||||
"effective_options":{"target_rows_per_fragment":1000,"io_buffer_size":0,"max_source_rows":null,"batch_size":null}
|
||||
}`),
|
||||
);
|
||||
const table = new LocalTable({ explainOptimize } as never);
|
||||
const plan = await table.explainOptimize(
|
||||
legacy
|
||||
? {
|
||||
compactionOptions: { maxSourceRows: 500, ioBufferSize: 0 },
|
||||
action: "rewrite_data",
|
||||
}
|
||||
: {
|
||||
maxSourceRows: 500,
|
||||
ioBufferSize: 0,
|
||||
action: "rewrite_data",
|
||||
},
|
||||
);
|
||||
expect(explainOptimize).toHaveBeenCalledTimes(1);
|
||||
expect(explainOptimize).toHaveBeenCalledWith({
|
||||
maxSourceRows: 500,
|
||||
ioBufferSize: 0,
|
||||
});
|
||||
expect(plan).toEqual({
|
||||
operation: "rewrite_data",
|
||||
table: "events",
|
||||
namespace: ["team"],
|
||||
branch: "main",
|
||||
sourceVersion: 42,
|
||||
plannedGroups: 0,
|
||||
plannedFragments: 0,
|
||||
plannedSourceRows: 0,
|
||||
moreWork: false,
|
||||
effectiveOptions: {
|
||||
targetRowsPerFragment: 1000,
|
||||
ioBufferSize: 0,
|
||||
maxSourceRows: null,
|
||||
batchSize: null,
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
test.each([
|
||||
{ cleanupOlderThan: new Date() },
|
||||
{ deleteUnverified: true },
|
||||
{ action: "cleanup" },
|
||||
{ dataOptions: {} },
|
||||
{ unknown: 1 },
|
||||
])(
|
||||
"rejects unsupported preview settings before native calls: %j",
|
||||
async (options) => {
|
||||
const explainOptimize = jest.fn();
|
||||
const table = new LocalTable({ explainOptimize } as never);
|
||||
await expect(table.explainOptimize(options as never)).rejects.toThrow();
|
||||
expect(explainOptimize).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
it("rejects Embedded previews", async () => {
|
||||
const db = await connect(`memory://optimize-preview-${Date.now()}`);
|
||||
const table = await db.createTable("events", [{ id: 1 }]);
|
||||
await expect(table.explainOptimize()).rejects.toThrow("Enterprise");
|
||||
await expect(table.explainOptimize({ batchSize: 0 })).rejects.toThrow(
|
||||
"safe integer",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -667,7 +667,11 @@ export {
|
||||
|
||||
export { Listing, ListingOptions } from "./listing";
|
||||
|
||||
export type { OptimizeResult } from "./optimize";
|
||||
export type {
|
||||
OptimizePlan,
|
||||
OptimizeResolvedOptions,
|
||||
OptimizeResult,
|
||||
} from "./optimize";
|
||||
export type { CompactionResult } from "./compaction";
|
||||
|
||||
export type {
|
||||
|
||||
@@ -39,3 +39,52 @@ export function decodeOptimizeResult(value: unknown): OptimizeResult {
|
||||
fragmentsRemoved: (result.fragments_removed as number | null) ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Effective settings after Enterprise policy resolution. */
|
||||
export interface OptimizeResolvedOptions {
|
||||
targetRowsPerFragment: number;
|
||||
maxSourceRows: number | null;
|
||||
/** Zero disables byte-based I/O backpressure; null uses the worker default. */
|
||||
ioBufferSize: number | null;
|
||||
batchSize: number | null;
|
||||
}
|
||||
|
||||
/** Data-rewrite preview without creating a maintenance job.
|
||||
* Counts describe planned work, not committed results, runtime, or memory use.
|
||||
* A later submission chooses its own snapshot and may select different work. */
|
||||
export interface OptimizePlan {
|
||||
operation: "rewrite_data";
|
||||
table: string;
|
||||
namespace: string[];
|
||||
branch: string;
|
||||
sourceVersion: number;
|
||||
effectiveOptions: OptimizeResolvedOptions;
|
||||
plannedGroups: number;
|
||||
plannedFragments: number;
|
||||
plannedSourceRows: number;
|
||||
moreWork: boolean;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function decodeOptimizePlan(value: unknown): OptimizePlan {
|
||||
// Rust validates the versioned SQL response before exposing it to JS.
|
||||
const plan = value as Record<string, unknown>;
|
||||
const options = plan.effective_options as Record<string, number | null>;
|
||||
return {
|
||||
operation: plan.operation as "rewrite_data",
|
||||
table: plan.table as string,
|
||||
namespace: plan.namespace as string[],
|
||||
branch: plan.branch as string,
|
||||
sourceVersion: plan.source_version as number,
|
||||
plannedGroups: plan.planned_groups as number,
|
||||
plannedFragments: plan.planned_fragments as number,
|
||||
plannedSourceRows: plan.planned_source_rows as number,
|
||||
moreWork: plan.more_work as boolean,
|
||||
effectiveOptions: {
|
||||
targetRowsPerFragment: options.target_rows_per_fragment as number,
|
||||
maxSourceRows: options.max_source_rows ?? null,
|
||||
ioBufferSize: options.io_buffer_size ?? null,
|
||||
batchSize: options.batch_size ?? null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
+29
-1
@@ -1,7 +1,12 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import { OptimizeResult, decodeOptimizeResult } from "./optimize";
|
||||
import {
|
||||
OptimizePlan,
|
||||
OptimizeResult,
|
||||
decodeOptimizePlan,
|
||||
decodeOptimizeResult,
|
||||
} from "./optimize";
|
||||
import {
|
||||
PrewarmDataPlan,
|
||||
PrewarmDataResult,
|
||||
@@ -1320,6 +1325,21 @@ export abstract class Table {
|
||||
* out state and the read_consistency_interval, if any, will apply.
|
||||
*/
|
||||
abstract restore(): Promise<void>;
|
||||
/** Preview Enterprise data rewriting using the same flat settings as optimizeAsync().
|
||||
* Requires structured SQL preview support, table Ownership and parent Usage.
|
||||
* Creates no maintenance job and does not poll job APIs. Cleanup, separate index
|
||||
* maintenance, Embedded and historical-version handles are unsupported.
|
||||
* A later submission plans its own snapshot.
|
||||
* @example
|
||||
* const plan = await table.explainOptimize({ maxSourceRows: 1_000_000 });
|
||||
* console.log(plan.sourceVersion, plan.plannedSourceRows);
|
||||
*/
|
||||
async explainOptimize(_options?: OptimizeOptions): Promise<OptimizePlan> {
|
||||
throw new Error(
|
||||
"Optimize previews are only supported by LanceDB Enterprise",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit Enterprise Optimize and return its durable job after acceptance.
|
||||
*
|
||||
@@ -2067,6 +2087,14 @@ export class LocalTable extends Table {
|
||||
return this.inner.currentBranch() ?? null;
|
||||
}
|
||||
|
||||
async explainOptimize(options?: OptimizeOptions): Promise<OptimizePlan> {
|
||||
options = normalizeOptimizeOptions(options);
|
||||
validateOptimizeOptions(options, true);
|
||||
return decodeOptimizePlan(
|
||||
await this.inner.explainOptimize(optimizeRewriteSettings(options)),
|
||||
);
|
||||
}
|
||||
|
||||
async optimizeAsync(options?: OptimizeOptions): Promise<Job<OptimizeResult>> {
|
||||
options = normalizeOptimizeOptions(options);
|
||||
validateOptimizeOptions(options, true);
|
||||
|
||||
@@ -1001,6 +1001,23 @@ impl Table {
|
||||
Ok(self.inner_ref()?.current_branch())
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn explain_optimize(
|
||||
&self,
|
||||
options: Option<OptimizeOptions>,
|
||||
) -> napi::Result<serde_json::Value> {
|
||||
let options = options
|
||||
.map(OptimizeOptions::into_overrides)
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let plan = self
|
||||
.inner_ref()?
|
||||
.explain_optimize(options)
|
||||
.await
|
||||
.default_error()?;
|
||||
serde_json::to_value(plan).map_err(|error| napi::Error::from_reason(error.to_string()))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn optimize_async(
|
||||
&self,
|
||||
|
||||
@@ -806,6 +806,9 @@ class Table:
|
||||
async def update_field_metadata(
|
||||
self, updates: list[dict[str, Any]]
|
||||
) -> UpdateFieldMetadataResult: ...
|
||||
async def explain_optimize(
|
||||
self, data_options: Optional[Dict[str, Any]] = None
|
||||
) -> str: ...
|
||||
async def optimize_async(
|
||||
self, data_options: Optional[Dict[str, Any]] = None
|
||||
) -> Job: ...
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Results of durable Enterprise Optimize jobs."""
|
||||
"""Typed previews and results of Enterprise Optimize data rewrites."""
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
import json
|
||||
from typing import Optional
|
||||
from typing import List, Literal, Optional
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -35,3 +35,48 @@ class OptimizeResult:
|
||||
value = json.loads(raw)
|
||||
names = {field.name for field in fields(cls)}
|
||||
return cls(**{key: item for key, item in value.items() if key in names})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OptimizeResolvedOptions:
|
||||
"""Effective rewrite settings after Enterprise policy resolution."""
|
||||
|
||||
target_rows_per_fragment: int
|
||||
max_source_rows: Optional[int] = None
|
||||
io_buffer_size: Optional[int] = None
|
||||
batch_size: Optional[int] = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OptimizePlan:
|
||||
"""Data-rewrite preview without submitting a maintenance job.
|
||||
|
||||
Counts describe planned work, not committed results, memory use, or runtime.
|
||||
A later submission plans its own snapshot and may select different work.
|
||||
"""
|
||||
|
||||
operation: Literal["rewrite_data"]
|
||||
table: str
|
||||
namespace: List[str]
|
||||
branch: str
|
||||
source_version: int
|
||||
effective_options: OptimizeResolvedOptions
|
||||
planned_groups: int
|
||||
planned_fragments: int
|
||||
planned_source_rows: int
|
||||
more_work: bool
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, raw: str) -> "OptimizePlan":
|
||||
# The native decoder validates the versioned server contract first.
|
||||
value = json.loads(raw)
|
||||
option_names = {field.name for field in fields(OptimizeResolvedOptions)}
|
||||
value["effective_options"] = OptimizeResolvedOptions(
|
||||
**{
|
||||
key: item
|
||||
for key, item in value["effective_options"].items()
|
||||
if key in option_names
|
||||
}
|
||||
)
|
||||
names = {field.name for field in fields(cls)}
|
||||
return cls(**{key: item for key, item in value.items() if key in names})
|
||||
|
||||
@@ -51,6 +51,7 @@ from lancedb.index import (
|
||||
Bitmap,
|
||||
LabelList,
|
||||
)
|
||||
from lancedb.optimize import OptimizePlan
|
||||
from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
|
||||
from lancedb.job import Job
|
||||
from lancedb.functions import (
|
||||
@@ -1128,6 +1129,9 @@ class RemoteTable(Table):
|
||||
)
|
||||
return self.optimize_async(**(compaction_options or {}))
|
||||
|
||||
def explain_optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizePlan:
|
||||
return LOOP.run(self._table.explain_optimize(**options))
|
||||
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
return Job(LOOP.run(self._table.optimize_async(**options)))
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ from lancedb.background_loop import LOOP, embedding_executor
|
||||
from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
|
||||
from lancedb.job import AsyncJob, Job, _typed_job
|
||||
from lancedb.compaction import CompactionResult # noqa: F401 - public compatibility import
|
||||
from lancedb.optimize import OptimizeResult
|
||||
from lancedb.optimize import OptimizePlan, OptimizeResult
|
||||
from .dependencies import (
|
||||
_check_for_hugging_face,
|
||||
_check_for_lance,
|
||||
@@ -3230,6 +3230,23 @@ class Table(ABC):
|
||||
)
|
||||
return self.optimize_async(**(compaction_options or {}))
|
||||
|
||||
def explain_optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizePlan:
|
||||
"""Preview Enterprise data rewriting without creating a maintenance job.
|
||||
|
||||
Accepts the same flat rewrite settings as ``optimize_async()``. Cleanup
|
||||
and separate index maintenance are unsupported, as are Embedded and
|
||||
historical-version handles. Requires SQL preview support, table
|
||||
Ownership and parent Usage. A later submission plans its own snapshot.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> plan = table.explain_optimize(max_source_rows=1_000_000) # doctest: +SKIP
|
||||
>>> print(plan.source_version, plan.planned_source_rows) # doctest: +SKIP
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
"Optimize previews are only supported by LanceDB Enterprise"
|
||||
)
|
||||
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
"""Submit Enterprise Optimize and return a durable job after acceptance.
|
||||
|
||||
@@ -5990,6 +6007,9 @@ class LanceTable(Table):
|
||||
)
|
||||
return self.optimize_async(**(compaction_options or {}))
|
||||
|
||||
def explain_optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizePlan:
|
||||
return LOOP.run(self._table.explain_optimize(**options))
|
||||
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
return Job(LOOP.run(self._table.optimize_async(**options)))
|
||||
|
||||
@@ -9690,6 +9710,16 @@ class AsyncTable:
|
||||
)
|
||||
return await self.optimize_async(**(compaction_options or {}))
|
||||
|
||||
async def explain_optimize(
|
||||
self, **options: Unpack[OptimizeOptions]
|
||||
) -> OptimizePlan:
|
||||
"""Preview Enterprise data rewriting without submitting a job.
|
||||
|
||||
See [Table.explain_optimize][lancedb.table.Table.explain_optimize].
|
||||
"""
|
||||
tuning, _, _, _ = _split_optimize_options(options, durable=True)
|
||||
return OptimizePlan.from_json(await self._inner.explain_optimize(tuning))
|
||||
|
||||
async def optimize_async(
|
||||
self, **options: Unpack[OptimizeOptions]
|
||||
) -> AsyncJob[OptimizeResult]:
|
||||
|
||||
@@ -8810,3 +8810,177 @@ def test_legacy_optimize_rejects_ambiguous_or_unknown_settings(options):
|
||||
|
||||
with pytest.warns(DeprecationWarning), pytest.raises(TypeError):
|
||||
_split_optimize_options(options)
|
||||
|
||||
|
||||
def _optimize_preview_payload():
|
||||
return {
|
||||
"format_version": 1,
|
||||
"operation": "rewrite_data",
|
||||
"table": "test",
|
||||
"namespace": [],
|
||||
"branch": "main",
|
||||
"source_version": 42,
|
||||
"effective_options": {
|
||||
"target_rows_per_fragment": 1000,
|
||||
"max_source_rows": None,
|
||||
"io_buffer_size": 0,
|
||||
"batch_size": None,
|
||||
},
|
||||
"planned_groups": 0,
|
||||
"planned_fragments": 0,
|
||||
"planned_source_rows": 0,
|
||||
"more_work": False,
|
||||
"future_field": "ignored",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"options, expected",
|
||||
[
|
||||
({}, None),
|
||||
({"compaction_options": {"io_buffer_size": 0}}, b"io_buffer_size = 0"),
|
||||
(
|
||||
{"target_rows_per_fragment": 1_048_576},
|
||||
b"target_rows_per_fragment = 1048576",
|
||||
),
|
||||
(
|
||||
{"max_source_rows": 500, "io_buffer_size": 0, "batch_size": 16},
|
||||
b"io_buffer_size = 0",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_explain_optimize_forwards_flat_options_without_creating_jobs(
|
||||
asynchronous, options, expected
|
||||
):
|
||||
from lancedb.optimize import OptimizePlan, OptimizeResolvedOptions
|
||||
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class Server(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.tickets = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.tickets.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(
|
||||
pa.table(
|
||||
{
|
||||
"plan_type": ["logical_plan"],
|
||||
"plan": [json.dumps(_optimize_preview_payload())],
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
server = Server()
|
||||
with _mock_remote_sql_connection(server) as kwargs:
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
plan = await table.explain_optimize(**options)
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
plan = table.explain_optimize(**options)
|
||||
assert isinstance(plan, OptimizePlan)
|
||||
assert isinstance(plan.effective_options, OptimizeResolvedOptions)
|
||||
assert plan.operation == "rewrite_data"
|
||||
assert plan.source_version == 42
|
||||
assert plan.planned_source_rows == 0
|
||||
assert plan.effective_options.io_buffer_size == 0
|
||||
assert plan.effective_options.batch_size is None
|
||||
assert not plan.more_work
|
||||
assert len(server.tickets) == 1
|
||||
assert b"EXPLAIN (FORMAT JSON) OPTIMIZE" in server.tickets[0]
|
||||
if expected:
|
||||
assert expected in server.tickets[0]
|
||||
else:
|
||||
assert b"WITH (" not in server.tickets[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"change", ["version", "operation", "missing", "negative", "text", "duplicate"]
|
||||
)
|
||||
async def test_explain_optimize_rejects_malformed_previews_without_retry(
|
||||
asynchronous, change
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class Server(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
|
||||
plan = _optimize_preview_payload()
|
||||
if change == "version":
|
||||
plan["format_version"] = 99
|
||||
elif change == "operation":
|
||||
plan["operation"] = "cleanup"
|
||||
elif change == "missing":
|
||||
del plan["source_version"]
|
||||
elif change == "negative":
|
||||
plan["planned_groups"] = -1
|
||||
value = "display text" if change == "text" else json.dumps(plan)
|
||||
return flight.RecordBatchStream(
|
||||
pa.table({"plan": [value] * (2 if change == "duplicate" else 1)})
|
||||
)
|
||||
|
||||
server = Server()
|
||||
with _mock_remote_sql_connection(server) as kwargs:
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
with pytest.raises(Exception, match="structured preview"):
|
||||
await table.explain_optimize()
|
||||
else:
|
||||
table = lancedb.connect(**kwargs).create_table("test", [{"id": 1}])
|
||||
with pytest.raises(Exception, match="structured preview"):
|
||||
table.explain_optimize()
|
||||
assert server.calls == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"options",
|
||||
[
|
||||
{"cleanup_older_than": timedelta(days=1)},
|
||||
{"delete_unverified": True},
|
||||
{"action": "cleanup"},
|
||||
{"data_options": {}},
|
||||
{"batch_size": 0},
|
||||
{"max_source_bytes": 1024},
|
||||
],
|
||||
)
|
||||
async def test_explain_optimize_rejects_unsupported_options_before_requests(
|
||||
asynchronous, options
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class Server(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("invalid previews must not send SQL")
|
||||
|
||||
server = Server()
|
||||
with _mock_remote_sql_connection(server) as kwargs:
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
with pytest.raises((ValueError, TypeError, NotImplementedError)):
|
||||
await table.explain_optimize(**options)
|
||||
else:
|
||||
table = lancedb.connect(**kwargs).create_table("test", [{"id": 1}])
|
||||
with pytest.raises((ValueError, TypeError, NotImplementedError)):
|
||||
table.explain_optimize(**options)
|
||||
assert server.calls == 0
|
||||
|
||||
@@ -6542,3 +6542,13 @@ async def test_optimize_inherits_embedded_table_config(tmp_path, asynchronous):
|
||||
)
|
||||
assert stats.compaction.fragments_removed == 2
|
||||
assert table.count_rows() == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_explain_optimize_requires_enterprise(mem_db, mem_db_async):
|
||||
table = mem_db.create_table("preview", [{"id": 1}])
|
||||
with pytest.raises(NotImplementedError, match="Enterprise"):
|
||||
table.explain_optimize()
|
||||
table = await mem_db_async.create_table("preview", [{"id": 1}])
|
||||
with pytest.raises(NotImplementedError, match="Enterprise"):
|
||||
await table.explain_optimize()
|
||||
|
||||
@@ -26,6 +26,7 @@ import pytest
|
||||
"search",
|
||||
"cleanup_old_versions",
|
||||
"optimize_async",
|
||||
"explain_optimize",
|
||||
"optimize",
|
||||
"to_polars",
|
||||
],
|
||||
|
||||
@@ -8,7 +8,7 @@ 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
|
||||
from lancedb.optimize import OptimizePlan, OptimizeResult
|
||||
|
||||
|
||||
def synchronous(table: Table) -> None:
|
||||
@@ -17,6 +17,8 @@ def synchronous(table: Table) -> None:
|
||||
assert_type(table.optimize(retrain=False), OptimizeStats)
|
||||
table.optimize_async(retrain=True) # pyright: ignore[reportCallIssue]
|
||||
assert_type(table.optimize_async(**options), Job[OptimizeResult])
|
||||
assert_type(table.explain_optimize(**options), OptimizePlan)
|
||||
table.explain_optimize(data_options={}) # pyright: ignore[reportCallIssue]
|
||||
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]
|
||||
@@ -27,6 +29,7 @@ async def asynchronous(table: AsyncTable) -> None:
|
||||
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})
|
||||
assert_type(await table.explain_optimize(**options), OptimizePlan)
|
||||
|
||||
|
||||
async def legacy_types(table: AsyncTable) -> None:
|
||||
@@ -39,3 +42,8 @@ async def legacy_types(table: AsyncTable) -> None:
|
||||
await table.compact_async(compaction_options=options),
|
||||
AsyncJob[CompactionResult],
|
||||
)
|
||||
|
||||
|
||||
def preview_types(table: Table, options: OptimizeOptions) -> None:
|
||||
assert_type(table.explain_optimize(**options), OptimizePlan)
|
||||
table.explain_optimize(compaction_options={})
|
||||
|
||||
@@ -2316,6 +2316,19 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (data_options=None))]
|
||||
pub fn explain_optimize<'py>(
|
||||
self_: PyRef<'py, Self>,
|
||||
data_options: Option<&Bound<'py, PyDict>>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let options = parse_optimize_options(data_options)?;
|
||||
future_into_py(self_.py(), async move {
|
||||
let plan = inner.explain_optimize(options).await.infer_error()?;
|
||||
serde_json::to_string(&plan).map_err(|error| PyRuntimeError::new_err(error.to_string()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Submit remote Optimize and retain its durable job and actual result.
|
||||
#[pyo3(signature = (data_options=None))]
|
||||
pub fn optimize_async<'py>(
|
||||
|
||||
@@ -516,7 +516,8 @@ impl FlightService for TestSqlService {
|
||||
.and_then(|command| command.unpack::<CommandStatementQuery>().ok().flatten());
|
||||
if let Some(command) = &initial {
|
||||
self.statements.lock().unwrap().push(command.query.clone());
|
||||
if command.query.starts_with("OPTIMIZE ")
|
||||
if (command.query.starts_with("OPTIMIZE ")
|
||||
|| command.query.starts_with("EXPLAIN (FORMAT JSON) OPTIMIZE "))
|
||||
&& let Some(error) = &self.optimize_error
|
||||
{
|
||||
return Err(error.clone());
|
||||
@@ -5428,3 +5429,186 @@ async fn remote_optimize_legacy_compact_convenience_preserves_settings_without_p
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn optimize_preview_result() -> RecordBatch {
|
||||
let value = serde_json::json!({
|
||||
"format_version":1, "operation":"rewrite_data", "table":"events", "namespace":["team","inner"],
|
||||
"branch":"o'brien", "source_version":42,
|
||||
"effective_options":{"target_rows_per_fragment":1000,"max_source_rows":500,"io_buffer_size":0,"batch_size":16},
|
||||
"planned_groups":2,"planned_fragments":4,"planned_source_rows":400,"more_work":true,
|
||||
});
|
||||
RecordBatch::try_from_iter([(
|
||||
"plan",
|
||||
Arc::new(StringArray::from(vec![value.to_string()])) as ArrayRef,
|
||||
)])
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_optimize_preview_uses_shared_options_without_submitting_jobs() {
|
||||
use crate::table::OptimizeOverrides;
|
||||
use crate::table::optimize::OptimizeOptions;
|
||||
for (adaptive, defer) in [(false, false), (true, false), (true, true)] {
|
||||
let service = TestSqlService {
|
||||
adaptive,
|
||||
defer,
|
||||
result: optimize_preview_result(),
|
||||
..Default::default()
|
||||
};
|
||||
let statements = service.statements.clone();
|
||||
let headers = service.headers.clone();
|
||||
let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await;
|
||||
let table = public_remote_table(
|
||||
RemoteTable::new_with_sql_client(
|
||||
client_with_handler(|request| -> http::Response<String> {
|
||||
panic!("preview must not call HTTP jobs or REST: {}", request.url());
|
||||
}),
|
||||
"analytics".into(),
|
||||
"events".into(),
|
||||
vec!["team".into(), "inner".into()],
|
||||
"team$inner$events".into(),
|
||||
Default::default(),
|
||||
Some(sql),
|
||||
)
|
||||
.with_branch(Some("o'brien".into())),
|
||||
);
|
||||
let options = OptimizeOptions {
|
||||
max_source_rows: Some(500),
|
||||
io_buffer_size: Some(0),
|
||||
..Default::default()
|
||||
};
|
||||
let preview = table.explain_optimize(options).await.unwrap();
|
||||
assert_eq!(preview.source_version, 42);
|
||||
assert_eq!(preview.planned_source_rows, 400);
|
||||
assert!(preview.more_work);
|
||||
assert_eq!(preview.effective_options.io_buffer_size, Some(0));
|
||||
let target =
|
||||
lance::dataset::optimize::CompactionOptions::default().target_rows_per_fragment;
|
||||
table
|
||||
.explain_optimize(OptimizeOverrides {
|
||||
target_rows_per_fragment: Some(target),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(*statements.lock().unwrap(), [
|
||||
"EXPLAIN (FORMAT JSON) OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'o''brien', max_source_rows = 500, io_buffer_size = 0)".to_owned(),
|
||||
format!("EXPLAIN (FORMAT JSON) OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'o''brien', target_rows_per_fragment = {target})"),
|
||||
]);
|
||||
assert!(!headers.lock().unwrap().is_empty());
|
||||
assert!(
|
||||
headers
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|h| h.database == "analytics" && h.namespace_path == "team$inner")
|
||||
);
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_optimize_preview_rejects_maintenance_and_invalid_options_before_sql() {
|
||||
use crate::table::optimize::OptimizeOptions;
|
||||
use crate::table::{OptimizeAction, OptimizeOverrides};
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
result: optimize_preview_result(),
|
||||
..Default::default()
|
||||
};
|
||||
let statements = service.statements.clone();
|
||||
let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await;
|
||||
let table = public_remote_table(RemoteTable::new_with_sql_client(
|
||||
client_with_handler(|_| -> http::Response<String> { panic!("no REST") }),
|
||||
"analytics".into(),
|
||||
"events".into(),
|
||||
vec![],
|
||||
"events".into(),
|
||||
Default::default(),
|
||||
Some(sql),
|
||||
));
|
||||
for action in [
|
||||
OptimizeAction::All,
|
||||
OptimizeAction::Index(Default::default()),
|
||||
OptimizeAction::Prune {
|
||||
older_than: None,
|
||||
delete_unverified: None,
|
||||
error_if_tagged_old_versions: None,
|
||||
},
|
||||
] {
|
||||
assert!(matches!(
|
||||
table.explain_optimize(action).await,
|
||||
Err(Error::NotSupported { .. })
|
||||
));
|
||||
}
|
||||
assert!(matches!(
|
||||
table
|
||||
.explain_optimize(OptimizeOptions {
|
||||
max_source_bytes: Some(10),
|
||||
..Default::default()
|
||||
})
|
||||
.await,
|
||||
Err(Error::NotSupported { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
table
|
||||
.explain_optimize(OptimizeOverrides {
|
||||
batch_size: Some(0),
|
||||
..Default::default()
|
||||
})
|
||||
.await,
|
||||
Err(Error::InvalidInput { .. })
|
||||
));
|
||||
assert!(statements.lock().unwrap().is_empty());
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_optimize_preview_preserves_errors_without_retry_or_execution_fallback() {
|
||||
for (code, message, unsupported) in [
|
||||
(
|
||||
tonic::Code::InvalidArgument,
|
||||
"ParserError: Expected OPTIMIZE",
|
||||
true,
|
||||
),
|
||||
(
|
||||
tonic::Code::Internal,
|
||||
"Invalid EXPLAIN format. Expected text or json, got 'JSON'",
|
||||
true,
|
||||
),
|
||||
(tonic::Code::PermissionDenied, "permission denied", false),
|
||||
(tonic::Code::NotFound, "table missing", false),
|
||||
] {
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
optimize_error: Some(Status::new(code, message)),
|
||||
..Default::default()
|
||||
};
|
||||
let statements = service.statements.clone();
|
||||
let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await;
|
||||
let table = public_remote_table(RemoteTable::new_with_sql_client(
|
||||
client_with_handler(|_| -> http::Response<String> { panic!("no REST fallback") }),
|
||||
"analytics".into(),
|
||||
"events".into(),
|
||||
vec![],
|
||||
"events".into(),
|
||||
Default::default(),
|
||||
Some(sql),
|
||||
));
|
||||
let error = table
|
||||
.explain_optimize(crate::table::OptimizeOverrides::default())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
matches!(error, Error::NotSupported { .. }),
|
||||
unsupported,
|
||||
"{error}"
|
||||
);
|
||||
assert!(error.to_string().contains(message));
|
||||
if unsupported {
|
||||
assert!(error.to_string().contains("EXPLAIN (FORMAT JSON) OPTIMIZE"));
|
||||
}
|
||||
assert_eq!(statements.lock().unwrap().len(), 1);
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod blobs;
|
||||
pub mod insert;
|
||||
mod ipc_stream;
|
||||
mod optimize;
|
||||
mod preview;
|
||||
mod prewarm;
|
||||
#[cfg(test)]
|
||||
mod write_tests;
|
||||
@@ -674,6 +675,40 @@ impl<S: HttpSend> std::fmt::Debug for RemoteTable<S> {
|
||||
}
|
||||
|
||||
impl<S: HttpSend> RemoteTable<S> {
|
||||
async fn execute_optimize_statement(
|
||||
&self,
|
||||
options: &crate::table::OptimizeOverrides,
|
||||
explain: bool,
|
||||
) -> Result<Vec<arrow_array::RecordBatch>> {
|
||||
self.check_mutable().await?;
|
||||
let mut statement = optimize::statement(&self.name, self.branch.as_deref(), options)?;
|
||||
if explain {
|
||||
statement = format!("EXPLAIN (FORMAT JSON) {statement}");
|
||||
}
|
||||
let client = self.sql_client.as_ref().ok_or_else(|| Error::NotSupported {
|
||||
message: if explain { "Optimize previews require a Flight SQL endpoint supporting EXPLAIN (FORMAT JSON) OPTIMIZE" } else { "Optimize jobs require a Flight SQL endpoint" }.into(),
|
||||
})?;
|
||||
let map_error = if explain {
|
||||
optimize::map_explain_error
|
||||
} else {
|
||||
optimize::map_optimize_error
|
||||
};
|
||||
let query = client
|
||||
.execute(crate::database::ExecuteQueryRequest {
|
||||
query: statement,
|
||||
default_namespace_path: self.namespace.clone(),
|
||||
parameters: None,
|
||||
})
|
||||
.await
|
||||
.map_err(map_error)?;
|
||||
let mut reader = query.reader().await.map_err(map_error)?;
|
||||
let mut batches = Vec::new();
|
||||
while let Some(batch) = reader.try_next().await.map_err(map_error)? {
|
||||
batches.push(batch);
|
||||
}
|
||||
Ok(batches)
|
||||
}
|
||||
|
||||
fn table_overrides_query(&self) -> Vec<(&str, &str)> {
|
||||
let mut query = Vec::with_capacity(3 + self.namespace.len());
|
||||
query.push(("db", self.db_name.as_str()));
|
||||
@@ -4067,31 +4102,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
&self,
|
||||
options: crate::table::optimize::OptimizeOverrides,
|
||||
) -> Result<Job<crate::table::OptimizeResult>> {
|
||||
self.check_mutable().await?;
|
||||
let statement = optimize::statement(&self.name, self.branch.as_deref(), &options)?;
|
||||
let client = self
|
||||
.sql_client
|
||||
.as_ref()
|
||||
.ok_or_else(|| Error::NotSupported {
|
||||
message: "Optimize jobs require a Flight SQL endpoint".into(),
|
||||
})?;
|
||||
let query = client
|
||||
.execute(crate::database::ExecuteQueryRequest {
|
||||
query: statement,
|
||||
default_namespace_path: self.namespace.clone(),
|
||||
parameters: None,
|
||||
})
|
||||
.await
|
||||
.map_err(optimize::map_optimize_error)?;
|
||||
let mut reader = query.reader().await.map_err(optimize::map_optimize_error)?;
|
||||
let mut batches = Vec::new();
|
||||
while let Some(batch) = reader
|
||||
.try_next()
|
||||
.await
|
||||
.map_err(optimize::map_optimize_error)?
|
||||
{
|
||||
batches.push(batch);
|
||||
}
|
||||
let batches = self.execute_optimize_statement(&options, false).await?;
|
||||
let job_id = optimize::receipt(&batches)?;
|
||||
Ok(Job::new_typed(Box::new(RemoteJob::new(
|
||||
self.client.clone(),
|
||||
@@ -4099,6 +4110,14 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
))))
|
||||
}
|
||||
|
||||
async fn explain_optimize(
|
||||
&self,
|
||||
options: crate::table::OptimizeOverrides,
|
||||
) -> Result<crate::table::OptimizePlan> {
|
||||
let batches = self.execute_optimize_statement(&options, true).await?;
|
||||
optimize::plan(&batches)
|
||||
}
|
||||
|
||||
async fn add_columns(
|
||||
&self,
|
||||
transforms: NewColumnTransform,
|
||||
|
||||
@@ -47,6 +47,24 @@ pub(super) fn receipt(batches: &[arrow_array::RecordBatch]) -> Result<String> {
|
||||
Ok(ids.value(0).into())
|
||||
}
|
||||
|
||||
pub(super) fn plan(batches: &[arrow_array::RecordBatch]) -> Result<crate::table::OptimizePlan> {
|
||||
let plan: crate::table::OptimizePlan = super::preview::decode(batches, "OPTIMIZE")?;
|
||||
let options = &plan.effective_options;
|
||||
if options.target_rows_per_fragment == 0
|
||||
|| options.max_source_rows == Some(0)
|
||||
|| options.batch_size == Some(0)
|
||||
{
|
||||
return Err(Error::Runtime {
|
||||
message: "EXPLAIN OPTIMIZE returned invalid resolved options".into(),
|
||||
});
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
pub(super) fn map_explain_error(error: Error) -> Error {
|
||||
super::preview::map_error(error, "OPTIMIZE", map_optimize_error)
|
||||
}
|
||||
|
||||
pub(super) fn rewrite_sql_options(
|
||||
options: &crate::table::optimize::OptimizeOverrides,
|
||||
) -> Result<Vec<String>> {
|
||||
@@ -336,3 +354,65 @@ mod receipt_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod preview_tests {
|
||||
use super::*;
|
||||
use arrow_array::{ArrayRef, RecordBatch, StringArray};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn payload() -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"format_version": 1, "operation": "rewrite_data", "table": "events",
|
||||
"namespace": ["team"], "branch": "main", "source_version": 42,
|
||||
"effective_options": {"target_rows_per_fragment": 1000, "io_buffer_size": 0,
|
||||
"max_source_rows": null, "batch_size": null},
|
||||
"planned_groups": 0, "planned_fragments": 0, "planned_source_rows": 0,
|
||||
"more_work": false, "future_field": true,
|
||||
})
|
||||
}
|
||||
fn batch(value: serde_json::Value) -> RecordBatch {
|
||||
RecordBatch::try_from_iter([(
|
||||
"plan",
|
||||
Arc::new(StringArray::from(vec![value.to_string()])) as ArrayRef,
|
||||
)])
|
||||
.unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn structured_preview_keeps_known_zero_and_resolved_defaults() {
|
||||
let plan = plan(&[batch(payload())]).unwrap();
|
||||
assert_eq!(plan.source_version, 42);
|
||||
assert_eq!(plan.planned_source_rows, 0);
|
||||
assert_eq!(plan.effective_options.io_buffer_size, Some(0));
|
||||
assert_eq!(plan.effective_options.batch_size, None);
|
||||
assert_eq!(plan.operation, crate::table::OptimizeOperation::RewriteData);
|
||||
}
|
||||
#[test]
|
||||
fn previews_reject_missing_unknown_or_malformed_contracts() {
|
||||
for (key, value) in [
|
||||
("format_version", serde_json::json!(2)),
|
||||
("operation", serde_json::json!("cleanup")),
|
||||
("source_version", serde_json::json!(-1)),
|
||||
("planned_groups", serde_json::json!("unknown")),
|
||||
("effective_options", serde_json::json!({})),
|
||||
] {
|
||||
let mut invalid = payload();
|
||||
invalid[key] = value;
|
||||
assert!(plan(&[batch(invalid)]).is_err(), "{key}");
|
||||
}
|
||||
for key in [
|
||||
"format_version",
|
||||
"operation",
|
||||
"source_version",
|
||||
"planned_source_rows",
|
||||
"more_work",
|
||||
] {
|
||||
let mut invalid = payload();
|
||||
invalid.as_object_mut().unwrap().remove(key);
|
||||
assert!(plan(&[batch(invalid)]).is_err(), "{key}");
|
||||
}
|
||||
let one = batch(payload());
|
||||
assert!(plan(&[]).is_err());
|
||||
assert!(plan(&[one.clone(), one]).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! Shared versioned SQL preview decoding and compatibility diagnostics.
|
||||
|
||||
use arrow_array::{Array, RecordBatch, StringArray};
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
pub(super) fn decode<T: DeserializeOwned>(batches: &[RecordBatch], operation: &str) -> Result<T> {
|
||||
let invalid = || Error::Runtime {
|
||||
message: format!(
|
||||
"EXPLAIN {operation} did not return a valid structured preview; a server supporting EXPLAIN (FORMAT JSON) {operation} is required"
|
||||
),
|
||||
};
|
||||
if batches.iter().map(RecordBatch::num_rows).sum::<usize>() != 1 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let batch = batches
|
||||
.iter()
|
||||
.find(|batch| batch.num_rows() == 1)
|
||||
.ok_or_else(invalid)?;
|
||||
let payload = batch
|
||||
.column_by_name("plan")
|
||||
.and_then(|array| array.as_any().downcast_ref::<StringArray>())
|
||||
.ok_or_else(invalid)?;
|
||||
if payload.is_null(0) {
|
||||
return Err(invalid());
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Preview<T> {
|
||||
format_version: u32,
|
||||
#[serde(flatten)]
|
||||
plan: T,
|
||||
}
|
||||
let preview: Preview<T> = serde_json::from_str(payload.value(0)).map_err(|_| invalid())?;
|
||||
if preview.format_version != 1 {
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(preview.plan)
|
||||
}
|
||||
|
||||
pub(super) fn map_error(error: Error, operation: &str, classify: fn(Error) -> Error) -> Error {
|
||||
fn unsupported_format(error: &Error) -> bool {
|
||||
match error {
|
||||
Error::Sql {
|
||||
message, grpc_code, ..
|
||||
} => {
|
||||
let diagnostic = message.to_ascii_lowercase();
|
||||
// Older servers reject JSON through DataFusion, sometimes as Internal.
|
||||
(*grpc_code == tonic::Code::Internal as i32
|
||||
|| *grpc_code == tonic::Code::InvalidArgument as i32)
|
||||
&& diagnostic.contains("invalid explain format.")
|
||||
&& diagnostic.contains("got 'json'")
|
||||
}
|
||||
Error::JobFailed { failure, .. } => {
|
||||
failure.source.as_deref().is_some_and(unsupported_format)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
let error = if unsupported_format(&error) {
|
||||
Error::NotSupported {
|
||||
message: error.to_string(),
|
||||
}
|
||||
} else {
|
||||
classify(error)
|
||||
};
|
||||
match error {
|
||||
Error::NotSupported { message } => Error::NotSupported {
|
||||
message: format!(
|
||||
"{operation} previews require a server supporting EXPLAIN (FORMAT JSON) {operation}; upgrade the server. Preview will not fall back to text or REST. Server diagnostic: {message}"
|
||||
),
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
@@ -113,73 +113,11 @@ pub(super) fn receipt(batches: &[RecordBatch]) -> Result<(String, u64)> {
|
||||
|
||||
/// Decode the versioned JSON payload without depending on the display text.
|
||||
pub(super) fn plan(batches: &[RecordBatch]) -> Result<crate::table::PrewarmDataPlan> {
|
||||
let invalid = || {
|
||||
Error::Runtime {
|
||||
message: "EXPLAIN PREWARM did not return a valid structured preview; a server supporting EXPLAIN (FORMAT JSON) PREWARM is required".into(),
|
||||
}
|
||||
};
|
||||
if batches.iter().map(RecordBatch::num_rows).sum::<usize>() != 1 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let batch = batches
|
||||
.iter()
|
||||
.find(|batch| batch.num_rows() == 1)
|
||||
.ok_or_else(invalid)?;
|
||||
let payload = batch
|
||||
.column_by_name("plan")
|
||||
.and_then(|array| array.as_any().downcast_ref::<StringArray>())
|
||||
.ok_or_else(invalid)?;
|
||||
if payload.is_null(0) {
|
||||
return Err(invalid());
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Preview {
|
||||
format_version: u32,
|
||||
#[serde(flatten)]
|
||||
plan: crate::table::PrewarmDataPlan,
|
||||
}
|
||||
let preview: Preview = serde_json::from_str(payload.value(0)).map_err(|_| invalid())?;
|
||||
if preview.format_version != 1 {
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(preview.plan)
|
||||
super::preview::decode(batches, "PREWARM")
|
||||
}
|
||||
|
||||
pub(super) fn map_explain_error(error: Error) -> Error {
|
||||
fn unsupported_format(error: &Error) -> bool {
|
||||
match error {
|
||||
Error::Sql {
|
||||
message, grpc_code, ..
|
||||
} => {
|
||||
let diagnostic = message.to_ascii_lowercase();
|
||||
// Older servers hand this EXPLAIN to DataFusion, which rejects
|
||||
// JSON as a configuration error (sometimes gRPC Internal).
|
||||
(*grpc_code == tonic::Code::Internal as i32
|
||||
|| *grpc_code == tonic::Code::InvalidArgument as i32)
|
||||
&& diagnostic.contains("invalid explain format.")
|
||||
&& diagnostic.contains("got 'json'")
|
||||
}
|
||||
Error::JobFailed { failure, .. } => {
|
||||
failure.source.as_deref().is_some_and(unsupported_format)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
let error = if unsupported_format(&error) {
|
||||
Error::NotSupported {
|
||||
message: error.to_string(),
|
||||
}
|
||||
} else {
|
||||
map_error(error)
|
||||
};
|
||||
match error {
|
||||
Error::NotSupported { message } => Error::NotSupported {
|
||||
message: format!(
|
||||
"Data prewarm previews require a server supporting EXPLAIN (FORMAT JSON) PREWARM; upgrade the server. Preview will not fall back to text or REST. Server diagnostic: {message}"
|
||||
),
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
super::preview::map_error(error, "PREWARM", map_error)
|
||||
}
|
||||
|
||||
pub(super) fn map_error(error: Error) -> Error {
|
||||
|
||||
@@ -86,9 +86,9 @@ pub mod freshness;
|
||||
pub mod function_column_status;
|
||||
pub mod merge;
|
||||
pub mod optimize;
|
||||
pub use optimize::OptimizeResult;
|
||||
#[allow(deprecated)]
|
||||
pub use optimize::{CompactionMode, CompactionOptions, CompactionOverrides, CompactionResult};
|
||||
pub use optimize::{OptimizeOperation, OptimizePlan, OptimizeResolvedOptions, OptimizeResult};
|
||||
mod prewarm;
|
||||
pub use prewarm::{PrewarmDataOptions, PrewarmDataPlan, PrewarmDataResult, PrewarmPruningSummary};
|
||||
pub(crate) mod primary_key;
|
||||
@@ -945,6 +945,15 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Preview Enterprise data rewrites without creating a maintenance job.
|
||||
async fn explain_optimize(
|
||||
&self,
|
||||
_options: optimize::OptimizeOverrides,
|
||||
) -> Result<OptimizePlan> {
|
||||
Err(Error::NotSupported {
|
||||
message: "Optimize previews are only supported by LanceDB Enterprise".into(),
|
||||
})
|
||||
}
|
||||
/// Add columns to the table.
|
||||
async fn add_columns(
|
||||
&self,
|
||||
@@ -2176,6 +2185,33 @@ impl Table {
|
||||
self.inner.compact_async(options).await
|
||||
}
|
||||
|
||||
/// Preview Enterprise data rewriting using the same options as [`Self::optimize_async`].
|
||||
///
|
||||
/// Uses `EXPLAIN (FORMAT JSON) OPTIMIZE ... REWRITE DATA`, without creating
|
||||
/// a maintenance job or polling HTTP job APIs. Requires a compatible Enterprise
|
||||
/// server and the SQL preview's Ownership and parent Usage privileges.
|
||||
/// Cleanup, separate index maintenance, Embedded and historical-version handles
|
||||
/// are unsupported. A later submission plans its own source snapshot.
|
||||
///
|
||||
/// ```no_run
|
||||
/// # async fn preview(table: &lancedb::Table) -> lancedb::Result<()> {
|
||||
/// use lancedb::table::optimize::OptimizeOptions;
|
||||
/// let plan = table.explain_optimize(OptimizeOptions {
|
||||
/// max_source_rows: Some(1_000_000), ..Default::default()
|
||||
/// }).await?;
|
||||
/// println!("version={}, rows={}", plan.source_version, plan.planned_source_rows);
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn explain_optimize(
|
||||
&self,
|
||||
options: impl Into<OptimizeAction>,
|
||||
) -> Result<OptimizePlan> {
|
||||
self.inner
|
||||
.explain_optimize(options.into().into_remote_overrides()?)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Language-binding entry point retaining optional compaction fields.
|
||||
#[doc(hidden)]
|
||||
pub async fn optimize_full_with_overrides(
|
||||
|
||||
@@ -248,6 +248,46 @@ pub struct OptimizeResult {
|
||||
pub fragments_removed: Option<u64>,
|
||||
}
|
||||
|
||||
/// Operation covered by an Optimize preview. Cleanup and separate index
|
||||
/// maintenance are not included in a data-rewrite plan.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[non_exhaustive]
|
||||
pub enum OptimizeOperation {
|
||||
/// Rewrite data files while maintaining their index references.
|
||||
RewriteData,
|
||||
}
|
||||
|
||||
/// Effective data-rewrite settings after Enterprise policy resolution.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub struct OptimizeResolvedOptions {
|
||||
pub target_rows_per_fragment: u64,
|
||||
pub max_source_rows: Option<u64>,
|
||||
/// Zero disables byte-based I/O backpressure; None uses the worker default.
|
||||
pub io_buffer_size: Option<u64>,
|
||||
pub batch_size: Option<u64>,
|
||||
}
|
||||
|
||||
/// Non-executing Enterprise Optimize preview for one source snapshot.
|
||||
///
|
||||
/// Counts describe planned work, not committed results, memory use, or runtime.
|
||||
/// A later submission plans its own snapshot and may select different work.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub struct OptimizePlan {
|
||||
pub operation: OptimizeOperation,
|
||||
pub table: String,
|
||||
pub namespace: Vec<String>,
|
||||
pub branch: String,
|
||||
pub source_version: u64,
|
||||
pub effective_options: OptimizeResolvedOptions,
|
||||
pub planned_groups: u64,
|
||||
pub planned_fragments: u64,
|
||||
pub planned_source_rows: u64,
|
||||
pub more_work: bool,
|
||||
}
|
||||
|
||||
struct PrecomputedCompactionPlanner {
|
||||
plan: Mutex<Option<CompactionPlan>>,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user