mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Merge remote-tracking branch 'origin/main' into xuanwo/add-node-version-parity
# Conflicts: # nodejs/src/table.rs
This commit is contained in:
@@ -268,6 +268,38 @@ const after = await table.getRTEStats();
|
||||
|
||||
***
|
||||
|
||||
### cleanupAsync()
|
||||
|
||||
```ts
|
||||
cleanupAsync(_options?): Promise<Job<CleanupResult>>
|
||||
```
|
||||
|
||||
Submit durable remote cleanup through SQL VACUUM and return after acceptance.
|
||||
Requires table Ownership and parent Usage. Retention inherits from the table
|
||||
then deployment when omitted. Local/historical handles are unsupported.
|
||||
Before submission, disable/drain automatic cleanup and prevent other cleanup,
|
||||
tag/branch publication and restore until completion, including direct clients.
|
||||
Coordination is not enforced by the server. Cancellation cannot undo deletion
|
||||
or prove storage I/O stopped. Preview is available without deletion.
|
||||
Wait timeout leaves work running; save the ID and reopen with db.openJob().
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **\_options?**: [`CleanupOptions`](../interfaces/CleanupOptions.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`Job`](Job.md)<[`CleanupResult`](../interfaces/CleanupResult.md)>>
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
const job = await table.cleanupAsync({ minAgeSeconds: 604800 });
|
||||
const result = await job.wait({ timeoutMs: 600000 });
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### close()
|
||||
|
||||
```ts
|
||||
@@ -653,6 +685,24 @@ await table.enableRTE({
|
||||
|
||||
***
|
||||
|
||||
### explainCleanup()
|
||||
|
||||
```ts
|
||||
explainCleanup(_options?): Promise<CleanupPlan>
|
||||
```
|
||||
|
||||
Preview version deletion without creating a job. Execution re-evaluates current state.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **\_options?**: [`CleanupOptions`](../interfaces/CleanupOptions.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`CleanupPlan`](../interfaces/CleanupPlan.md)>
|
||||
|
||||
***
|
||||
|
||||
### explainPrewarmData()
|
||||
|
||||
```ts
|
||||
|
||||
@@ -71,6 +71,9 @@
|
||||
- [CherryPickError](interfaces/CherryPickError.md)
|
||||
- [CherryPickPreview](interfaces/CherryPickPreview.md)
|
||||
- [CherryPickResult](interfaces/CherryPickResult.md)
|
||||
- [CleanupOptions](interfaces/CleanupOptions.md)
|
||||
- [CleanupPlan](interfaces/CleanupPlan.md)
|
||||
- [CleanupResult](interfaces/CleanupResult.md)
|
||||
- [ClientConfig](interfaces/ClientConfig.md)
|
||||
- [ColumnAlteration](interfaces/ColumnAlteration.md)
|
||||
- [ColumnOrdering](interfaces/ColumnOrdering.md)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / CleanupOptions
|
||||
|
||||
# Interface: CleanupOptions
|
||||
|
||||
Per-run retention; omission inherits selected table/branch then deployment policy.
|
||||
|
||||
## Properties
|
||||
|
||||
### minAgeSeconds?
|
||||
|
||||
```ts
|
||||
optional minAgeSeconds: number;
|
||||
```
|
||||
|
||||
Minimum old-version age in seconds. Zero is explicit, not omitted.
|
||||
@@ -0,0 +1,57 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / CleanupPlan
|
||||
|
||||
# Interface: CleanupPlan
|
||||
|
||||
Read-only deletion estimates; no job or deletion snapshot is reserved.
|
||||
|
||||
## Properties
|
||||
|
||||
### bytesToRemove
|
||||
|
||||
```ts
|
||||
bytesToRemove: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### cutoffMillis
|
||||
|
||||
```ts
|
||||
cutoffMillis: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### formatVersion
|
||||
|
||||
```ts
|
||||
formatVersion: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### minAgeSeconds
|
||||
|
||||
```ts
|
||||
minAgeSeconds: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### sourceVersion
|
||||
|
||||
```ts
|
||||
sourceVersion: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### versionsToRemove
|
||||
|
||||
```ts
|
||||
versionsToRemove: number;
|
||||
```
|
||||
@@ -0,0 +1,61 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / CleanupResult
|
||||
|
||||
# Interface: CleanupResult
|
||||
|
||||
Version-deletion outcome. Best-effort auxiliary sweeps are excluded.
|
||||
|
||||
## Properties
|
||||
|
||||
### bytesRemoved
|
||||
|
||||
```ts
|
||||
bytesRemoved: null | number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### failedDeletes
|
||||
|
||||
```ts
|
||||
failedDeletes: null | number;
|
||||
```
|
||||
|
||||
Failed object deletions, if measured. Successful removals are retained.
|
||||
|
||||
***
|
||||
|
||||
### formatVersion
|
||||
|
||||
```ts
|
||||
formatVersion: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### minAgeSeconds
|
||||
|
||||
```ts
|
||||
minAgeSeconds: number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### oldVersions
|
||||
|
||||
```ts
|
||||
oldVersions: null | number;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### statisticsComplete
|
||||
|
||||
```ts
|
||||
statisticsComplete: boolean;
|
||||
```
|
||||
|
||||
False after uncertain retry/recovery; both counts are then null.
|
||||
@@ -1580,6 +1580,10 @@ Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or
|
||||
|
||||
::: lancedb.compaction.CompactionResult
|
||||
|
||||
::: lancedb.cleanup.CleanupPlan
|
||||
|
||||
::: lancedb.cleanup.CleanupResult
|
||||
|
||||
::: lancedb.prewarm.PrewarmDataResult
|
||||
|
||||
::: lancedb.prewarm.PrewarmDataPlan
|
||||
|
||||
@@ -209,6 +209,7 @@ gpu_class = next(
|
||||
@function(
|
||||
gpu=True,
|
||||
gpu_class=gpu_class,
|
||||
row_timeout_seconds=600,
|
||||
pip=["torch==2.12.0", "sentence-transformers==5.7.0"],
|
||||
input_schema=pa.schema([pa.field("text", pa.string(), nullable=True)]),
|
||||
output_schema=pa.list_(pa.float32(), 384),
|
||||
@@ -231,6 +232,15 @@ table.add_columns({"embedding": version(text=col("caption"))})
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
`row_timeout_seconds` sets the per-call deadline, not the `__init__` budget.
|
||||
Current Enterprise builds default to 300 seconds for both CPU and GPU
|
||||
Functions. Enterprise 1.13.0 through 1.14.1, and 1.15.0 builds before the
|
||||
shared default was restored, reject a GPU refresh unless the Function
|
||||
definition or the refresh request sets a positive value; registration still
|
||||
succeeds. A refresh value overrides the definition. Size the deadline from the
|
||||
longest observed call. The 600 seconds above is one working GPU example, not a
|
||||
universal recommendation.
|
||||
|
||||
Older servers that do not implement `GET /v1/gpu/classes` raise
|
||||
`NotImplementedError`. Without `gpu_class`, the deployment's default GPU
|
||||
class is used. The class is immutable with the Function version; set a
|
||||
|
||||
@@ -125,14 +125,19 @@ for the fields, precedence, source-budget planning failures, and compatible-vers
|
||||
they referenced. In LanceDB Embedded, that always happens because you asked
|
||||
for it, through a call to `optimize()`. In LanceDB Enterprise, a
|
||||
[manual `optimize()` call](/maintenance/compaction#enterprise-manual-compaction)
|
||||
submits compaction only. Cleanup remains this planner's own decision, off by
|
||||
default unless the deployment sets a minimum version age:
|
||||
submits compaction only. This planner controls automatic cleanup, which is
|
||||
disabled by default unless the deployment sets a minimum version age:
|
||||
with no minimum age configured, nothing is ever old enough to clean up
|
||||
automatically, and old versions simply accumulate until an operator enables
|
||||
it. A table can also disable it individually even when the deployment allows
|
||||
it, overriding the deployment-wide setting for just that table.
|
||||
automatically. A table can also disable automatic cleanup individually even
|
||||
when the deployment allows it, overriding the deployment-wide setting for
|
||||
just that table.
|
||||
|
||||
Once enabled, a table becomes due for cleanup when any one of these is true:
|
||||
You can [submit manual cleanup](/maintenance/cleanup#enterprise-manual-cleanup)
|
||||
even when automatic cleanup is disabled. Follow the coordination requirements
|
||||
in that guide before submitting a manual run.
|
||||
|
||||
Once automatic cleanup is enabled, a table becomes due when any one of these
|
||||
is true:
|
||||
|
||||
| Trigger | Condition |
|
||||
| --- | --- |
|
||||
|
||||
@@ -17,12 +17,15 @@ those versions referenced.
|
||||
<Note>
|
||||
**Enterprise job type:** `cleanup`. Distinct from `compact`: compaction
|
||||
merges files, cleanup removes them. `optimize()` in LanceDB Embedded runs both in one call;
|
||||
Enterprise schedules them as separate jobs, and runs cleanup only when the
|
||||
deployment's configuration enables it.
|
||||
Enterprise schedules them as separate jobs. Automatic cleanup follows deployment
|
||||
and table policy; authorized manual cleanup can run while automatic cleanup is disabled.
|
||||
</Note>
|
||||
|
||||
## Retention {#retention}
|
||||
|
||||
The Embedded examples below keep their existing behavior. For an explicit
|
||||
Enterprise job, use [manual cleanup](#enterprise-manual-cleanup).
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
from datetime import timedelta
|
||||
@@ -77,6 +80,114 @@ to cover the range you
|
||||
need before running this, not after.
|
||||
</Warning>
|
||||
|
||||
## Enterprise manual cleanup {#enterprise-manual-cleanup}
|
||||
|
||||
Requires compatible SDK and Enterprise query-node, agent and worker releases
|
||||
with SQL `VACUUM` and cleanup result format version 1. Submission requires table
|
||||
Ownership and database/namespace Usage. SDK methods use the table handle's
|
||||
namespace and branch; historical-version handles and LanceDB Embedded are unsupported.
|
||||
|
||||
<Warning>
|
||||
Before submission, disable automatic cleanup for the table and its branches,
|
||||
drain existing cleanup workers, and prevent other cleanup, tag creation/update,
|
||||
branch creation and restore until completion, including direct storage clients.
|
||||
The server does not enforce this coordination. Restore prior scheduling settings
|
||||
afterward. Disabling scheduling or cancelling a job does not prove outstanding
|
||||
storage requests stopped. Concurrent restore can make the current table unreadable.
|
||||
These restrictions apply to every retention value, including zero.
|
||||
</Warning>
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
from datetime import timedelta
|
||||
|
||||
job = table.cleanup_async(min_age_seconds=604800)
|
||||
print(job.id) # Save this durable ID.
|
||||
result = job.wait(timeout=timedelta(minutes=10), progress=print)
|
||||
print(result.old_versions, result.bytes_removed)
|
||||
reopened = db.open_job(job.id)
|
||||
```
|
||||
|
||||
```python Python async icon="python"
|
||||
job = await table.cleanup_async(min_age_seconds=604800)
|
||||
result = await job.wait()
|
||||
reopened = await db.open_job(job.id)
|
||||
```
|
||||
|
||||
```typescript TypeScript icon="js"
|
||||
const job = await table.cleanupAsync({ minAgeSeconds: 604800 });
|
||||
const result = await job.wait({ timeoutMs: 600000, onProgress: console.log });
|
||||
console.log(result.oldVersions, result.bytesRemoved);
|
||||
const reopened = await db.openJob(job.id!);
|
||||
```
|
||||
|
||||
```rust Rust icon="rust"
|
||||
use lancedb::table::{CleanupOptions, CleanupResult};
|
||||
|
||||
let job = table.cleanup_async(CleanupOptions::new().min_age_seconds(604800)).await?;
|
||||
let result = job.wait().await?;
|
||||
println!("{:?} {:?}", result.old_versions, result.bytes_removed);
|
||||
let reopened = db.open_job(job.id().unwrap()).await?.into_typed::<CleanupResult>()?;
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
Submission returns after durable acceptance, before deletion finishes. Omit the
|
||||
retention option to inherit selected table/branch `job_types.cleanup.ttl_seconds`,
|
||||
then deployment retention. Zero is explicit; invalid/missing effective retention
|
||||
fails. The resolved age stays with the job and does not change table policy.
|
||||
The worker calculates its cutoff against latest state at execution; the observed
|
||||
submission version is not a reserved deletion snapshot.
|
||||
|
||||
Status, progress, events, waiting, cancellation and reopening reuse the shared
|
||||
[Job APIs](/basics/jobs) and their existing REST permissions. Describe supports
|
||||
scoped database/namespace Usage; events require system Usage and cancellation
|
||||
requires system Operate. Waiting timeout leaves the job running. Failure or
|
||||
cancellation may follow partial deletion and cannot roll it back.
|
||||
|
||||
`CleanupResult` reports effective retention, `statistics_complete` and optional
|
||||
`old_versions` / `bytes_removed` (`statisticsComplete`, `oldVersions` and
|
||||
`bytesRemoved` in TypeScript). Counts cover version deletion, not best-effort
|
||||
auxiliary sweeps. Unknown totals after retry/recovery remain None/null; measured
|
||||
zero stays zero. `failed_deletes` / `failedDeletes` reports nonfatal object deletion failures
|
||||
when measured; successful removals are retained. Missing or incompatible typed results raise an error rather
|
||||
than inventing counts. Completion does not guarantee every orphaned file was reclaimed.
|
||||
|
||||
Preview deletion using the same options, without creating a job:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
plan = table.explain_cleanup(min_age_seconds=604800)
|
||||
print(plan.source_version, plan.versions_to_remove, plan.bytes_to_remove)
|
||||
# AsyncTable: plan = await table.explain_cleanup(min_age_seconds=604800)
|
||||
```
|
||||
|
||||
```typescript TypeScript icon="js"
|
||||
const plan = await table.explainCleanup({ minAgeSeconds: 604800 });
|
||||
console.log(plan.sourceVersion, plan.versionsToRemove, plan.bytesToRemove);
|
||||
```
|
||||
|
||||
```rust Rust icon="rust"
|
||||
let plan = table.explain_cleanup(CleanupOptions::new().min_age_seconds(604800)).await?;
|
||||
println!("{} {}", plan.versions_to_remove, plan.bytes_to_remove);
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
`CleanupPlan` is a versioned SQL `EXPLAIN (FORMAT JSON) VACUUM` response. It
|
||||
reports observed source version, effective retention, cutoff milliseconds and
|
||||
version/byte deletion estimates. It can list metadata/storage objects but does
|
||||
not delete, submit or monitor a job, expose file paths, or reserve the preview
|
||||
snapshot. Auxiliary sweeps are excluded. Execution re-evaluates latest state;
|
||||
actual removals can differ. `EXPLAIN ANALYZE` is rejected. Read-only preview does
|
||||
not require draining automatic work; actual cleanup still requires coordination.
|
||||
|
||||
The SDK does not fall back to execution/REST or silently drop unsupported
|
||||
options. If acceptance is ambiguous, inspect jobs before retrying; an independent
|
||||
submission can create another job.
|
||||
|
||||
Python's existing Enterprise `cleanup_old_versions()` remains a warning-only
|
||||
no-op for compatibility. Use `cleanup_async()` explicitly to submit a job.
|
||||
Embedded cleanup and Enterprise `optimize()` retain their existing behavior.
|
||||
|
||||
## Managed blob objects {#managed-blobs}
|
||||
|
||||
[Managed blobs](/management/table#managed-blobs) store out-of-line payloads
|
||||
@@ -98,8 +209,8 @@ them, and reopen handles created before that upgrade.
|
||||
For LanceDB Embedded tables, `optimize()` performs compaction and cleanup.
|
||||
Enterprise schedules them as separate background jobs. With compatible releases,
|
||||
remote `optimize()` also submits [manual compaction](/maintenance/compaction#enterprise-manual-compaction),
|
||||
but does not prune versions or remove their files. Cleanup remains governed by
|
||||
the deployment's separate policy.
|
||||
but does not prune versions or remove their files. Automatic cleanup remains governed by
|
||||
the deployment's separate policy; explicit manual cleanup uses the retention rules above.
|
||||
See [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance#cleanup) for the Enterprise path.
|
||||
|
||||
## Disk usage does not drop immediately {#disk}
|
||||
|
||||
@@ -29,6 +29,42 @@ In specific use cases, you may need the flexibility to shuffle, split, and selec
|
||||
functionality `StreamingDataset` is built on. A `Permutation` defines a customizable row ordering, and supports
|
||||
map-style access through `__getitem__()` and batched access through `__getitems__()`.
|
||||
|
||||
## Persisting a permutation {#persisting}
|
||||
|
||||
By default a permutation table is stored in memory. Call `persist` before `execute` to write it to an embedded
|
||||
LanceDB connection backed by local files or object storage. The plan becomes an ordinary table, so another process
|
||||
with access to the same storage can open it and use `Permutation.from_tables` to read the same split.
|
||||
|
||||
<CodeGroup>
|
||||
```py Python icon=Python
|
||||
from lancedb.permutation import Permutation, permutation_builder
|
||||
|
||||
db = lancedb.connect("file://some/db/path")
|
||||
table = db.open_table("some_table")
|
||||
plan = (
|
||||
permutation_builder(table)
|
||||
.split_random(ratios=[0.8, 0.2], seed=42, split_names=["train", "validation"])
|
||||
.persist(db, "splits_v1")
|
||||
.execute()
|
||||
)
|
||||
train = Permutation.from_tables(table, db.open_table("splits_v1"), split="train")
|
||||
print(train.base_version, train.base_branch)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
The table returned by `execute` keeps the destination connection and namespace context, so it can be pickled and
|
||||
reopened directly in a worker process.
|
||||
|
||||
`mode="create"` is the default and fails when the destination table already exists. Pass `mode="overwrite"` to
|
||||
replace it explicitly. Overwriting writes a new table version; readers that already opened the previous version keep
|
||||
reading that snapshot. Use `namespace_path` to create the plan in a namespace. Persisting to LanceDB Enterprise
|
||||
connections is not supported yet, because reproducible Enterprise plan ordering requires deterministic remote row
|
||||
ordering.
|
||||
|
||||
The plan records the base table version and branch in its schema metadata. `Permutation.base_version` and
|
||||
`Permutation.base_branch` read those values without querying the base table; both are `None` for older plans that did
|
||||
not record them.
|
||||
|
||||
## Version Pinning {#version-pinning}
|
||||
|
||||
A `Permutation` is pinned to the version of its base table at the time it was constructed, and every read (including future reads
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import {
|
||||
type CleanupOptions,
|
||||
decodeCleanupPlan,
|
||||
decodeCleanupResult,
|
||||
validateCleanupOptions,
|
||||
} from "../lancedb/cleanup";
|
||||
|
||||
test.each([null, [], 1, true, "options"])(
|
||||
"cleanup rejects malformed options instead of inheriting retention (%p)",
|
||||
(options) => {
|
||||
expect(() =>
|
||||
validateCleanupOptions(options as unknown as CleanupOptions),
|
||||
).toThrow("cleanup options must be an object");
|
||||
},
|
||||
);
|
||||
|
||||
test("cleanup never silently discards an unknown option", () => {
|
||||
expect(() =>
|
||||
validateCleanupOptions({ force: true } as unknown as CleanupOptions),
|
||||
).toThrow("Unknown cleanup option");
|
||||
});
|
||||
|
||||
test.each([undefined, 0, 604800])(
|
||||
"cleanup retention accepts omission and explicit zero (%s)",
|
||||
(age) => {
|
||||
expect(() => validateCleanupOptions({ minAgeSeconds: age })).not.toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
test.each([
|
||||
-1,
|
||||
1.5,
|
||||
Number.NaN,
|
||||
Number.POSITIVE_INFINITY,
|
||||
Number.MAX_SAFE_INTEGER + 1,
|
||||
])("cleanup retention rejects invalid values (%s)", (age) => {
|
||||
expect(() => validateCleanupOptions({ minAgeSeconds: age })).toThrow();
|
||||
});
|
||||
|
||||
test.each([0, 2, null])(
|
||||
"cleanup results distinguish known zero and unknown (%s)",
|
||||
(count) => {
|
||||
const result = decodeCleanupResult(
|
||||
JSON.parse(
|
||||
JSON.stringify({
|
||||
["format_version"]: 1,
|
||||
["min_age_seconds"]: 0,
|
||||
["statistics_complete"]: count !== null,
|
||||
["old_versions"]: count,
|
||||
["bytes_removed"]: count,
|
||||
future: "ignored",
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(result.oldVersions).toBe(count);
|
||||
},
|
||||
);
|
||||
|
||||
test.each([
|
||||
null,
|
||||
{},
|
||||
{ ["format_version"]: 2 },
|
||||
{
|
||||
["format_version"]: 1,
|
||||
["min_age_seconds"]: 0,
|
||||
["statistics_complete"]: false,
|
||||
["old_versions"]: 1,
|
||||
},
|
||||
])("cleanup rejects incompatible results (%p)", (value) => {
|
||||
expect(() => decodeCleanupResult(value)).toThrow();
|
||||
});
|
||||
|
||||
test("cleanup preview validates its versioned contract", () => {
|
||||
const value = JSON.parse(
|
||||
'{"format_version":1,"source_version":42,"min_age_seconds":0,"cutoff_millis":-1,"versions_to_remove":2,"bytes_to_remove":100}',
|
||||
);
|
||||
expect(decodeCleanupPlan(value).versionsToRemove).toBe(2);
|
||||
value.format_version = 2;
|
||||
expect(() => decodeCleanupPlan(value)).toThrow();
|
||||
});
|
||||
@@ -3328,3 +3328,59 @@ describe("table overrides", () => {
|
||||
expect(requests).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cleanup typed results", () => {
|
||||
test.each(["counts", "no_op", "unknown", "missing", "FAILED", "CANCELLED"])(
|
||||
"reopens and waits for cleanup (%s)",
|
||||
async (outcome) => {
|
||||
const known = outcome !== "unknown";
|
||||
await withMockDatabase(
|
||||
(request, response) => {
|
||||
expect(request.url).toBe("/v1/jobs/describe");
|
||||
response.writeHead(200, { "Content-Type": "application/json" });
|
||||
response.end(
|
||||
JSON.stringify({
|
||||
["job_id"]: "cleanup-job",
|
||||
["job_type"]: "cleanup",
|
||||
["job_state"]: ["FAILED", "CANCELLED"].includes(outcome)
|
||||
? outcome
|
||||
: "DONE",
|
||||
result:
|
||||
outcome === "missing"
|
||||
? null
|
||||
: {
|
||||
["format_version"]: 1,
|
||||
["min_age_seconds"]: 0,
|
||||
["statistics_complete"]: known,
|
||||
["old_versions"]: known
|
||||
? outcome === "no_op"
|
||||
? 0
|
||||
: 2
|
||||
: null,
|
||||
["bytes_removed"]: known
|
||||
? outcome === "no_op"
|
||||
? 0
|
||||
: 123
|
||||
: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
},
|
||||
async (db) => {
|
||||
const job =
|
||||
await db.openJob<import("../lancedb").CleanupResult>("cleanup-job");
|
||||
if (["missing", "FAILED", "CANCELLED"].includes(outcome)) {
|
||||
await expect(job.wait()).rejects.toThrow();
|
||||
} else {
|
||||
const result = await job.wait();
|
||||
expect(result.statisticsComplete).toBe(known);
|
||||
expect(result.oldVersions).toBe(
|
||||
known ? (outcome === "no_op" ? 0 : 2) : null,
|
||||
);
|
||||
expect(result.minAgeSeconds).toBe(0);
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
/** Per-run retention; omission inherits selected table/branch then deployment policy. */
|
||||
export interface CleanupOptions {
|
||||
/** Minimum old-version age in seconds. Zero is explicit, not omitted. */
|
||||
minAgeSeconds?: number;
|
||||
}
|
||||
|
||||
/** Version-deletion outcome. Best-effort auxiliary sweeps are excluded. */
|
||||
export interface CleanupResult {
|
||||
formatVersion: number;
|
||||
minAgeSeconds: number;
|
||||
/** False after uncertain retry/recovery; both counts are then null. */
|
||||
statisticsComplete: boolean;
|
||||
oldVersions: number | null;
|
||||
bytesRemoved: number | null;
|
||||
/** Failed object deletions, if measured. Successful removals are retained. */
|
||||
failedDeletes: number | null;
|
||||
}
|
||||
|
||||
/** Read-only deletion estimates; no job or deletion snapshot is reserved. */
|
||||
export interface CleanupPlan {
|
||||
formatVersion: number;
|
||||
sourceVersion: number;
|
||||
minAgeSeconds: number;
|
||||
cutoffMillis: number;
|
||||
versionsToRemove: number;
|
||||
bytesToRemove: number;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function decodeCleanupPlan(value: unknown): CleanupPlan {
|
||||
if (typeof value !== "object" || value === null)
|
||||
throw new Error("invalid cleanup preview");
|
||||
const plan = value as Record<string, unknown>;
|
||||
if (
|
||||
plan.format_version !== 1 ||
|
||||
[
|
||||
"source_version",
|
||||
"min_age_seconds",
|
||||
"cutoff_millis",
|
||||
"versions_to_remove",
|
||||
"bytes_to_remove",
|
||||
].some(
|
||||
(key) =>
|
||||
!Number.isSafeInteger(plan[key]) ||
|
||||
(key !== "cutoff_millis" && (plan[key] as number) < 0),
|
||||
)
|
||||
) {
|
||||
throw new Error("unsupported or invalid cleanup preview");
|
||||
}
|
||||
return {
|
||||
formatVersion: 1,
|
||||
sourceVersion: plan.source_version as number,
|
||||
minAgeSeconds: plan.min_age_seconds as number,
|
||||
cutoffMillis: plan.cutoff_millis as number,
|
||||
versionsToRemove: plan.versions_to_remove as number,
|
||||
bytesToRemove: plan.bytes_to_remove as number,
|
||||
};
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function validateCleanupOptions(options?: CleanupOptions): void {
|
||||
if (
|
||||
options !== undefined &&
|
||||
(typeof options !== "object" || options === null || Array.isArray(options))
|
||||
) {
|
||||
throw new Error("cleanup options must be an object");
|
||||
}
|
||||
for (const key of Object.keys(options ?? {})) {
|
||||
if (key !== "minAgeSeconds")
|
||||
throw new Error(`Unknown cleanup option: ${key}`);
|
||||
}
|
||||
const age = options?.minAgeSeconds;
|
||||
if (age !== undefined && (!Number.isSafeInteger(age) || age < 0)) {
|
||||
throw new Error("minAgeSeconds must be a nonnegative safe integer");
|
||||
}
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function decodeCleanupResult(value: unknown): CleanupResult {
|
||||
if (typeof value !== "object" || value === null)
|
||||
throw new Error("invalid cleanup result");
|
||||
const result = value as Record<string, unknown>;
|
||||
const counts = [result.old_versions ?? null, result.bytes_removed ?? null];
|
||||
const failed = result.failed_deletes ?? null;
|
||||
if (
|
||||
failed !== null &&
|
||||
(!Number.isSafeInteger(failed) ||
|
||||
(failed as number) < 0 ||
|
||||
result.statistics_complete !== true)
|
||||
) {
|
||||
throw new Error("invalid cleanup failed-deletion measurement");
|
||||
}
|
||||
if (
|
||||
result.format_version !== 1 ||
|
||||
typeof result.statistics_complete !== "boolean" ||
|
||||
!Number.isSafeInteger(result.min_age_seconds) ||
|
||||
(result.min_age_seconds as number) < 0 ||
|
||||
counts.some(
|
||||
(count) =>
|
||||
count !== null &&
|
||||
(!Number.isSafeInteger(count) || (count as number) < 0),
|
||||
) ||
|
||||
(result.statistics_complete
|
||||
? counts.some((count) => count === null)
|
||||
: counts.some((count) => count !== null))
|
||||
) {
|
||||
throw new Error("unsupported or inconsistent cleanup result");
|
||||
}
|
||||
return {
|
||||
formatVersion: 1,
|
||||
minAgeSeconds: result.min_age_seconds as number,
|
||||
statisticsComplete: result.statistics_complete,
|
||||
oldVersions: counts[0] as number | null,
|
||||
bytesRemoved: counts[1] as number | null,
|
||||
failedDeletes: (result.failed_deletes as number | null) ?? null,
|
||||
};
|
||||
}
|
||||
@@ -669,6 +669,7 @@ export {
|
||||
export { Listing, ListingOptions } from "./listing";
|
||||
|
||||
export type { CompactionResult } from "./compaction";
|
||||
export type { CleanupOptions, CleanupPlan, CleanupResult } from "./cleanup";
|
||||
|
||||
export type {
|
||||
PrewarmDataPlan,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import { Table as ArrowTable, tableFromIPC } from "apache-arrow";
|
||||
import { decodeCleanupResult } from "./cleanup";
|
||||
import { decodeCompactionResult } from "./compaction";
|
||||
import { JobFailureInfo, Job as NativeJob } from "./native";
|
||||
import { decodePrewarmDataResult } from "./prewarm";
|
||||
@@ -123,7 +124,9 @@ export class Job<T = void> {
|
||||
? (decodePrewarmDataResult as (value: unknown) => T)
|
||||
: inner.jobType === "compact"
|
||||
? (decodeCompactionResult as (value: unknown) => T)
|
||||
: undefined);
|
||||
: inner.jobType === "cleanup"
|
||||
? (decodeCleanupResult as (value: unknown) => T)
|
||||
: undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import {
|
||||
CleanupOptions,
|
||||
CleanupPlan,
|
||||
CleanupResult,
|
||||
decodeCleanupPlan,
|
||||
decodeCleanupResult,
|
||||
validateCleanupOptions,
|
||||
} from "./cleanup";
|
||||
import { CompactionResult, decodeCompactionResult } from "./compaction";
|
||||
import {
|
||||
PrewarmDataPlan,
|
||||
@@ -1341,6 +1349,28 @@ export abstract class Table {
|
||||
* out state and the read_consistency_interval, if any, will apply.
|
||||
*/
|
||||
abstract restore(): Promise<void>;
|
||||
/**
|
||||
* Submit durable remote cleanup through SQL VACUUM and return after acceptance.
|
||||
* Requires table Ownership and parent Usage. Retention inherits from the table
|
||||
* then deployment when omitted. Local/historical handles are unsupported.
|
||||
* Before submission, disable/drain automatic cleanup and prevent other cleanup,
|
||||
* tag/branch publication and restore until completion, including direct clients.
|
||||
* Coordination is not enforced by the server. Cancellation cannot undo deletion
|
||||
* or prove storage I/O stopped. Preview is available without deletion.
|
||||
* Wait timeout leaves work running; save the ID and reopen with db.openJob().
|
||||
* @example
|
||||
* const job = await table.cleanupAsync({ minAgeSeconds: 604800 });
|
||||
* const result = await job.wait({ timeoutMs: 600000 });
|
||||
*/
|
||||
async cleanupAsync(_options?: CleanupOptions): Promise<Job<CleanupResult>> {
|
||||
throw new Error("durable cleanup jobs are only supported on remote tables");
|
||||
}
|
||||
|
||||
/** Preview version deletion without creating a job. Execution re-evaluates current state. */
|
||||
async explainCleanup(_options?: CleanupOptions): Promise<CleanupPlan> {
|
||||
throw new Error("cleanup previews require LanceDB Enterprise");
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit remote compaction and return its durable job after acceptance.
|
||||
*
|
||||
@@ -2091,6 +2121,21 @@ export class LocalTable extends Table {
|
||||
);
|
||||
}
|
||||
|
||||
async cleanupAsync(options?: CleanupOptions): Promise<Job<CleanupResult>> {
|
||||
validateCleanupOptions(options);
|
||||
return new Job(
|
||||
await this.inner.cleanupAsync(options?.minAgeSeconds),
|
||||
decodeCleanupResult,
|
||||
);
|
||||
}
|
||||
|
||||
async explainCleanup(options?: CleanupOptions): Promise<CleanupPlan> {
|
||||
validateCleanupOptions(options);
|
||||
return decodeCleanupPlan(
|
||||
await this.inner.explainCleanup(options?.minAgeSeconds),
|
||||
);
|
||||
}
|
||||
|
||||
async optimize(options?: Partial<OptimizeOptions>): Promise<OptimizeStats> {
|
||||
validateCompactionOptions(options?.compactionOptions);
|
||||
return await this.inner.optimize(
|
||||
|
||||
@@ -572,6 +572,11 @@ impl Connection {
|
||||
job.into_typed::<lancedb::table::PrewarmDataResult>()
|
||||
.default_error()?,
|
||||
))
|
||||
} else if job.job_type().as_deref() == Some("cleanup") {
|
||||
Ok(crate::job::Job::new_typed(
|
||||
job.into_typed::<lancedb::table::CleanupResult>()
|
||||
.default_error()?,
|
||||
))
|
||||
} else if job.job_type().as_deref() == Some("compact") {
|
||||
Ok(crate::job::Job::new_typed(
|
||||
job.into_typed::<lancedb::table::CompactionResult>()
|
||||
|
||||
@@ -1001,6 +1001,33 @@ impl Table {
|
||||
Ok(self.inner_ref()?.current_branch())
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn explain_cleanup(
|
||||
&self,
|
||||
min_age_seconds: Option<f64>,
|
||||
) -> napi::Result<serde_json::Value> {
|
||||
let plan = self
|
||||
.inner_ref()?
|
||||
.explain_cleanup(parse_cleanup_options(min_age_seconds)?)
|
||||
.await
|
||||
.default_error()?;
|
||||
serde_json::to_value(plan).map_err(|error| napi::Error::from_reason(error.to_string()))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn cleanup_async(
|
||||
&self,
|
||||
min_age_seconds: Option<f64>,
|
||||
) -> napi::Result<crate::job::Job> {
|
||||
let options = parse_cleanup_options(min_age_seconds)?;
|
||||
let job = self
|
||||
.inner_ref()?
|
||||
.cleanup_async(options)
|
||||
.await
|
||||
.default_error()?;
|
||||
Ok(crate::job::Job::new_typed(job))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn compact_async(
|
||||
&self,
|
||||
@@ -2600,6 +2627,22 @@ impl Branches {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_cleanup_options(
|
||||
min_age_seconds: Option<f64>,
|
||||
) -> napi::Result<lancedb::table::CleanupOptions> {
|
||||
let mut options = lancedb::table::CleanupOptions::new();
|
||||
if let Some(age) = min_age_seconds {
|
||||
if !age.is_finite() || age.fract() != 0.0 || !(0.0..=9_007_199_254_740_991.0).contains(&age)
|
||||
{
|
||||
return Err(napi::Error::from_reason(
|
||||
"minAgeSeconds must be a nonnegative safe integer",
|
||||
));
|
||||
}
|
||||
options.min_age_seconds = Some(age as u64);
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::from_tag_hint;
|
||||
|
||||
@@ -651,6 +651,7 @@ class Table:
|
||||
async def version(self) -> int: ...
|
||||
async def checkout(self, version: Union[int, str]): ...
|
||||
async def checkout_latest(self): ...
|
||||
async def _checkout_current(self) -> Table: ...
|
||||
async def restore(self, version: Optional[Union[int, str]] = None): ...
|
||||
async def prewarm_index(self, index_name: str) -> None: ...
|
||||
async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: ...
|
||||
@@ -812,6 +813,8 @@ class Table:
|
||||
async def update_field_metadata(
|
||||
self, updates: list[dict[str, Any]]
|
||||
) -> UpdateFieldMetadataResult: ...
|
||||
async def cleanup_async(self, min_age_seconds: Optional[int] = None) -> Job: ...
|
||||
async def explain_cleanup(self, min_age_seconds: Optional[int] = None) -> str: ...
|
||||
async def compact_async(
|
||||
self, compaction_options: Optional[Dict[str, Any]] = None
|
||||
) -> Job: ...
|
||||
@@ -952,6 +955,12 @@ class RecordBatchStream:
|
||||
def __aiter__(self) -> "RecordBatchStream": ...
|
||||
async def __anext__(self) -> pa.RecordBatch: ...
|
||||
|
||||
class SyncRecordBatchStream:
|
||||
@property
|
||||
def schema(self) -> pa.Schema: ...
|
||||
def __iter__(self) -> "SyncRecordBatchStream": ...
|
||||
def __next__(self) -> pa.RecordBatch: ...
|
||||
|
||||
class ColumnOrdering(TypedDict):
|
||||
column_name: str
|
||||
ascending: bool
|
||||
@@ -972,10 +981,14 @@ class Query:
|
||||
def nearest_to(self, query_vec: pa.Array) -> VectorQuery: ...
|
||||
def nearest_to_text(self, query: dict) -> FTSQuery: ...
|
||||
def order_by(self, ordering: Optional[List[ColumnOrdering]]): ...
|
||||
def scan_in_order(self, ordered: bool): ...
|
||||
async def output_schema(self) -> pa.Schema: ...
|
||||
async def execute(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> RecordBatchStream: ...
|
||||
def execute_sync(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> SyncRecordBatchStream: ...
|
||||
async def execute_to_reader(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
@@ -1129,6 +1142,7 @@ class PyQueryRequest:
|
||||
postfilter: Optional[bool]
|
||||
norm: Optional[str]
|
||||
order_by: Optional[List[ColumnOrdering]]
|
||||
scan_in_order: Optional[bool]
|
||||
|
||||
class CompactionStats:
|
||||
fragments_removed: int
|
||||
@@ -1345,6 +1359,14 @@ class AsyncPermutationBuilder:
|
||||
self, seed: Optional[int], clump_size: Optional[int]
|
||||
) -> "AsyncPermutationBuilder": ...
|
||||
def filter(self, filter: str) -> "AsyncPermutationBuilder": ...
|
||||
def persist(
|
||||
self,
|
||||
db: Connection,
|
||||
table_name: str,
|
||||
*,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
mode: str = "create",
|
||||
) -> "AsyncPermutationBuilder": ...
|
||||
async def execute(self) -> Table: ...
|
||||
|
||||
def async_permutation_builder(
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Results of durable remote version cleanup."""
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CleanupResult:
|
||||
"""Version-deletion outcome, excluding best-effort auxiliary sweeps.
|
||||
|
||||
Unknown totals after retry/recovery are None, never fabricated zeroes.
|
||||
Completion does not guarantee that every orphaned file was reclaimed.
|
||||
"""
|
||||
|
||||
format_version: int
|
||||
min_age_seconds: int
|
||||
statistics_complete: bool
|
||||
old_versions: Optional[int] = None
|
||||
bytes_removed: Optional[int] = None
|
||||
failed_deletes: Optional[int] = None
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, raw: str) -> "CleanupResult":
|
||||
"""Decode the versioned contract, preserving unknown measurements."""
|
||||
value = json.loads(raw)
|
||||
if (
|
||||
not isinstance(value, dict)
|
||||
or type(value.get("format_version")) is not int
|
||||
or value["format_version"] != 1
|
||||
):
|
||||
raise ValueError("unsupported cleanup result format")
|
||||
if type(value.get("statistics_complete")) is not bool:
|
||||
raise ValueError("invalid cleanup result statistics_complete")
|
||||
for key in (
|
||||
"min_age_seconds",
|
||||
"old_versions",
|
||||
"bytes_removed",
|
||||
"failed_deletes",
|
||||
):
|
||||
count = value.get(key)
|
||||
if count is None and key != "min_age_seconds":
|
||||
continue
|
||||
if type(count) is not int or count < 0:
|
||||
raise ValueError(f"invalid cleanup result {key}")
|
||||
counts = [value.get("old_versions"), value.get("bytes_removed")]
|
||||
if not value["statistics_complete"] and value.get("failed_deletes") is not None:
|
||||
raise ValueError("inconsistent cleanup failed-deletion measurement")
|
||||
if (
|
||||
value["statistics_complete"] and any(count is None for count in counts)
|
||||
) or (
|
||||
not value["statistics_complete"]
|
||||
and any(count is not None for count in counts)
|
||||
):
|
||||
raise ValueError("inconsistent cleanup result statistics")
|
||||
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 CleanupPlan:
|
||||
"""Read-only version-deletion estimates, excluding auxiliary sweeps.
|
||||
|
||||
No job or deletion snapshot is reserved. Execution plans current state again.
|
||||
"""
|
||||
|
||||
format_version: int
|
||||
source_version: int
|
||||
min_age_seconds: int
|
||||
cutoff_millis: int
|
||||
versions_to_remove: int
|
||||
bytes_to_remove: int
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, raw: str) -> "CleanupPlan":
|
||||
value = json.loads(raw)
|
||||
if not isinstance(value, dict) or value.get("format_version") != 1:
|
||||
raise ValueError("unsupported cleanup preview format")
|
||||
names = {field.name for field in fields(cls)}
|
||||
for name in names:
|
||||
item = value.get(name)
|
||||
if type(item) is not int or (name != "cutoff_millis" and item < 0):
|
||||
raise ValueError(f"invalid cleanup preview {name}")
|
||||
return cls(**{key: item for key, item in value.items() if key in names})
|
||||
|
||||
|
||||
def _validate_min_age_seconds(value: Optional[int]) -> None:
|
||||
if value is not None and (type(value) is not int or value < 0):
|
||||
raise ValueError("min_age_seconds must be a nonnegative integer or None")
|
||||
@@ -3724,7 +3724,11 @@ def function(
|
||||
Positive, finite deadline in seconds for each Python call: one row for
|
||||
scalar Functions and one batch for vectorized Functions. This does not
|
||||
govern class initialization. When omitted, the service applies its
|
||||
default per-call budget.
|
||||
default per-call budget, currently 300 seconds on Enterprise builds.
|
||||
Set it for a GPU Function whose longest call can exceed that budget.
|
||||
Enterprise builds that require an explicit GPU deadline reject a
|
||||
refresh when neither the definition nor the refresh request sets one;
|
||||
a refresh value overrides the definition.
|
||||
retry_policy : FunctionRetryPolicy, optional
|
||||
Retry selected failed calls inside the Function, with bounded attempts
|
||||
and backoff. A refresh may override this default. Retrying a partial
|
||||
@@ -3918,7 +3922,11 @@ __all__ = [
|
||||
|
||||
|
||||
def udf(*args: Any, **kwargs: Any) -> Any:
|
||||
"""Deprecated alias of :func:`function`."""
|
||||
"""Deprecated alias of :func:`function`.
|
||||
|
||||
Accepts the same options, including ``row_timeout_seconds``. See
|
||||
:func:`function` for GPU deadline guidance.
|
||||
"""
|
||||
warnings.warn(
|
||||
"lancedb.udf is deprecated; use lancedb.function",
|
||||
DeprecationWarning,
|
||||
|
||||
@@ -22,6 +22,7 @@ from . import _lancedb
|
||||
from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url
|
||||
from .functions import RefreshColumnResult
|
||||
from .compaction import CompactionResult
|
||||
from .cleanup import CleanupResult
|
||||
from .prewarm import PrewarmDataResult
|
||||
from .remote.errors import HttpError, RetryError
|
||||
|
||||
@@ -858,6 +859,8 @@ def _typed_job(
|
||||
|
||||
|
||||
def _opened_job(inner: "_lancedb.Job") -> AsyncJob:
|
||||
if inner.job_type == "cleanup":
|
||||
return _typed_job(inner, CleanupResult.from_json)
|
||||
if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"):
|
||||
return _typed_job(inner, RefreshColumnResult.from_json)
|
||||
if inner.job_type == "prewarm_page_cache":
|
||||
|
||||
@@ -510,8 +510,8 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
|
||||
- "QueryTable": Execute queries on the namespace server via
|
||||
namespace.query_table() instead of locally. Queries with a
|
||||
nonempty ``order_by`` execute locally and require the client to
|
||||
access the table storage.
|
||||
nonempty ``order_by`` or an explicit ``scan_in_order(True)``
|
||||
execute on the client and require access to the table storage.
|
||||
- "CreateTable": Execute table creation on the namespace server via
|
||||
namespace.create_table() instead of using declare_table + local write.
|
||||
|
||||
@@ -1215,8 +1215,8 @@ class AsyncLanceNamespaceDBConnection:
|
||||
|
||||
- "QueryTable": Execute queries on the namespace server via
|
||||
namespace.query_table() instead of locally. Queries with a
|
||||
nonempty ``order_by`` execute locally and require the client to
|
||||
access the table storage.
|
||||
nonempty ``order_by`` or an explicit ``scan_in_order(True)``
|
||||
execute on the client and require access to the table storage.
|
||||
- "CreateTable": Execute table creation on the namespace server via
|
||||
namespace.create_table() instead of using declare_table + local write.
|
||||
|
||||
@@ -1824,8 +1824,8 @@ def connect_namespace(
|
||||
|
||||
- "QueryTable": Execute queries on the namespace server via
|
||||
namespace.query_table() instead of locally. Queries with a nonempty
|
||||
``order_by`` execute locally and require the client to access the
|
||||
table storage.
|
||||
``order_by`` or an explicit ``scan_in_order(True)`` execute on the
|
||||
client and require access to the table storage.
|
||||
- "CreateTable": Execute table creation on the namespace server via
|
||||
namespace.create_table() instead of using declare_table + local write.
|
||||
|
||||
@@ -1917,8 +1917,8 @@ def connect_namespace_async(
|
||||
|
||||
- "QueryTable": Execute queries on the namespace server via
|
||||
namespace.query_table() instead of locally. Queries with a nonempty
|
||||
``order_by`` execute locally and require the client to access the
|
||||
table storage.
|
||||
``order_by`` or an explicit ``scan_in_order(True)`` execute on the
|
||||
client and require access to the table storage.
|
||||
- "CreateTable": Execute table creation on the namespace server via
|
||||
namespace.create_table() instead of using declare_table + local write.
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import os
|
||||
from deprecation import deprecated
|
||||
import pyarrow as pa
|
||||
|
||||
from ._lancedb import Connection as NativeConnection
|
||||
from ._lancedb import async_permutation_builder, PermutationReader
|
||||
from .table import LanceTable, Table
|
||||
from .background_loop import LOOP
|
||||
@@ -16,11 +17,26 @@ from .util import (
|
||||
batch_to_tensor_columns,
|
||||
batch_to_tensor_dict,
|
||||
batch_to_tensor_rows,
|
||||
get_uri_scheme,
|
||||
)
|
||||
from typing import Any, Callable, Iterator, Literal, Optional, TYPE_CHECKING, Union
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from lancedb.dependencies import pandas as pd, numpy as np, polars as pl
|
||||
from .db import DBConnection
|
||||
|
||||
|
||||
def _native_connection(db: Any) -> Any:
|
||||
"""Return the native connection wrapped by a sync or async connection."""
|
||||
async_connection = getattr(db, "_conn", None)
|
||||
if async_connection is not None:
|
||||
return _native_connection(async_connection)
|
||||
inner = getattr(db, "_inner", None)
|
||||
if inner is not None:
|
||||
return _native_connection(inner)
|
||||
if isinstance(db, NativeConnection):
|
||||
return db
|
||||
raise TypeError("db must be a LanceDB connection")
|
||||
|
||||
|
||||
class PermutationBuilder:
|
||||
@@ -43,7 +59,9 @@ class PermutationBuilder:
|
||||
be referenced by name in the future. If names are not provided then they can only
|
||||
be referenced by their ordinal index. There is no requirement to name every split.
|
||||
|
||||
The permutation is stored in memory and will be lost when the program exits.
|
||||
The permutation is stored in memory and will be lost when the program exits,
|
||||
unless [persist][lancedb.permutation.PermutationBuilder.persist] is called before
|
||||
[execute][lancedb.permutation.PermutationBuilder.execute].
|
||||
"""
|
||||
|
||||
def __init__(self, table: Table):
|
||||
@@ -56,6 +74,9 @@ class PermutationBuilder:
|
||||
Tables with an RTE write spec are rejected: unflushed rows have no row id.
|
||||
"""
|
||||
self._async = async_permutation_builder(table)
|
||||
self._persist_connection: Optional[Any] = None
|
||||
self._persist_table_name: Optional[str] = None
|
||||
self._persist_namespace_path: list[str] = []
|
||||
|
||||
def split_random(
|
||||
self,
|
||||
@@ -262,6 +283,76 @@ class PermutationBuilder:
|
||||
self._async.filter(filter)
|
||||
return self
|
||||
|
||||
def persist(
|
||||
self,
|
||||
db: "DBConnection",
|
||||
table_name: str,
|
||||
*,
|
||||
namespace_path: Optional[list[str]] = None,
|
||||
mode: Literal["create", "overwrite"] = "create",
|
||||
) -> "PermutationBuilder":
|
||||
"""
|
||||
Store the permutation table in an embedded database.
|
||||
|
||||
Persisting a plan makes the same split available to another process or
|
||||
another machine with access to the destination storage. The plan is an
|
||||
ordinary LanceDB table containing row ids and split ids; it can be
|
||||
opened with [open_table][lancedb.db.DBConnection.open_table] and passed to
|
||||
[Permutation.from_tables][lancedb.permutation.Permutation.from_tables].
|
||||
The table returned by ``execute`` keeps the destination connection and
|
||||
namespace context, so it can be pickled and reopened directly.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
db: DBConnection
|
||||
An embedded LanceDB connection. Local files and object storage are
|
||||
supported; LanceDB Enterprise connections are not supported yet.
|
||||
table_name: str
|
||||
The name of the permutation table to create.
|
||||
namespace_path: list[str], optional
|
||||
The namespace to create the table in. The default is the root
|
||||
namespace.
|
||||
mode: {"create", "overwrite"}, default "create"
|
||||
``create`` fails if the destination table already exists.
|
||||
``overwrite`` writes a new version of the table. Readers that already
|
||||
opened the previous version keep reading that snapshot.
|
||||
|
||||
Returns
|
||||
-------
|
||||
PermutationBuilder
|
||||
This builder, so ``persist`` can be chained with the split, filter,
|
||||
and execute methods.
|
||||
"""
|
||||
if mode not in ("create", "overwrite"):
|
||||
raise ValueError(f"Invalid mode {mode!r}; expected 'create' or 'overwrite'")
|
||||
|
||||
uri = getattr(db, "uri", None)
|
||||
if uri is None:
|
||||
raise TypeError("db must be a LanceDB connection")
|
||||
if get_uri_scheme(str(uri)) == "db":
|
||||
raise NotImplementedError(
|
||||
"Permutation persistence is not supported for LanceDB Enterprise "
|
||||
"connections yet; reproducible Enterprise plan ordering requires "
|
||||
"deterministic remote row ordering."
|
||||
)
|
||||
|
||||
if namespace_path is None:
|
||||
namespace_path = []
|
||||
elif not isinstance(namespace_path, (list, tuple)):
|
||||
raise TypeError("namespace_path must be a list of strings or None")
|
||||
|
||||
namespace_path = list(namespace_path)
|
||||
self._async.persist(
|
||||
_native_connection(db),
|
||||
table_name,
|
||||
namespace_path=namespace_path,
|
||||
mode=mode,
|
||||
)
|
||||
self._persist_connection = db
|
||||
self._persist_table_name = table_name
|
||||
self._persist_namespace_path = namespace_path
|
||||
return self
|
||||
|
||||
def execute(self) -> LanceTable:
|
||||
"""
|
||||
Execute the configuration and create the permutation table.
|
||||
@@ -269,7 +360,14 @@ class PermutationBuilder:
|
||||
|
||||
async def do_execute():
|
||||
inner_tbl = await self._async.execute()
|
||||
return await LanceTable.from_inner(inner_tbl)
|
||||
if self._persist_connection is None:
|
||||
return await LanceTable.from_inner(inner_tbl)
|
||||
return await LanceTable.from_inner(
|
||||
inner_tbl,
|
||||
connection=self._persist_connection,
|
||||
name=self._persist_table_name,
|
||||
namespace_path=self._persist_namespace_path,
|
||||
)
|
||||
|
||||
return LOOP.run(do_execute())
|
||||
|
||||
@@ -411,6 +509,11 @@ class Transforms:
|
||||
DEFAULT_BATCH_SIZE = 100
|
||||
|
||||
|
||||
def _is_persisted_plan(table: Table) -> bool:
|
||||
"""Whether a permutation table lives in reopenable storage rather than memory."""
|
||||
return isinstance(table, LanceTable) and not table._conn.uri.startswith("memory://")
|
||||
|
||||
|
||||
def _table_to_pickle_state(table: Table) -> dict[str, Any]:
|
||||
from .remote.table import RemoteTable
|
||||
|
||||
@@ -497,6 +600,9 @@ class Permutation:
|
||||
limit: Optional[int] = None,
|
||||
connection_factory: Optional[Callable[[str], Table]] = None,
|
||||
_reader: Optional[PermutationReader] = None,
|
||||
_plan_metadata: Optional[dict[bytes, bytes]] = None,
|
||||
_plan_version: Optional[int] = None,
|
||||
_plan_branch: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
Internal constructor. Use
|
||||
@@ -513,6 +619,9 @@ class Permutation:
|
||||
self.offset = offset
|
||||
self.limit = limit
|
||||
self.connection_factory = connection_factory
|
||||
self._plan_metadata = _plan_metadata
|
||||
self._plan_version = _plan_version
|
||||
self._plan_branch = _plan_branch
|
||||
if _reader is None:
|
||||
_reader = LOOP.run(self._build_reader())
|
||||
self.reader: PermutationReader = _reader
|
||||
@@ -652,6 +761,17 @@ class Permutation:
|
||||
then the first split will be used.
|
||||
"""
|
||||
assert base_table is not None, "base_table is required"
|
||||
persisted_plan = permutation_table is not None and _is_persisted_plan(
|
||||
permutation_table
|
||||
)
|
||||
if persisted_plan:
|
||||
# Pin before reading metadata or constructing the reader. The caller's
|
||||
# handle may keep tracking latest, but the live reader and pickle must
|
||||
# share one immutable plan snapshot.
|
||||
permutation_table = permutation_table._pin_current_snapshot()
|
||||
plan_metadata = None if permutation_table is not None else {}
|
||||
if permutation_table is not None and (isinstance(split, str) or persisted_plan):
|
||||
plan_metadata = dict(permutation_table.schema.metadata or {})
|
||||
if split is not None:
|
||||
if permutation_table is None:
|
||||
raise ValueError(
|
||||
@@ -659,12 +779,7 @@ class Permutation:
|
||||
" because no permutation table is provided"
|
||||
)
|
||||
if isinstance(split, str):
|
||||
if permutation_table.schema.metadata is None:
|
||||
raise ValueError(
|
||||
f"Cannot create a permutation on split `{split}`"
|
||||
" because no split names are defined in the permutation table"
|
||||
)
|
||||
raw = permutation_table.schema.metadata.get(b"split_names")
|
||||
raw = (plan_metadata or {}).get(b"split_names")
|
||||
split_names = raw.decode("utf-8") if raw is not None else None
|
||||
if split_names is None:
|
||||
raise ValueError(
|
||||
@@ -687,6 +802,14 @@ class Permutation:
|
||||
else:
|
||||
split = 0
|
||||
|
||||
plan_version = None
|
||||
plan_branch = None
|
||||
if persisted_plan:
|
||||
# Pin the pickled plan to the snapshot this object was created from,
|
||||
# not what the destination name points at after an overwrite.
|
||||
plan_version = permutation_table.version
|
||||
plan_branch = permutation_table.current_branch()
|
||||
|
||||
async def do_from_tables():
|
||||
reader = await PermutationReader.from_tables(
|
||||
base_table, permutation_table, split
|
||||
@@ -701,6 +824,9 @@ class Permutation:
|
||||
DEFAULT_BATCH_SIZE,
|
||||
Transforms.arrow2python,
|
||||
_reader=reader,
|
||||
_plan_metadata=plan_metadata,
|
||||
_plan_version=plan_version,
|
||||
_plan_branch=plan_branch,
|
||||
)
|
||||
|
||||
return LOOP.run(do_from_tables())
|
||||
@@ -710,18 +836,43 @@ class Permutation:
|
||||
|
||||
The base table is captured either via a user-supplied
|
||||
``connection_factory`` (see [with_connection_factory]) or, as a
|
||||
fallback, by the table's own picklable reopen state. The permutation
|
||||
table is captured as a pyarrow Table (which pickles via Arrow IPC
|
||||
natively). The reader is dropped from the wire format and rebuilt
|
||||
lazily on first use.
|
||||
fallback, by the table's own picklable reopen state. A permutation
|
||||
table in memory is captured as a pyarrow Table (which pickles via Arrow
|
||||
IPC natively). A persisted plan is reopened by reference and pinned to
|
||||
the plan snapshot this object was built from. The reader is dropped
|
||||
from the wire format and rebuilt lazily on first use.
|
||||
"""
|
||||
base_table_state = (
|
||||
None
|
||||
if self.connection_factory is not None
|
||||
else _table_to_pickle_state(self.base_table)
|
||||
)
|
||||
base_is_memory = (
|
||||
base_table_state is not None and base_table_state["kind"] == "memory"
|
||||
)
|
||||
|
||||
permutation_data: Optional[pa.Table] = None
|
||||
if self.permutation_table is not None:
|
||||
permutation_table_state: Optional[dict[str, Any]] = None
|
||||
if (
|
||||
self.permutation_table is not None
|
||||
and _is_persisted_plan(self.permutation_table)
|
||||
and not base_is_memory
|
||||
):
|
||||
plan_state = _table_to_pickle_state(self.permutation_table)
|
||||
# Keep the plan's own branch/version coordinate. A later overwrite
|
||||
# of the destination must not change what this pickle reads.
|
||||
table_state = plan_state["state"]
|
||||
if self._plan_version is not None:
|
||||
table_state["checkout_version"] = self._plan_version
|
||||
# None is the main branch. Restore it explicitly because the
|
||||
# live handle may have moved to another branch since capture.
|
||||
table_state["branch"] = self._plan_branch
|
||||
permutation_table_state = plan_state
|
||||
elif self.permutation_table is not None:
|
||||
permutation_data = self.permutation_table.to_arrow()
|
||||
|
||||
common = {
|
||||
"base_table_name": self.base_table.name,
|
||||
"permutation_data": permutation_data,
|
||||
"split": self.split,
|
||||
"selection": self.selection,
|
||||
"batch_size": self.batch_size,
|
||||
@@ -730,17 +881,13 @@ class Permutation:
|
||||
"limit": self.limit,
|
||||
"connection_factory": self.connection_factory,
|
||||
}
|
||||
|
||||
if self.connection_factory is not None:
|
||||
# The factory carries enough state to recover the base table on
|
||||
# its own; we don't need to capture the URI / storage options /
|
||||
# namespace from the existing connection.
|
||||
return common
|
||||
|
||||
return {
|
||||
**common,
|
||||
"base_table_state": _table_to_pickle_state(self.base_table),
|
||||
}
|
||||
if permutation_table_state is not None:
|
||||
common["permutation_table_state"] = permutation_table_state
|
||||
else:
|
||||
common["permutation_data"] = permutation_data
|
||||
if base_table_state is not None:
|
||||
common["base_table_state"] = base_table_state
|
||||
return common
|
||||
|
||||
def __setstate__(self, state: dict[str, Any]) -> None:
|
||||
from . import connect
|
||||
@@ -772,17 +919,32 @@ class Permutation:
|
||||
)
|
||||
|
||||
permutation_table: Optional[Table] = None
|
||||
permutation_data = state["permutation_data"]
|
||||
if permutation_data is not None:
|
||||
if rebuilt_base:
|
||||
# The base table was materialized from Arrow, so it is a fresh
|
||||
# single-version dataset and the recorded pin cannot resolve on it.
|
||||
permutation_data = _drop_base_version(permutation_data)
|
||||
mem_db = connect("memory://")
|
||||
permutation_table = mem_db.create_table("permutation", permutation_data)
|
||||
plan_metadata: dict[bytes, bytes] = {}
|
||||
plan_version = None
|
||||
plan_branch = None
|
||||
if "permutation_table_state" in state:
|
||||
plan_state = state["permutation_table_state"]
|
||||
permutation_table = _table_from_pickle_state(plan_state)
|
||||
nested_state = plan_state.get("state", {})
|
||||
plan_version = nested_state.get("checkout_version")
|
||||
plan_branch = nested_state.get("branch")
|
||||
plan_metadata = dict(permutation_table.schema.metadata or {})
|
||||
else:
|
||||
permutation_data = state.get("permutation_data")
|
||||
if permutation_data is not None:
|
||||
if rebuilt_base:
|
||||
# The base table was materialized from Arrow, so it is a fresh
|
||||
# single-version dataset and the recorded pin cannot resolve on it.
|
||||
permutation_data = _drop_base_version(permutation_data)
|
||||
mem_db = connect("memory://")
|
||||
permutation_table = mem_db.create_table("permutation", permutation_data)
|
||||
plan_metadata = dict(permutation_table.schema.metadata or {})
|
||||
|
||||
self.base_table = base_table
|
||||
self.permutation_table = permutation_table
|
||||
self._plan_metadata = plan_metadata
|
||||
self._plan_version = plan_version
|
||||
self._plan_branch = plan_branch
|
||||
self.split = state["split"]
|
||||
self.selection = state["selection"]
|
||||
self.batch_size = state["batch_size"]
|
||||
@@ -807,6 +969,44 @@ class Permutation:
|
||||
new.__dict__ = self.__dict__.copy()
|
||||
return new
|
||||
|
||||
def _loaded_plan_metadata(self) -> dict[bytes, bytes]:
|
||||
if self._plan_metadata is None:
|
||||
self._plan_metadata = (
|
||||
dict(self.permutation_table.schema.metadata or {})
|
||||
if self.permutation_table is not None
|
||||
else {}
|
||||
)
|
||||
return self._plan_metadata
|
||||
|
||||
@property
|
||||
def base_version(self) -> Optional[int]:
|
||||
"""The base table version recorded in the plan, or ``None`` for legacy plans.
|
||||
|
||||
This value comes from the plan's schema metadata, so reading it does not
|
||||
query the base table. Version numbers are per-branch; see
|
||||
[base_branch][lancedb.permutation.Permutation.base_branch].
|
||||
"""
|
||||
raw = self._loaded_plan_metadata().get(b"base_version")
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError as error:
|
||||
raise ValueError(
|
||||
f"Permutation table has an unreadable base_version of {raw!r}"
|
||||
) from error
|
||||
|
||||
@property
|
||||
def base_branch(self) -> Optional[str]:
|
||||
"""The base table branch recorded in the plan, or ``None`` for main.
|
||||
|
||||
Legacy plans recorded no branch and therefore also return ``None``.
|
||||
"""
|
||||
raw = self._loaded_plan_metadata().get(b"base_branch")
|
||||
if raw is None:
|
||||
return None
|
||||
return raw.decode("utf-8")
|
||||
|
||||
def _ensure_open(self) -> None:
|
||||
pid = os.getpid()
|
||||
if self.reader is not None and getattr(self, "_pid", None) == pid:
|
||||
|
||||
@@ -371,6 +371,10 @@ def _scanner_kwargs_for_query(
|
||||
"with_row_id": with_row_id if with_row_id is not None else query.with_row_id,
|
||||
"with_row_address": query.with_row_address,
|
||||
"fast_search": query.fast_search,
|
||||
"scan_in_order": query.scan_in_order,
|
||||
# Legacy scalar-index plans can reorder rows. Explicit storage order
|
||||
# evaluates filters over the manifest-ordered scan instead.
|
||||
"use_scalar_index": False if query.scan_in_order is True else None,
|
||||
"blob_handling": BLOB_MODE_TO_HANDLING[blob_mode],
|
||||
"fragments": fragments,
|
||||
}
|
||||
@@ -381,6 +385,12 @@ def _scanner_fragments_for_query(query: Query, dataset: Optional[Any]) -> Option
|
||||
if query.fragments is not None and query.fragment_ids is not None:
|
||||
raise ValueError("fragments and fragment_ids cannot both be set")
|
||||
if query.fragments is not None:
|
||||
if query.scan_in_order is True:
|
||||
raise ValueError(
|
||||
"scan_in_order(True) cannot validate with_fragments() against "
|
||||
"the scanned dataset version; use fragment_ids() to select "
|
||||
"fragments by manifest id"
|
||||
)
|
||||
return query.fragments
|
||||
if query.fragment_ids is None:
|
||||
return None
|
||||
@@ -1208,6 +1218,10 @@ class Query(pydantic.BaseModel):
|
||||
|
||||
order_by: Optional[List[ColumnOrdering]] = None
|
||||
|
||||
# Tri-state storage-order requirement: None preserves the backend default,
|
||||
# True requires manifest order, False allows an unordered scan.
|
||||
scan_in_order: Optional[bool] = None
|
||||
|
||||
@classmethod
|
||||
def from_inner(cls, req: PyQueryRequest) -> Self:
|
||||
query = cls()
|
||||
@@ -1241,6 +1255,7 @@ class Query(pydantic.BaseModel):
|
||||
query.postfilter = req.postfilter
|
||||
if req.order_by is not None:
|
||||
query.order_by = [ColumnOrdering(**o) for o in req.order_by]
|
||||
query.scan_in_order = req.scan_in_order
|
||||
if req.full_text_search is not None:
|
||||
query.full_text_query = FullTextSearchQuery(
|
||||
columns=None,
|
||||
@@ -1415,6 +1430,7 @@ class LanceQueryBuilder(ABC):
|
||||
self._approx_mode = None
|
||||
self._bypass_vector_index = None
|
||||
self._order_by = None
|
||||
self._scan_in_order = None
|
||||
|
||||
@deprecation.deprecated(
|
||||
deprecated_in="0.3.1",
|
||||
@@ -1834,7 +1850,14 @@ class LanceQueryBuilder(ABC):
|
||||
) -> pa.RecordBatchReader:
|
||||
query = self._query_for_scan(blob_sources, schema)
|
||||
reader = self._execute_query_prepared(
|
||||
query, batch_size=batch_size, timeout=timeout
|
||||
query,
|
||||
batch_size=batch_size,
|
||||
timeout=timeout,
|
||||
pull_reader=(
|
||||
blob_mode == "lazy"
|
||||
and _query_is_plain_scan(query)
|
||||
and not _query_needs_lance_scanner(self)
|
||||
),
|
||||
)
|
||||
return self._batches_in_mode(reader, blob_mode, blob_sources, schema)
|
||||
|
||||
@@ -1844,9 +1867,19 @@ class LanceQueryBuilder(ABC):
|
||||
*,
|
||||
batch_size: Optional[int] = None,
|
||||
timeout: Optional[timedelta] = None,
|
||||
pull_reader: bool = False,
|
||||
) -> pa.RecordBatchReader:
|
||||
if not _is_remote_query_table(self._table):
|
||||
query._blob_row_id_prepared = True
|
||||
if (
|
||||
pull_reader
|
||||
and not _is_remote_query_table(self._table)
|
||||
and not self._table.namespace
|
||||
and getattr(self._table, "_namespace_client", None) is None
|
||||
):
|
||||
return self._table._execute_pull_query(
|
||||
query, batch_size=batch_size, timeout=timeout
|
||||
)
|
||||
return self._table._execute_query(query, batch_size=batch_size, timeout=timeout)
|
||||
|
||||
def _execute_arrow_prepared(
|
||||
@@ -2023,7 +2056,9 @@ class LanceQueryBuilder(ABC):
|
||||
----------
|
||||
fragments : list[lance.Fragment]
|
||||
Fragments from ``table.to_lance().get_fragments()``. Pass fragments
|
||||
from the same dataset snapshot.
|
||||
from the same dataset snapshot. Use ``fragment_ids()`` instead when
|
||||
``scan_in_order(True)`` is set; fragment objects cannot be validated
|
||||
against the pinned dataset version.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -3082,6 +3117,52 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
def scan_in_order(self, ordered: bool = True) -> Self:
|
||||
"""Control whether an ordinary scan must preserve storage order.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ordered: bool, default True
|
||||
``True`` requires manifest order: fragments in manifest order, then
|
||||
rows in fragment order. ``False`` allows the backend to scan
|
||||
unordered. Leave the method uncalled to preserve the backend
|
||||
default.
|
||||
|
||||
An unfiltered plain base-only scan of an Embedded table, pinned to one
|
||||
dataset version, returns manifest order by default. RTE tables scan the
|
||||
LSM by default and do not provide this guarantee unless
|
||||
``use_rte(False)`` selects the base table. Explicit ``True`` also
|
||||
disables scalar-index filter planning, because legacy scalar-index plans
|
||||
can return a different sequence; default filtered scans can still use
|
||||
those plans and may not preserve manifest order. Filters still apply,
|
||||
but the scan can read more data. ``with_fragments()`` is not supported
|
||||
with ``True`` because fragment objects cannot be validated against the
|
||||
pinned dataset version; use ``fragment_ids()`` instead, which resolves
|
||||
ids from the manifest and remains ordered. Compaction, updates, or
|
||||
opening a newer version can change that order, so pin the table version
|
||||
when positions must remain stable across executions. An explicit
|
||||
``order_by()`` replaces manifest order with a global sort, and vector,
|
||||
full-text, hybrid, or reranked queries return ranked results; combining
|
||||
those with ``scan_in_order(True)`` raises ``ValueError``. Enterprise
|
||||
tables and RTE/LSM reads raise ``NotImplementedError`` because they
|
||||
cannot uphold the order; set ``use_rte(False)`` to read the RTE base
|
||||
table in storage order. When ``QueryTable`` pushdown is enabled, the
|
||||
backend default may not preserve order; requesting ``True`` executes
|
||||
against Embedded storage instead, because the namespace request has no
|
||||
order field.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import lancedb
|
||||
>>> db = lancedb.connect("memory://")
|
||||
>>> table = db.create_table("scan_in_order", [{"id": 1}])
|
||||
>>> query = table.search().scan_in_order(True).select(["id"])
|
||||
>>> query.to_arrow()["id"].to_pylist()
|
||||
[1]
|
||||
"""
|
||||
self._scan_in_order = ordered
|
||||
return self
|
||||
|
||||
def to_query_object(self) -> Query:
|
||||
return Query(
|
||||
columns=self._columns,
|
||||
@@ -3094,6 +3175,7 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
|
||||
use_rte=self._use_rte,
|
||||
offset=self._offset,
|
||||
order_by=self._order_by,
|
||||
scan_in_order=self._scan_in_order,
|
||||
)
|
||||
|
||||
def output_schema(self) -> pa.Schema:
|
||||
@@ -4142,7 +4224,9 @@ class AsyncQueryBase(object):
|
||||
query types. Other terminals and remote tables raise
|
||||
``NotImplementedError`` before scanning instead of silently scanning
|
||||
the full table. Blob-specific ``to_pandas()`` fallbacks keep their
|
||||
existing validation errors.
|
||||
existing validation errors. Use ``fragment_ids()`` instead when
|
||||
``scan_in_order(True)`` is set; fragment objects cannot be validated
|
||||
against the pinned dataset version.
|
||||
"""
|
||||
self._fragments = fragments
|
||||
return self
|
||||
@@ -4866,6 +4950,72 @@ class AsyncQuery(AsyncStandardQuery):
|
||||
super().__init__(inner, table)
|
||||
self._inner = inner
|
||||
|
||||
def _execute_batches_sync(
|
||||
self,
|
||||
*,
|
||||
max_batch_length: Optional[int] = None,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.RecordBatchReader:
|
||||
"""Execute a plain local scan with one Rust fetch per batch.
|
||||
|
||||
The query starts once; each iteration asks the same Rust stream for a
|
||||
single batch instead of submitting one Python future per batch to the
|
||||
background event loop. The public reader type and schema come from the
|
||||
same stream, so Arrow export and exception behavior stay unchanged.
|
||||
"""
|
||||
self._ensure_fragment_constraints_supported("to_batches()")
|
||||
stream = self._inner.execute_sync(max_batch_length, timeout)
|
||||
return pa.RecordBatchReader.from_batches(stream.schema, stream)
|
||||
|
||||
def scan_in_order(self, ordered: bool = True) -> Self:
|
||||
"""Control whether an ordinary scan must preserve storage order.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ordered: bool, default True
|
||||
``True`` requires manifest order: fragments in manifest order, then
|
||||
rows in fragment order. ``False`` allows the backend to scan
|
||||
unordered. Leave the method uncalled to preserve the backend
|
||||
default.
|
||||
|
||||
An unfiltered plain base-only scan of an Embedded table, pinned to one
|
||||
dataset version, returns manifest order by default. RTE tables scan the
|
||||
LSM by default and do not provide this guarantee unless
|
||||
``use_rte(False)`` selects the base table. Explicit ``True`` also
|
||||
disables scalar-index filter planning, because legacy scalar-index plans
|
||||
can return a different sequence; default filtered scans can still use
|
||||
those plans and may not preserve manifest order. Filters still apply,
|
||||
but the scan can read more data. ``with_fragments()`` is not supported
|
||||
with ``True`` because fragment objects cannot be validated against the
|
||||
pinned dataset version; use ``fragment_ids()`` instead, which resolves
|
||||
ids from the manifest and remains ordered. Compaction, updates, or
|
||||
opening a newer version can change that order, so pin the table version
|
||||
when positions must remain stable across executions. An explicit
|
||||
``order_by()`` replaces manifest order with a global sort, and vector,
|
||||
full-text, hybrid, or reranked queries return ranked results; combining
|
||||
those with ``scan_in_order(True)`` raises ``ValueError``. Enterprise
|
||||
tables and RTE/LSM reads raise ``NotImplementedError`` because they
|
||||
cannot uphold the order; set ``use_rte(False)`` to read the RTE base
|
||||
table in storage order. When ``QueryTable`` pushdown is enabled, the
|
||||
backend default may not preserve order; requesting ``True`` executes
|
||||
against Embedded storage instead, because the namespace request has no
|
||||
order field.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import asyncio
|
||||
>>> import lancedb
|
||||
>>> async def example():
|
||||
... db = await lancedb.connect_async("memory://")
|
||||
... table = await db.create_table("scan_in_order_async", [{"id": 1}])
|
||||
... query = table.query().scan_in_order(True).select(["id"])
|
||||
... return (await query.to_arrow())["id"].to_pylist()
|
||||
>>> asyncio.run(example())
|
||||
[1]
|
||||
"""
|
||||
self._inner.scan_in_order(ordered)
|
||||
return self
|
||||
|
||||
@classmethod
|
||||
def _query_vec_to_array(self, vec: Union[VEC, Tuple]):
|
||||
if isinstance(vec, list):
|
||||
|
||||
@@ -50,6 +50,7 @@ from lancedb.index import (
|
||||
LabelList,
|
||||
)
|
||||
from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
|
||||
from lancedb.cleanup import CleanupPlan, CleanupResult
|
||||
from lancedb.job import Job
|
||||
from lancedb.functions import (
|
||||
FunctionProvenance,
|
||||
@@ -1101,7 +1102,8 @@ class RemoteTable(Table):
|
||||
cleanup_old_versions() is a no-op in LanceDB Enterprise.
|
||||
"""
|
||||
warnings.warn(
|
||||
"cleanup_old_versions() is a no-op in LanceDB Enterprise.",
|
||||
"cleanup_old_versions() is a no-op in LanceDB Enterprise. "
|
||||
"Use cleanup_async() to submit durable cleanup explicitly.",
|
||||
stacklevel=2,
|
||||
)
|
||||
pass
|
||||
@@ -1116,6 +1118,19 @@ class RemoteTable(Table):
|
||||
)
|
||||
pass
|
||||
|
||||
def explain_cleanup(self, *, min_age_seconds: Optional[int] = None) -> CleanupPlan:
|
||||
"""Preview cleanup without submitting a job or deleting files."""
|
||||
return LOOP.run(self._table.explain_cleanup(min_age_seconds=min_age_seconds))
|
||||
|
||||
def cleanup_async(
|
||||
self, *, min_age_seconds: Optional[int] = None
|
||||
) -> Job[CleanupResult]:
|
||||
"""Submit cleanup. See
|
||||
|
||||
[Table.cleanup_async][lancedb.table.Table.cleanup_async].
|
||||
"""
|
||||
return Job(LOOP.run(self._table.cleanup_async(min_age_seconds=min_age_seconds)))
|
||||
|
||||
def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[CompactionResult]:
|
||||
|
||||
@@ -52,6 +52,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
|
||||
from lancedb.cleanup import CleanupPlan, CleanupResult, _validate_min_age_seconds
|
||||
from .dependencies import (
|
||||
_check_for_hugging_face,
|
||||
_check_for_lance,
|
||||
@@ -149,6 +150,9 @@ def _requires_local_namespace_execution(query: Query) -> bool:
|
||||
# The namespace QueryTable request has no order_by field. Pushing a
|
||||
# nonempty ordering down would drop it and return the wrong top-K rows.
|
||||
or bool(query.order_by)
|
||||
# An ordered scan is a local manifest-order guarantee. The request has
|
||||
# no scan-order field, so run it locally where storage is available.
|
||||
or query.scan_in_order is True
|
||||
or (
|
||||
query.full_text_query is not None
|
||||
and query.fast_search is True
|
||||
@@ -2958,6 +2962,16 @@ class Table(ABC):
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.RecordBatchReader: ...
|
||||
|
||||
def _execute_pull_query(
|
||||
self,
|
||||
query: Query,
|
||||
*,
|
||||
batch_size: Optional[int] = None,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.RecordBatchReader:
|
||||
"""Execute a pull-driven batch query, falling back to the normal path."""
|
||||
return self._execute_query(query, batch_size=batch_size, timeout=timeout)
|
||||
|
||||
def _execute_arrow(
|
||||
self,
|
||||
query: Query,
|
||||
@@ -3181,6 +3195,38 @@ class Table(ABC):
|
||||
compaction for you automatically.
|
||||
"""
|
||||
|
||||
def explain_cleanup(self, *, min_age_seconds: Optional[int] = None) -> CleanupPlan:
|
||||
"""Preview version deletion without submitting a job or deleting files.
|
||||
|
||||
Uses the same retention, branch and Ownership boundary as cleanup_async.
|
||||
Estimates exclude auxiliary sweeps and reserve no snapshot for execution.
|
||||
"""
|
||||
raise NotImplementedError("cleanup previews require LanceDB Enterprise")
|
||||
|
||||
def cleanup_async(
|
||||
self, *, min_age_seconds: Optional[int] = None
|
||||
) -> Job[CleanupResult]:
|
||||
"""Submit durable remote version cleanup through SQL VACUUM.
|
||||
|
||||
Omitted retention inherits selected table/branch then deployment policy.
|
||||
Requires Ownership and parent Usage. Local/historical handles are unsupported.
|
||||
Disable/drain automatic cleanup and prevent other cleanup, tag/branch
|
||||
publication and restore until completion, including direct storage clients.
|
||||
The server does not enforce coordination. Cancellation cannot undo deletion
|
||||
or prove storage I/O stopped. Preview is available without deletion.
|
||||
|
||||
Save ``job.id`` to reopen with ``db.open_job(id)``. Waiting returns
|
||||
[CleanupResult][lancedb.cleanup.CleanupResult]; timeout leaves work running.
|
||||
Unknown totals after retry/recovery remain None. Auxiliary sweeps are
|
||||
best effort and excluded from the version-deletion counts.
|
||||
|
||||
>>> job = table.cleanup_async(min_age_seconds=604800) # doctest: +SKIP
|
||||
>>> result = job.wait() # doctest: +SKIP
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
"durable cleanup jobs are only supported on remote tables"
|
||||
)
|
||||
|
||||
def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[CompactionResult]:
|
||||
@@ -4424,10 +4470,40 @@ class LanceTable(Table):
|
||||
return self._namespace_path
|
||||
|
||||
@classmethod
|
||||
async def from_inner(cls, tbl: LanceDBTable):
|
||||
async def from_inner(
|
||||
cls,
|
||||
tbl: LanceDBTable,
|
||||
*,
|
||||
connection: Optional["DBConnection"] = None,
|
||||
name: Optional[str] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
location: Optional[str] = None,
|
||||
):
|
||||
async_tbl = AsyncTable(tbl)
|
||||
if connection is not None:
|
||||
# A table created through a Python connection keeps that
|
||||
# connection's explicit options. Reconstructing a bare connection
|
||||
# from the native handle loses namespace, storage, manifest and
|
||||
# Session state needed by pickle.
|
||||
return cls(
|
||||
connection,
|
||||
name or async_tbl.name,
|
||||
namespace_path=namespace_path,
|
||||
storage_options=getattr(connection, "storage_options", None),
|
||||
location=location,
|
||||
namespace_client=getattr(connection, "_namespace_client", None),
|
||||
managed_versioning=getattr(connection, "_managed_versioning", None),
|
||||
pushdown_operations=getattr(
|
||||
connection, "_namespace_client_pushdown_operations", None
|
||||
),
|
||||
route_pushdown_to_rust=getattr(
|
||||
connection, "_route_pushdown_to_rust", False
|
||||
),
|
||||
_async=async_tbl,
|
||||
)
|
||||
|
||||
from .db import AsyncConnection, LanceDBConnection
|
||||
|
||||
async_tbl = AsyncTable(tbl)
|
||||
inner_conn = tbl.database()
|
||||
read_consistency_interval = await AsyncConnection(
|
||||
inner_conn
|
||||
@@ -4657,6 +4733,16 @@ class LanceTable(Table):
|
||||
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
|
||||
return self._table.current_branch()
|
||||
|
||||
def _pin_current_snapshot(self) -> "LanceTable":
|
||||
"""Return an independent handle pinned to this table's current snapshot."""
|
||||
|
||||
async def do_pin():
|
||||
pinned = await self._table._checkout_current()
|
||||
return pinned, await pinned.version()
|
||||
|
||||
pinned, version = LOOP.run(do_pin())
|
||||
return self._wrap_branch_handle(pinned, version)
|
||||
|
||||
def _wrap_branch_handle(
|
||||
self, async_table: "AsyncTable", version: Optional[int] = None
|
||||
) -> "LanceTable":
|
||||
@@ -6044,6 +6130,27 @@ class LanceTable(Table):
|
||||
|
||||
return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync())
|
||||
|
||||
def _execute_pull_query(
|
||||
self,
|
||||
query: Query,
|
||||
*,
|
||||
batch_size: Optional[int] = None,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.RecordBatchReader:
|
||||
"""Execute a plain local scan with one Rust fetch per batch.
|
||||
|
||||
The caller has already checked that this is an embedded, non-namespace
|
||||
plain lazy scan. A query shape that does not map to ``AsyncQuery``
|
||||
keeps the existing reader path instead of guessing at its semantics.
|
||||
"""
|
||||
async_query = self._table._sync_query_to_async(query)
|
||||
async_query._blob_row_id_prepared = query._blob_row_id_prepared
|
||||
if isinstance(async_query, AsyncQuery):
|
||||
return async_query._execute_batches_sync(
|
||||
max_batch_length=batch_size, timeout=timeout
|
||||
)
|
||||
return self._execute_query(query, batch_size=batch_size, timeout=timeout)
|
||||
|
||||
def _execute_arrow(
|
||||
self,
|
||||
query: Query,
|
||||
@@ -6166,6 +6273,14 @@ class LanceTable(Table):
|
||||
LOOP.run(self._table.compact_async(compaction_options=compaction_options))
|
||||
)
|
||||
|
||||
def explain_cleanup(self, *, min_age_seconds: Optional[int] = None) -> CleanupPlan:
|
||||
return LOOP.run(self._table.explain_cleanup(min_age_seconds=min_age_seconds))
|
||||
|
||||
def cleanup_async(
|
||||
self, *, min_age_seconds: Optional[int] = None
|
||||
) -> Job[CleanupResult]:
|
||||
return Job(LOOP.run(self._table.cleanup_async(min_age_seconds=min_age_seconds)))
|
||||
|
||||
def optimize(
|
||||
self,
|
||||
*,
|
||||
@@ -8529,6 +8644,8 @@ class AsyncTable:
|
||||
async_query = async_query.with_row_id()
|
||||
if query.order_by:
|
||||
async_query = async_query.order_by(query.order_by)
|
||||
if query.scan_in_order is not None:
|
||||
async_query = async_query.scan_in_order(query.scan_in_order)
|
||||
|
||||
if query.vector:
|
||||
async_query = async_query.nearest_to(query.vector).distance_range(
|
||||
@@ -9628,6 +9745,10 @@ class AsyncTable:
|
||||
"""
|
||||
return await self._inner.version()
|
||||
|
||||
async def _checkout_current(self) -> "AsyncTable":
|
||||
"""Return an independent handle pinned to the currently selected snapshot."""
|
||||
return AsyncTable(await self._inner._checkout_current())
|
||||
|
||||
async def list_versions(self):
|
||||
"""
|
||||
List all versions of the table
|
||||
@@ -9903,6 +10024,25 @@ class AsyncTable:
|
||||
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
|
||||
return self._inner.current_branch()
|
||||
|
||||
async def explain_cleanup(
|
||||
self, *, min_age_seconds: Optional[int] = None
|
||||
) -> CleanupPlan:
|
||||
"""Read-only preview; see Table.explain_cleanup."""
|
||||
_validate_min_age_seconds(min_age_seconds)
|
||||
return CleanupPlan.from_json(await self._inner.explain_cleanup(min_age_seconds))
|
||||
|
||||
async def cleanup_async(
|
||||
self, *, min_age_seconds: Optional[int] = None
|
||||
) -> AsyncJob[CleanupResult]:
|
||||
"""Submit cleanup. See
|
||||
|
||||
[Table.cleanup_async][lancedb.table.Table.cleanup_async].
|
||||
"""
|
||||
_validate_min_age_seconds(min_age_seconds)
|
||||
return _typed_job(
|
||||
await self._inner.cleanup_async(min_age_seconds), CleanupResult.from_json
|
||||
)
|
||||
|
||||
async def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> AsyncJob[CompactionResult]:
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
import traceback
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -14,7 +12,7 @@ import pytest
|
||||
BACKGROUND_THREAD_NAME = "LanceDBBackgroundEventLoop"
|
||||
|
||||
|
||||
def _run_in_subprocess(code: str) -> subprocess.CompletedProcess:
|
||||
def _run_in_subprocess(code: str, timeout: int = 30) -> subprocess.CompletedProcess:
|
||||
env = os.environ.copy()
|
||||
env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path)
|
||||
return subprocess.run(
|
||||
@@ -23,7 +21,7 @@ def _run_in_subprocess(code: str) -> subprocess.CompletedProcess:
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env=env,
|
||||
timeout=30,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
@@ -142,45 +140,6 @@ def test_concurrent_first_use_initializes_one_background_thread():
|
||||
_assert_subprocess_ok(result)
|
||||
|
||||
|
||||
def _fork_child_starts_lazily(queue):
|
||||
def background_threads():
|
||||
import threading
|
||||
|
||||
return [
|
||||
thread
|
||||
for thread in threading.enumerate()
|
||||
if thread.name == BACKGROUND_THREAD_NAME
|
||||
]
|
||||
|
||||
try:
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
inherited_thread_is_none = LOOP.thread is None
|
||||
inherited_loop_is_none = LOOP.loop is None
|
||||
background_threads_before = [thread.name for thread in background_threads()]
|
||||
|
||||
import lancedb
|
||||
|
||||
db = lancedb.connect("memory://")
|
||||
tables = db.table_names()
|
||||
|
||||
worker = LOOP.thread
|
||||
queue.put(
|
||||
{
|
||||
"error": None,
|
||||
"inherited_thread_is_none": inherited_thread_is_none,
|
||||
"inherited_loop_is_none": inherited_loop_is_none,
|
||||
"background_threads_before": background_threads_before,
|
||||
"tables": tables,
|
||||
"thread_alive": False if worker is None else worker.is_alive(),
|
||||
"thread_daemon": False if worker is None else worker.daemon,
|
||||
"background_thread_count": len(background_threads()),
|
||||
}
|
||||
)
|
||||
except BaseException:
|
||||
queue.put({"error": traceback.format_exc()})
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
sys.platform != "linux",
|
||||
reason=(
|
||||
@@ -189,48 +148,100 @@ def _fork_child_starts_lazily(queue):
|
||||
),
|
||||
)
|
||||
def test_forked_child_starts_background_loop_lazily():
|
||||
import asyncio
|
||||
# Fork from a fresh interpreter: earlier tests in a shared pytest process
|
||||
# may have left native runtime state that is not part of this scenario.
|
||||
result = _run_in_subprocess(
|
||||
f"""
|
||||
import asyncio
|
||||
import multiprocessing as mp
|
||||
import threading
|
||||
import traceback
|
||||
|
||||
from lancedb.background_loop import LOOP
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before"
|
||||
parent_thread = LOOP.thread
|
||||
assert parent_thread is not None
|
||||
BACKGROUND_THREAD_NAME = {BACKGROUND_THREAD_NAME!r}
|
||||
|
||||
ctx = mp.get_context("fork")
|
||||
queue = ctx.Queue()
|
||||
def background_threads():
|
||||
return [
|
||||
thread
|
||||
for thread in threading.enumerate()
|
||||
if thread.name == BACKGROUND_THREAD_NAME
|
||||
]
|
||||
|
||||
# Simulate forking while another thread held the initialization lock. The
|
||||
# child must replace the inherited lock instead of trying to acquire it.
|
||||
LOOP._start_lock.acquire()
|
||||
try:
|
||||
proc = ctx.Process(target=_fork_child_starts_lazily, args=(queue,))
|
||||
proc.start()
|
||||
finally:
|
||||
LOOP._start_lock.release()
|
||||
def fork_child(queue):
|
||||
try:
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
proc.join(timeout=20)
|
||||
if proc.is_alive():
|
||||
proc.terminate()
|
||||
proc.join(timeout=5)
|
||||
inherited_thread_is_none = LOOP.thread is None
|
||||
inherited_loop_is_none = LOOP.loop is None
|
||||
background_threads_before = [
|
||||
thread.name for thread in background_threads()
|
||||
]
|
||||
|
||||
import lancedb
|
||||
|
||||
db = lancedb.connect("memory://")
|
||||
tables = db.table_names()
|
||||
|
||||
worker = LOOP.thread
|
||||
queue.put(
|
||||
dict(
|
||||
error=None,
|
||||
inherited_thread_is_none=inherited_thread_is_none,
|
||||
inherited_loop_is_none=inherited_loop_is_none,
|
||||
background_threads_before=background_threads_before,
|
||||
tables=tables,
|
||||
thread_alive=False if worker is None else worker.is_alive(),
|
||||
thread_daemon=False if worker is None else worker.daemon,
|
||||
background_thread_count=len(background_threads()),
|
||||
)
|
||||
)
|
||||
except BaseException:
|
||||
queue.put(dict(error=traceback.format_exc()))
|
||||
|
||||
assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before"
|
||||
parent_thread = LOOP.thread
|
||||
assert parent_thread is not None
|
||||
|
||||
ctx = mp.get_context("fork")
|
||||
queue = ctx.Queue()
|
||||
|
||||
# Simulate forking while another thread held the initialization lock. The
|
||||
# child must replace the inherited lock instead of trying to acquire it.
|
||||
LOOP._start_lock.acquire()
|
||||
try:
|
||||
proc = ctx.Process(target=fork_child, args=(queue,))
|
||||
proc.start()
|
||||
finally:
|
||||
LOOP._start_lock.release()
|
||||
|
||||
proc.join(timeout=20)
|
||||
if proc.is_alive():
|
||||
proc.kill()
|
||||
proc.join()
|
||||
pytest.fail("Forked child hung starting the background loop")
|
||||
proc.terminate()
|
||||
proc.join(timeout=5)
|
||||
if proc.is_alive():
|
||||
proc.kill()
|
||||
proc.join()
|
||||
raise AssertionError("Forked child hung starting the background loop")
|
||||
|
||||
assert proc.exitcode == 0, f"child exited with code {proc.exitcode}"
|
||||
payload = queue.get(timeout=5)
|
||||
queue.close()
|
||||
assert payload["error"] is None, payload["error"]
|
||||
assert payload["inherited_thread_is_none"] is True
|
||||
assert payload["inherited_loop_is_none"] is True
|
||||
assert payload["background_threads_before"] == []
|
||||
assert payload["tables"] == []
|
||||
assert payload["thread_alive"] is True
|
||||
assert payload["thread_daemon"] is True
|
||||
assert payload["background_thread_count"] == 1
|
||||
assert proc.exitcode == 0, "child exited with code %s" % proc.exitcode
|
||||
payload = queue.get(timeout=5)
|
||||
queue.close()
|
||||
assert payload["error"] is None, payload["error"]
|
||||
assert payload["inherited_thread_is_none"] is True
|
||||
assert payload["inherited_loop_is_none"] is True
|
||||
assert payload["background_threads_before"] == []
|
||||
assert payload["tables"] == []
|
||||
assert payload["thread_alive"] is True
|
||||
assert payload["thread_daemon"] is True
|
||||
assert payload["background_thread_count"] == 1
|
||||
|
||||
# The child's reset must not disturb the parent's loop.
|
||||
assert LOOP.thread is parent_thread
|
||||
assert parent_thread.is_alive()
|
||||
assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after"
|
||||
# The child's reset must not disturb the parent's loop.
|
||||
assert LOOP.thread is parent_thread
|
||||
assert parent_thread.is_alive()
|
||||
assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after"
|
||||
""",
|
||||
# join(20) + terminate join(5) + queue get(5), plus startup and traceback.
|
||||
timeout=40,
|
||||
)
|
||||
_assert_subprocess_ok(result)
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
from lancedb.cleanup import CleanupResult
|
||||
from test_remote_db import _create_table_handler, _mock_remote_sql_connection
|
||||
|
||||
|
||||
@pytest.mark.parametrize("counts", [(0, 0), (2, 123), (None, None)])
|
||||
def test_cleanup_result_preserves_measurements(counts):
|
||||
versions, size = counts
|
||||
result = CleanupResult.from_json(
|
||||
json.dumps(
|
||||
{
|
||||
"format_version": 1,
|
||||
"min_age_seconds": 0,
|
||||
"statistics_complete": versions is not None,
|
||||
"old_versions": versions,
|
||||
"bytes_removed": size,
|
||||
"future": True,
|
||||
}
|
||||
)
|
||||
)
|
||||
assert result.old_versions == versions
|
||||
assert result.bytes_removed == size
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[
|
||||
None,
|
||||
{},
|
||||
{"format_version": 2},
|
||||
{
|
||||
"format_version": 1,
|
||||
"min_age_seconds": 0,
|
||||
"statistics_complete": False,
|
||||
"old_versions": 1,
|
||||
},
|
||||
],
|
||||
)
|
||||
def test_cleanup_result_rejects_missing_unknown_or_inconsistent_contract(payload):
|
||||
with pytest.raises(ValueError):
|
||||
CleanupResult.from_json(json.dumps(payload))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"outcome", ["counts", "no_op", "unknown", "missing", "FAILED", "CANCELLED"]
|
||||
)
|
||||
async def test_cleanup_submission_wait_and_reopen(asynchronous, outcome):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
polls = []
|
||||
result = {
|
||||
"format_version": 1,
|
||||
"min_age_seconds": 0,
|
||||
"statistics_complete": outcome != "unknown",
|
||||
"old_versions": None
|
||||
if outcome == "unknown"
|
||||
else 0
|
||||
if outcome == "no_op"
|
||||
else 2,
|
||||
"bytes_removed": None
|
||||
if outcome == "unknown"
|
||||
else 0
|
||||
if outcome == "no_op"
|
||||
else 123,
|
||||
}
|
||||
|
||||
class Server(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.tickets = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.tickets.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(pa.table({"job_id": ["cleanup-job"]}))
|
||||
|
||||
def handler(request):
|
||||
if request.path != "/v1/jobs/describe":
|
||||
return _create_table_handler(request)
|
||||
polls.append(
|
||||
json.loads(request.rfile.read(int(request.headers["Content-Length"])))
|
||||
)
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.end_headers()
|
||||
request.wfile.write(
|
||||
json.dumps(
|
||||
{
|
||||
"job_id": "cleanup-job",
|
||||
"job_type": "cleanup",
|
||||
"job_state": outcome
|
||||
if outcome in ("FAILED", "CANCELLED")
|
||||
else "DONE",
|
||||
"result": None if outcome == "missing" else result,
|
||||
}
|
||||
).encode()
|
||||
)
|
||||
|
||||
server = Server()
|
||||
with _mock_remote_sql_connection(server, handler) as kwargs:
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
job = await table.cleanup_async(min_age_seconds=0)
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
job = table.cleanup_async(min_age_seconds=0)
|
||||
assert job.id == "cleanup-job" and not polls
|
||||
if outcome in ("missing", "FAILED", "CANCELLED"):
|
||||
with pytest.raises(
|
||||
Exception,
|
||||
match={
|
||||
"missing": "did not contain a result",
|
||||
"FAILED": "failed",
|
||||
"CANCELLED": "cancel",
|
||||
}[outcome],
|
||||
):
|
||||
if asynchronous:
|
||||
await job.wait()
|
||||
else:
|
||||
job.wait()
|
||||
else:
|
||||
stats = await job.wait() if asynchronous else job.wait()
|
||||
assert isinstance(stats, CleanupResult)
|
||||
assert stats.old_versions == result["old_versions"]
|
||||
reopened = (
|
||||
await db.open_job(job.id) if asynchronous else db.open_job(job.id)
|
||||
)
|
||||
assert (await reopened.wait() if asynchronous else reopened.wait()) == stats
|
||||
assert len(server.tickets) == 1
|
||||
assert b"VACUUM" in server.tickets[0]
|
||||
assert b"min_age_seconds = 0" in server.tickets[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
async def test_cleanup_preview_is_read_only(asynchronous):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
payload = {
|
||||
"format_version": 1,
|
||||
"source_version": 42,
|
||||
"min_age_seconds": 0,
|
||||
"cutoff_millis": 123,
|
||||
"versions_to_remove": 2,
|
||||
"bytes_to_remove": 100,
|
||||
}
|
||||
|
||||
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(payload)]})
|
||||
)
|
||||
|
||||
def handler(request):
|
||||
assert not request.path.startswith("/v1/jobs"), (
|
||||
"preview must not submit/monitor jobs"
|
||||
)
|
||||
return _create_table_handler(request)
|
||||
|
||||
server = Server()
|
||||
with _mock_remote_sql_connection(server, handler) as kwargs:
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
plan = await table.explain_cleanup(min_age_seconds=0)
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
plan = table.explain_cleanup(min_age_seconds=0)
|
||||
assert plan.source_version == 42
|
||||
assert plan.versions_to_remove == 2
|
||||
assert len(server.tickets) == 1
|
||||
assert b"EXPLAIN (FORMAT JSON) VACUUM" in server.tickets[0]
|
||||
@@ -241,6 +241,25 @@ def test_lsm_read_sees_active_memtable(tmp_path):
|
||||
assert sorted(base_only["id"].to_pylist()) == [1, 2, 3]
|
||||
|
||||
|
||||
def test_lsm_read_to_batches_sees_active_memtable(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3])) # base ids 1,2,3
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_rte(RTEWriteSpec.unsharded())
|
||||
|
||||
_lsm_upsert(table, [4, 5]) # active memtable only, not committed to base
|
||||
|
||||
# The sync batch reader keeps the default LSM route and its pending writes.
|
||||
lsm = pa.Table.from_batches(list(table.search().to_batches(batch_size=2)))
|
||||
assert sorted(lsm["id"].to_pylist()) == [1, 2, 3, 4, 5]
|
||||
|
||||
# use_rte(False) still takes the base-only escape hatch through to_batches.
|
||||
base_only = pa.Table.from_batches(
|
||||
list(table.search().use_rte(False).to_batches(batch_size=2))
|
||||
)
|
||||
assert sorted(base_only["id"].to_pylist()) == [1, 2, 3]
|
||||
|
||||
|
||||
def test_lsm_read_dedup_newest_wins(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3])) # id 2 -> value 1
|
||||
|
||||
@@ -1789,6 +1789,31 @@ class TestPushdownOperations:
|
||||
assert result.column("id").to_pylist() == [1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
def test_lance_table_scan_in_order_is_not_pushed_down(self, tmp_path):
|
||||
namespace_client = _NamespaceClient()
|
||||
db = lancedb.connect(str(tmp_path / "db"))
|
||||
table = db.create_table("hist", data=[{"id": 3}, {"id": 1}])
|
||||
table.add([{"id": 2}])
|
||||
table._namespace_path = ["geneva"]
|
||||
table._namespace_client = namespace_client
|
||||
table._pushdown_operations = {"QueryTable"}
|
||||
table._route_pushdown_to_rust = False
|
||||
|
||||
result = table._execute_query(
|
||||
Query(
|
||||
limit=2,
|
||||
filter="id >= 1",
|
||||
columns=["id"],
|
||||
scan_in_order=True,
|
||||
)
|
||||
).read_all()
|
||||
|
||||
# The namespace request has no scan-order field. Local execution keeps
|
||||
# membership order, projection and limit; a dropped order or a sort
|
||||
# would return [1, 3] or [1, 2].
|
||||
assert result.column("id").to_pylist() == [3, 1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestAsyncPushdownOperations:
|
||||
@@ -1869,6 +1894,29 @@ class TestAsyncPushdownOperations:
|
||||
assert pa.Table.from_batches(batches).column("id").to_pylist() == [1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
async def test_async_table_scan_in_order_is_not_pushed_down(self, tmp_path):
|
||||
namespace_client = _NamespaceClient()
|
||||
db = await lancedb.connect_async(str(tmp_path / "db"))
|
||||
table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}])
|
||||
await table.add([{"id": 2}])
|
||||
table._namespace_path = ["geneva"]
|
||||
table._namespace_client = namespace_client
|
||||
table._pushdown_operations = {"QueryTable"}
|
||||
table._route_pushdown_to_rust = False
|
||||
|
||||
result = await table._execute_query(
|
||||
Query(
|
||||
limit=2,
|
||||
filter="id >= 1",
|
||||
columns=["id"],
|
||||
scan_in_order=True,
|
||||
)
|
||||
)
|
||||
|
||||
batches = await result.read_all()
|
||||
assert pa.Table.from_batches(batches).column("id").to_pylist() == [3, 1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query_kwargs",
|
||||
[
|
||||
|
||||
@@ -5,7 +5,7 @@ import pyarrow as pa
|
||||
import math
|
||||
import pytest
|
||||
|
||||
from lancedb import DBConnection, Table, connect
|
||||
from lancedb import DBConnection, Session, Table, connect, connect_namespace
|
||||
from lancedb.background_loop import LOOP
|
||||
from lancedb.permutation import (
|
||||
DEFAULT_BATCH_SIZE,
|
||||
@@ -21,6 +21,18 @@ from utils import (
|
||||
)
|
||||
|
||||
|
||||
def _read_permutation_in_spawned_process(payload: bytes, output) -> None:
|
||||
import pickle
|
||||
|
||||
permutation = pickle.loads(payload)
|
||||
output.put(
|
||||
[
|
||||
row["id"]
|
||||
for row in permutation.__getitems__(list(range(permutation.num_rows)))
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def test_split_random_ratios(mem_db):
|
||||
"""Test random splitting with ratios."""
|
||||
tbl = mem_db.create_table(
|
||||
@@ -87,6 +99,282 @@ def test_pickled_permutation_reads_pinned_version(tmp_path):
|
||||
assert sorted(row["idx"] for row in rows) == list(range(20))
|
||||
|
||||
|
||||
def test_persist_plan_create_overwrite_namespace_and_metadata(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
db.create_namespace(["plans"])
|
||||
namespace_path = ["plans"]
|
||||
|
||||
plan = (
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2, split_names=["train", "test"])
|
||||
.persist(db, "splits", namespace_path=namespace_path)
|
||||
.execute()
|
||||
)
|
||||
assert plan.count_rows() == 20
|
||||
assert plan.namespace == namespace_path
|
||||
assert pickle.loads(pickle.dumps(plan)).namespace == namespace_path
|
||||
|
||||
permutation = Permutation.from_tables(tbl, plan, split="train")
|
||||
assert permutation.base_version == tbl.version
|
||||
assert permutation.base_branch is None
|
||||
assert permutation.num_rows == 10
|
||||
|
||||
with pytest.raises((ValueError, RuntimeError), match="already exists"):
|
||||
(
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2)
|
||||
.persist(db, "splits", namespace_path=namespace_path)
|
||||
.execute()
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="Invalid mode"):
|
||||
permutation_builder(tbl).persist(db, "other", mode="replace")
|
||||
|
||||
class RemoteLike:
|
||||
uri = "db://example"
|
||||
|
||||
with pytest.raises(NotImplementedError, match="Enterprise"):
|
||||
permutation_builder(tbl).persist(RemoteLike(), "remote_splits")
|
||||
|
||||
tbl.add(pa.table({"id": range(20, 40)}))
|
||||
plan = (
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2)
|
||||
.persist(db, "splits", namespace_path=namespace_path, mode="overwrite")
|
||||
.execute()
|
||||
)
|
||||
assert plan.count_rows() == 40
|
||||
assert db.open_table("splits", namespace_path=namespace_path).count_rows() == 40
|
||||
# The earlier permutation still reads the plan and base snapshot it was built from.
|
||||
assert permutation.num_rows == 10
|
||||
assert [row["id"] for row in permutation.__getitems__([0, 1])] == [0, 1]
|
||||
|
||||
|
||||
def test_persist_namespace_connection_direct_result_pickle(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect_namespace("dir", {"root": str(tmp_path)})
|
||||
db.create_namespace(["plans"])
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
|
||||
plan = (
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2, split_names=["train", "test"])
|
||||
.persist(db, "splits", namespace_path=["plans"])
|
||||
.execute()
|
||||
)
|
||||
assert plan.namespace == ["plans"]
|
||||
assert plan._conn is db
|
||||
|
||||
restored_plan = pickle.loads(pickle.dumps(plan))
|
||||
assert restored_plan.namespace == ["plans"]
|
||||
assert restored_plan.count_rows() == 20
|
||||
|
||||
permutation = Permutation.from_tables(tbl, plan, split="train")
|
||||
restored = pickle.loads(pickle.dumps(permutation))
|
||||
assert restored.num_rows == 10
|
||||
assert sorted(
|
||||
row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
|
||||
) == list(range(10))
|
||||
|
||||
|
||||
def test_persist_direct_result_keeps_session_pickle_error(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path, session=Session())
|
||||
tbl = db.create_table("base", pa.table({"id": range(5)}))
|
||||
plan = permutation_builder(tbl).persist(db, "splits").execute()
|
||||
|
||||
with pytest.raises(TypeError, match="Session"):
|
||||
pickle.dumps(plan)
|
||||
|
||||
permutation = Permutation.from_tables(tbl, plan)
|
||||
with pytest.raises(TypeError, match="Session"):
|
||||
pickle.dumps(permutation)
|
||||
|
||||
|
||||
def test_persist_direct_result_preserves_manifest_connection_state(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path, manifest_enabled=True)
|
||||
tbl = db.create_table("base", pa.table({"id": range(5)}))
|
||||
plan = permutation_builder(tbl).persist(db, "splits").execute()
|
||||
|
||||
restored = pickle.loads(pickle.dumps(plan))
|
||||
assert restored._conn._manifest_enabled is True
|
||||
assert restored.count_rows() == 5
|
||||
|
||||
|
||||
def test_base_branch_property_reads_plan_metadata(tmp_path):
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(10)}))
|
||||
branch = tbl.branches.create("exp")
|
||||
branch.add(pa.table({"id": range(10, 20)}))
|
||||
|
||||
plan = permutation_builder(branch).persist(db, "branch_splits").execute()
|
||||
permutation = Permutation.from_tables(branch, plan)
|
||||
|
||||
assert permutation.base_branch == "exp"
|
||||
assert permutation.base_version == branch.version
|
||||
assert permutation.num_rows == 20
|
||||
|
||||
|
||||
def test_persisted_plan_pickle_reopens_same_snapshot_after_overwrite(tmp_path):
|
||||
from datetime import timedelta
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path, read_consistency_interval=timedelta(0))
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
plan = permutation_builder(tbl).filter("id < 10").persist(db, "splits").execute()
|
||||
permutation = Permutation.from_tables(tbl, plan)
|
||||
old_base_version = permutation.base_version
|
||||
old_plan_version = permutation._plan_version
|
||||
state = permutation.__getstate__()
|
||||
assert "permutation_data" not in state
|
||||
assert (
|
||||
state["permutation_table_state"]["state"]["checkout_version"]
|
||||
== old_plan_version
|
||||
)
|
||||
|
||||
# Replace the plan with disjoint rows of the same cardinality.
|
||||
permutation_builder(tbl).filter("id >= 10").persist(
|
||||
db, "splits", mode="overwrite"
|
||||
).execute()
|
||||
assert plan.version == old_plan_version + 1
|
||||
assert permutation.permutation_table.version == old_plan_version
|
||||
|
||||
live_ids = [
|
||||
row["id"] for row in permutation.__getitems__(list(range(permutation.num_rows)))
|
||||
]
|
||||
assert live_ids == list(range(10))
|
||||
|
||||
# A reader recreated after the overwrite must still use the pinned snapshot.
|
||||
permutation.reader = None
|
||||
permutation._pid = None
|
||||
recreated_ids = [
|
||||
row["id"] for row in permutation.__getitems__(list(range(permutation.num_rows)))
|
||||
]
|
||||
assert recreated_ids == list(range(10))
|
||||
|
||||
restored = pickle.loads(pickle.dumps(permutation))
|
||||
assert restored.base_version == old_base_version
|
||||
restored_ids = [
|
||||
row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
|
||||
]
|
||||
assert restored_ids == list(range(10))
|
||||
|
||||
# A newly constructed permutation sees the overwritten plan.
|
||||
fresh = Permutation.from_tables(tbl, db.open_table("splits"))
|
||||
assert fresh.base_version == old_base_version
|
||||
fresh_ids = [row["id"] for row in fresh.__getitems__(list(range(fresh.num_rows)))]
|
||||
assert fresh_ids == list(range(10, 20))
|
||||
|
||||
|
||||
def test_persisted_plan_pickle_uses_captured_main_branch(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
permutation_builder(tbl).persist(db, "splits").execute()
|
||||
|
||||
initial_plan = db.open_table("splits")
|
||||
initial_plan.branches.create("exp", from_version=1)
|
||||
|
||||
# Main plan version 2 still has all 20 rows.
|
||||
permutation_builder(tbl).persist(db, "splits", mode="overwrite").execute()
|
||||
main_plan = db.open_table("splits")
|
||||
assert main_plan.version == 2
|
||||
|
||||
# Branch plan version 2 has different contents, so the numeric version alone
|
||||
# does not identify the snapshot.
|
||||
branch_plan = db.open_table("splits", branch="exp")
|
||||
branch_plan.add(
|
||||
pa.table(
|
||||
{
|
||||
"row_id": pa.array([0], type=pa.uint64()),
|
||||
"split_id": pa.array([0], type=pa.uint32()),
|
||||
}
|
||||
)
|
||||
)
|
||||
branch_plan = db.open_table("splits", branch="exp")
|
||||
assert branch_plan.version == 2
|
||||
assert branch_plan.count_rows() == 21
|
||||
branch_plan.tags.create("exp_v2", 2)
|
||||
|
||||
permutation = Permutation.from_tables(tbl, main_plan)
|
||||
|
||||
# Move the same passed-in plan handle to the other branch at the same
|
||||
# numeric version. Pickle must still reopen the captured main snapshot.
|
||||
main_plan.checkout("exp_v2")
|
||||
assert main_plan.current_branch() == "exp"
|
||||
assert main_plan.version == 2
|
||||
payload = pickle.dumps(permutation)
|
||||
|
||||
restored = pickle.loads(payload)
|
||||
assert restored.permutation_table.current_branch() is None
|
||||
assert restored.permutation_table.version == 2
|
||||
assert restored.num_rows == 20
|
||||
|
||||
|
||||
def test_persisted_plan_pickle_reopens_in_spawned_process(tmp_path):
|
||||
import multiprocessing as mp
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(12)}))
|
||||
plan = permutation_builder(tbl).persist(db, "splits").execute()
|
||||
payload = pickle.dumps(Permutation.from_tables(tbl, plan))
|
||||
|
||||
tbl.add(pa.table({"id": range(12, 24)}))
|
||||
permutation_builder(tbl).persist(db, "splits", mode="overwrite").execute()
|
||||
|
||||
context = mp.get_context("spawn")
|
||||
output = context.Queue()
|
||||
process = context.Process(
|
||||
target=_read_permutation_in_spawned_process, args=(payload, output)
|
||||
)
|
||||
process.start()
|
||||
try:
|
||||
ids = output.get(timeout=60)
|
||||
finally:
|
||||
process.join(timeout=60)
|
||||
|
||||
assert process.exitcode == 0
|
||||
assert sorted(ids) == list(range(12))
|
||||
|
||||
|
||||
def test_old_permutation_pickle_state_still_round_trips(tmp_path):
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
plan = permutation_builder(tbl).execute()
|
||||
state = {
|
||||
"base_table_name": tbl.name,
|
||||
"permutation_data": plan.to_arrow(),
|
||||
"split": 0,
|
||||
"selection": {"id": "id"},
|
||||
"batch_size": DEFAULT_BATCH_SIZE,
|
||||
"transform_fn": Transforms.arrow2python,
|
||||
"offset": None,
|
||||
"limit": None,
|
||||
"connection_factory": None,
|
||||
"base_table_uri": str(tmp_path),
|
||||
"base_table_storage_options": None,
|
||||
"base_table_namespace": [],
|
||||
}
|
||||
|
||||
restored = Permutation.__new__(Permutation)
|
||||
restored.__setstate__(state)
|
||||
|
||||
assert restored.base_version == tbl.version
|
||||
assert restored.base_branch is None
|
||||
assert sorted(
|
||||
row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
|
||||
) == list(range(20))
|
||||
|
||||
|
||||
def test_builder_copy_is_shallow_and_does_not_materialize(
|
||||
some_table: Table, some_perm_table: Table, monkeypatch
|
||||
):
|
||||
|
||||
@@ -1102,6 +1102,201 @@ def test_order_by_clears_with_none_and_empty_list(mem_db):
|
||||
assert query.order_by([]).to_query_object().order_by is None
|
||||
|
||||
|
||||
def test_scan_in_order_plain_query(tmp_db):
|
||||
table = tmp_db.create_table("scan_in_order", pa.table({"id": [0, 1]}))
|
||||
table.add(pa.table({"id": [2, 3]}))
|
||||
table.add(pa.table({"id": [4, 5]}))
|
||||
|
||||
fragments = table.to_lance().get_fragments()
|
||||
assert len(fragments) == 3, "the test needs real multi-fragment data"
|
||||
|
||||
version = table.version
|
||||
table.checkout(version)
|
||||
|
||||
default = table.search().select(["id"]).to_arrow()["id"].to_pylist()
|
||||
assert default == [0, 1, 2, 3, 4, 5]
|
||||
assert table.search().to_query_object().scan_in_order is None
|
||||
|
||||
ordered = table.search().scan_in_order().select(["id"]).to_arrow()
|
||||
assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5]
|
||||
repeated = table.search().scan_in_order(True).select(["id"]).to_arrow()
|
||||
assert repeated.equals(ordered)
|
||||
|
||||
unordered = (
|
||||
table.search().scan_in_order(False).select(["id"]).to_arrow()["id"].to_pylist()
|
||||
)
|
||||
assert sorted(unordered) == [0, 1, 2, 3, 4, 5]
|
||||
|
||||
sorted_desc = (
|
||||
table.search()
|
||||
.scan_in_order(False)
|
||||
.order_by(("id", "desc"))
|
||||
.select(["id"])
|
||||
.to_arrow()["id"]
|
||||
.to_pylist()
|
||||
)
|
||||
assert sorted_desc == [5, 4, 3, 2, 1, 0]
|
||||
|
||||
with pytest.raises(ValueError, match="nonempty order_by"):
|
||||
table.search().scan_in_order().order_by("id").to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scan_in_order_async_query(tmp_db_async: AsyncConnection):
|
||||
table = await tmp_db_async.create_table(
|
||||
"scan_in_order_async", pa.table({"id": [0, 1]})
|
||||
)
|
||||
await table.add(pa.table({"id": [2, 3]}))
|
||||
await table.add(pa.table({"id": [4, 5]}))
|
||||
|
||||
assert len((await table.to_lance()).get_fragments()) == 3
|
||||
version = await table.version()
|
||||
await table.checkout(version)
|
||||
|
||||
ordered = await table.query().scan_in_order().select(["id"]).to_arrow()
|
||||
assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5]
|
||||
assert table.query().to_query_object().scan_in_order is None
|
||||
|
||||
unordered = (await table.query().scan_in_order(False).select(["id"]).to_arrow())[
|
||||
"id"
|
||||
].to_pylist()
|
||||
assert sorted(unordered) == [0, 1, 2, 3, 4, 5]
|
||||
|
||||
with pytest.raises(ValueError, match="nonempty order_by"):
|
||||
await table.query().scan_in_order().order_by("id").to_arrow()
|
||||
with pytest.raises(ValueError, match="ranked results"):
|
||||
await table.query().scan_in_order().nearest_to([0.0, 0.0]).to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ordered", [False, True])
|
||||
def test_scan_in_order_pandas_scanner_path(tmp_db, monkeypatch, ordered):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = tmp_db.create_table(
|
||||
f"scan_in_order_scanner_{ordered}",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
table.add(data.slice(2, 2))
|
||||
|
||||
query = table.search().select(["id", "blob"]).scan_in_order(ordered)
|
||||
|
||||
def fail_to_arrow(*args, **kwargs):
|
||||
raise AssertionError("scanner-backed pandas must not collect through to_arrow")
|
||||
|
||||
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
||||
|
||||
dataset = table.to_lance()
|
||||
dataset_cls = type(dataset)
|
||||
real_scanner = dataset_cls.scanner
|
||||
captured = {}
|
||||
|
||||
def capture_scanner(self, **kwargs):
|
||||
captured.update(kwargs)
|
||||
return real_scanner(self, **kwargs)
|
||||
|
||||
monkeypatch.setattr(dataset_cls, "scanner", capture_scanner)
|
||||
|
||||
df = query.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
|
||||
assert captured["scan_in_order"] is ordered
|
||||
assert captured.get("use_scalar_index") is (False if ordered else None)
|
||||
assert sorted(df["id"].tolist()) == [1, 2, 3, 4]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("storage_version", ["legacy", "stable"])
|
||||
def test_scan_in_order_indexed_filter_preserves_manifest_order(
|
||||
tmp_path, storage_version
|
||||
):
|
||||
lance = pytest.importorskip("lance")
|
||||
data = pa.table({"id": list(range(20)), "value": list(range(20))})
|
||||
dataset = lance.write_dataset(
|
||||
data,
|
||||
tmp_path / "t.lance",
|
||||
data_storage_version=storage_version,
|
||||
max_rows_per_file=10,
|
||||
)
|
||||
dataset.create_scalar_index("value", "BTREE")
|
||||
version_before_update = dataset.version
|
||||
dataset.update({"value": "100"}, where="id = 0")
|
||||
|
||||
table = lancedb.connect(str(tmp_path)).open_table("t")
|
||||
for version in (version_before_update, dataset.version):
|
||||
table.checkout(version)
|
||||
base = table.search().scan_in_order(True).select(["id"]).limit(100)
|
||||
expected = base.to_arrow()["id"].to_pylist()
|
||||
actual = base.where("value < 1000").to_arrow()["id"].to_pylist()
|
||||
assert actual == expected
|
||||
|
||||
|
||||
def test_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(tmp_db):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = tmp_db.create_table(
|
||||
"scan_in_order_fragments",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
table.add(data.slice(2, 2))
|
||||
table.checkout(table.version)
|
||||
|
||||
fragments = table.to_lance().get_fragments()
|
||||
reversed_fragments = fragments[::-1]
|
||||
with pytest.raises(ValueError, match="use fragment_ids"):
|
||||
(
|
||||
table.search()
|
||||
.scan_in_order()
|
||||
.select(["id", "blob"])
|
||||
.with_fragments(reversed_fragments)
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
|
||||
# fragment_ids is already resolved from the manifest and stays ordered.
|
||||
df_by_id = (
|
||||
table.search()
|
||||
.scan_in_order()
|
||||
.select(["id", "blob"])
|
||||
.fragment_ids([fragment.fragment_id for fragment in reversed_fragments])
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
assert df_by_id["id"].tolist() == [1, 2, 3, 4]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(
|
||||
tmp_db_async,
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
"scan_in_order_fragments_async",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
await table.checkout(await table.version())
|
||||
|
||||
fragments = (await table.to_lance()).get_fragments()
|
||||
reversed_fragments = fragments[::-1]
|
||||
with pytest.raises(ValueError, match="use fragment_ids"):
|
||||
await (
|
||||
table.query()
|
||||
.scan_in_order()
|
||||
.with_fragments(fragments[::-1])
|
||||
.select(["id", "blob"])
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
|
||||
df_by_id = await (
|
||||
table.query()
|
||||
.scan_in_order()
|
||||
.fragment_ids([fragment.fragment_id for fragment in reversed_fragments])
|
||||
.select(["id", "blob"])
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
assert df_by_id["id"].tolist() == [1, 2, 3, 4]
|
||||
|
||||
|
||||
def test_order_by_rejects_invalid_input_early(mem_db):
|
||||
table = mem_db.create_table("test_order_by_invalid", [{"name": "a"}])
|
||||
|
||||
|
||||
@@ -3737,13 +3737,16 @@ def test_remote_python_only_messages():
|
||||
f"{method}() is not supported in LanceDB Enterprise. "
|
||||
f"Use table.search().{method}() instead."
|
||||
)
|
||||
for method in ["compact_files", "cleanup_old_versions"]:
|
||||
for method, expected in {
|
||||
"compact_files": "compact_files() is a no-op in LanceDB Enterprise.",
|
||||
"cleanup_old_versions": (
|
||||
"cleanup_old_versions() is a no-op in LanceDB Enterprise. "
|
||||
"Use cleanup_async() to submit durable cleanup explicitly."
|
||||
),
|
||||
}.items():
|
||||
with pytest.warns(UserWarning) as warning:
|
||||
getattr(table, method)()
|
||||
assert (
|
||||
str(warning[0].message)
|
||||
== f"{method}() is a no-op in LanceDB Enterprise."
|
||||
)
|
||||
assert getattr(table, method)() is None
|
||||
assert str(warning[0].message) == expected
|
||||
|
||||
|
||||
def test_remote_embedding_config_does_not_warn_or_drop_metadata(caplog):
|
||||
|
||||
@@ -11,6 +11,7 @@ import threading
|
||||
import pytest
|
||||
import pyarrow as pa
|
||||
import lancedb
|
||||
from lancedb.permutation import Permutation, permutation_builder
|
||||
|
||||
|
||||
# These are all keys that are accepted by storage_options
|
||||
@@ -87,6 +88,36 @@ def test_s3_lifecycle(s3_bucket: str):
|
||||
asyncio.run(test())
|
||||
|
||||
|
||||
@pytest.mark.s3_test
|
||||
def test_s3_permutation_persist_direct_result_pickle(s3_bucket: str):
|
||||
import pickle
|
||||
|
||||
storage_options = copy.copy(CONFIG)
|
||||
uri = f"s3://{s3_bucket}/test_permutation_persist"
|
||||
db = lancedb.connect(uri, storage_options=storage_options)
|
||||
try:
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
plan = (
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2, split_names=["train", "test"])
|
||||
.persist(db, "splits")
|
||||
.execute()
|
||||
)
|
||||
assert plan._storage_options == storage_options
|
||||
|
||||
restored_plan = pickle.loads(pickle.dumps(plan))
|
||||
assert restored_plan.count_rows() == 20
|
||||
|
||||
permutation = Permutation.from_tables(tbl, plan, split="train")
|
||||
restored = pickle.loads(pickle.dumps(permutation))
|
||||
assert restored.num_rows == 10
|
||||
assert sorted(
|
||||
row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
|
||||
) == list(range(10))
|
||||
finally:
|
||||
db.drop_all_tables()
|
||||
|
||||
|
||||
@pytest.mark.s3_test
|
||||
def test_concurrent_open_table(s3_bucket: str):
|
||||
uri = f"s3://{s3_bucket}/test_concurrent_open_table"
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import gc
|
||||
import time
|
||||
from datetime import timedelta
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
import lancedb.table as table_module
|
||||
from lancedb.query import AsyncQuery
|
||||
|
||||
|
||||
def _table(db, name="sync_pull_reader"):
|
||||
return db.create_table(
|
||||
name,
|
||||
data=[{"id": i, "vector": [float(i), float(i)]} for i in range(10)],
|
||||
)
|
||||
|
||||
|
||||
def _spy_on_pull_reader(monkeypatch):
|
||||
calls = []
|
||||
real = AsyncQuery._execute_batches_sync
|
||||
|
||||
def spy(self, *, max_batch_length=None, timeout=None):
|
||||
calls.append((max_batch_length, timeout))
|
||||
return real(self, max_batch_length=max_batch_length, timeout=timeout)
|
||||
|
||||
monkeypatch.setattr(AsyncQuery, "_execute_batches_sync", spy)
|
||||
return calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"batch_size,row_limit",
|
||||
[
|
||||
(None, 1024),
|
||||
(0, None),
|
||||
(4, 4),
|
||||
],
|
||||
)
|
||||
def test_plain_sync_batches_use_pull_reader(mem_db, monkeypatch, batch_size, row_limit):
|
||||
table = _table(mem_db)
|
||||
calls = _spy_on_pull_reader(monkeypatch)
|
||||
|
||||
reader = table.search().select(["id"]).to_batches(batch_size=batch_size)
|
||||
|
||||
assert isinstance(reader, pa.RecordBatchReader)
|
||||
assert calls == [(batch_size, None)]
|
||||
batches = list(reader)
|
||||
assert sum(batch.num_rows for batch in batches) == 10
|
||||
assert pa.Table.from_batches(batches).column("id").to_pylist() == list(range(10))
|
||||
if row_limit is not None:
|
||||
assert all(batch.num_rows <= row_limit for batch in batches)
|
||||
|
||||
|
||||
def test_scan_in_order_routes_through_pull_reader(tmp_db, monkeypatch):
|
||||
table = tmp_db.create_table("ordered_pull_reader", pa.table({"id": [0, 1]}))
|
||||
table.add(pa.table({"id": [2, 3]}))
|
||||
table.add(pa.table({"id": [4, 5]}))
|
||||
table.checkout(table.version)
|
||||
calls = _spy_on_pull_reader(monkeypatch)
|
||||
|
||||
reader = table.search().scan_in_order(True).select(["id"]).to_batches(batch_size=2)
|
||||
|
||||
assert calls == [(2, None)]
|
||||
assert [value for batch in reader for value in batch["id"].to_pylist()] == [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
]
|
||||
with pytest.raises(ValueError, match="nonempty order_by"):
|
||||
table.search().scan_in_order(True).order_by("id").to_batches()
|
||||
|
||||
|
||||
def test_plain_sync_batches_do_not_enter_background_loop(mem_db, monkeypatch):
|
||||
table = _table(mem_db)
|
||||
|
||||
def fail(*args, **kwargs):
|
||||
raise AssertionError("plain sync batches entered the background event loop")
|
||||
|
||||
monkeypatch.setattr(table_module.LOOP, "run", fail)
|
||||
|
||||
reader = table.search().select(["id"]).to_batches(batch_size=4)
|
||||
|
||||
assert sum(batch.num_rows for batch in reader) == 10
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"execute",
|
||||
[
|
||||
lambda table: table.search().select(["id"]).to_arrow(),
|
||||
lambda table: table.search([0.0, 0.0]).to_batches(),
|
||||
lambda table: table.take_offsets([0]).to_batches(),
|
||||
lambda table: table.search().select(["id"]).order_by(["id"]).to_batches(),
|
||||
lambda table: (
|
||||
table.search().select(["id"]).to_batches(blob_mode="descriptions")
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_other_sync_routes_keep_the_existing_reader(mem_db, monkeypatch, execute):
|
||||
table = _table(mem_db)
|
||||
calls = _spy_on_pull_reader(monkeypatch)
|
||||
|
||||
execute(table)
|
||||
|
||||
assert calls == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_batches_keep_the_existing_reader(monkeypatch):
|
||||
db = await lancedb.connect_async("memory://")
|
||||
table = await db.create_table(
|
||||
"async_sync_pull_reader", data=[{"id": i} for i in range(4)]
|
||||
)
|
||||
calls = _spy_on_pull_reader(monkeypatch)
|
||||
|
||||
reader = await table.query().to_batches()
|
||||
|
||||
total_rows = 0
|
||||
async for batch in reader:
|
||||
total_rows += batch.num_rows
|
||||
assert total_rows == 4
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_timeout_starts_on_first_read_and_spans_reads(tmp_path):
|
||||
table = lancedb.connect(tmp_path).create_table(
|
||||
"timeout_pull_reader", data=[{"id": i} for i in range(8)]
|
||||
)
|
||||
reader = (
|
||||
table.search()
|
||||
.select(["id"])
|
||||
.to_batches(batch_size=2, timeout=timedelta(milliseconds=200))
|
||||
)
|
||||
|
||||
# A slow consumer before the first poll must not count against the query:
|
||||
# the timeout starts when the first batch is requested.
|
||||
time.sleep(0.25)
|
||||
first = reader.read_next_batch()
|
||||
assert first.num_rows == 2
|
||||
|
||||
# The deadline spans reads, so a pause between batches expires it.
|
||||
time.sleep(0.25)
|
||||
with pytest.raises(RuntimeError, match="Query timeout"):
|
||||
reader.read_next_batch()
|
||||
|
||||
|
||||
def test_early_break_can_resume_the_same_reader(mem_db):
|
||||
table = _table(mem_db)
|
||||
reader = table.search().select(["id"]).to_batches(batch_size=2)
|
||||
|
||||
first = next(iter(reader))
|
||||
rest = list(reader)
|
||||
|
||||
assert pa.Table.from_batches([first, *rest]).column("id").to_pylist() == list(
|
||||
range(10)
|
||||
)
|
||||
|
||||
reader = table.search().select(["id"]).to_batches(batch_size=2)
|
||||
for first in reader:
|
||||
break
|
||||
rest = list(reader)
|
||||
assert pa.Table.from_batches([first, *rest]).column("id").to_pylist() == list(
|
||||
range(10)
|
||||
)
|
||||
|
||||
|
||||
def test_arrow_export_shares_cursor_with_the_last_owner(mem_db):
|
||||
table = _table(mem_db)
|
||||
reader = table.search().select(["id"]).to_batches(batch_size=2)
|
||||
first = reader.read_next_batch()
|
||||
|
||||
capsule = reader.__arrow_c_stream__()
|
||||
del reader
|
||||
gc.collect()
|
||||
|
||||
imported = pa.RecordBatchReader._import_from_c_capsule(capsule)
|
||||
rest = imported.read_all()
|
||||
combined = pa.concat_tables([pa.Table.from_batches([first]), rest])
|
||||
assert combined.column("id").to_pylist() == list(range(10))
|
||||
|
||||
|
||||
def test_empty_result_preserves_the_query_schema(mem_db):
|
||||
table = _table(mem_db)
|
||||
query = table.search().select(["id"]).where("id < 0")
|
||||
|
||||
reader = query.to_batches(batch_size=4)
|
||||
|
||||
assert reader.schema == query.output_schema()
|
||||
assert reader.read_all().num_rows == 0
|
||||
@@ -1054,6 +1054,10 @@ impl Connection {
|
||||
job.into_typed::<lancedb::table::PrewarmDataResult>()
|
||||
.infer_error()?,
|
||||
)),
|
||||
Some("cleanup") => Ok(crate::job::Job::new_typed(
|
||||
job.into_typed::<lancedb::table::CleanupResult>()
|
||||
.infer_error()?,
|
||||
)),
|
||||
Some("compact") => Ok(crate::job::Job::new_typed(
|
||||
job.into_typed::<lancedb::table::CompactionResult>()
|
||||
.infer_error()?,
|
||||
|
||||
@@ -40,6 +40,7 @@ pub mod query;
|
||||
pub mod runtime;
|
||||
pub mod session;
|
||||
pub mod sql;
|
||||
mod sync_stream;
|
||||
pub mod table;
|
||||
pub mod util;
|
||||
|
||||
@@ -113,6 +114,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_class::<HybridQuery>()?;
|
||||
m.add_class::<VectorQuery>()?;
|
||||
m.add_class::<RecordBatchStream>()?;
|
||||
m.add_class::<sync_stream::SyncRecordBatchStream>()?;
|
||||
m.add_class::<AddColumnsResult>()?;
|
||||
m.add_class::<RefreshColumnResult>()?;
|
||||
m.add_class::<FunctionErrors>()?;
|
||||
|
||||
@@ -9,7 +9,10 @@ use crate::{
|
||||
use arrow::pyarrow::{PyArrowType, ToPyArrow};
|
||||
use lancedb::{
|
||||
dataloader::permutation::{
|
||||
builder::{PermutationBuilder as LancePermutationBuilder, ShuffleStrategy},
|
||||
builder::{
|
||||
PermutationBuilder as LancePermutationBuilder, PermutationPersistMode,
|
||||
PermutationPersistOptions, ShuffleStrategy,
|
||||
},
|
||||
reader::PermutationReader,
|
||||
split::{SplitSizes, SplitStrategy},
|
||||
},
|
||||
@@ -17,7 +20,7 @@ use lancedb::{
|
||||
};
|
||||
use pyo3::{
|
||||
Bound, PyAny, PyRef, PyRefMut, PyResult, Python,
|
||||
exceptions::PyRuntimeError,
|
||||
exceptions::{PyRuntimeError, PyValueError},
|
||||
pyclass, pymethods,
|
||||
types::{PyAnyMethods, PyDict, PyDictMethods, PyType},
|
||||
};
|
||||
@@ -247,6 +250,37 @@ impl PyAsyncPermutationBuilder {
|
||||
slf.modify(|builder| builder.with_filter(filter))
|
||||
}
|
||||
|
||||
/// Store the permutation table in a database.
|
||||
///
|
||||
/// This is only supported for embedded databases. The destination table is
|
||||
/// created in the selected namespace, and an existing table is replaced only
|
||||
/// when ``mode="overwrite"`` is explicit.
|
||||
#[pyo3(signature = (db, table_name, *, namespace_path=None, mode="create"))]
|
||||
pub fn persist(
|
||||
slf: PyRefMut<'_, Self>,
|
||||
db: PyRef<'_, crate::connection::Connection>,
|
||||
table_name: String,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
mode: &str,
|
||||
) -> PyResult<Self> {
|
||||
let mode = match mode {
|
||||
"create" => PermutationPersistMode::Create,
|
||||
"overwrite" => PermutationPersistMode::Overwrite,
|
||||
other => {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"Invalid mode {other}; expected 'create' or 'overwrite'"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let database = db.database()?;
|
||||
let options = PermutationPersistOptions {
|
||||
namespace_path: namespace_path.unwrap_or_default(),
|
||||
mode,
|
||||
};
|
||||
|
||||
slf.modify(|builder| builder.persist_with_options(database, table_name, options))
|
||||
}
|
||||
|
||||
pub fn execute(slf: PyRefMut<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let mut state = slf.state.lock().unwrap();
|
||||
let builder = state
|
||||
|
||||
+46
-7
@@ -7,6 +7,7 @@ use std::time::Duration;
|
||||
|
||||
use crate::expr::PyExpr;
|
||||
use crate::runtime::future_into_py;
|
||||
use crate::sync_stream::SyncRecordBatchStream;
|
||||
use crate::util::parse_distance_type;
|
||||
use crate::{arrow::RecordBatchStream, util::PyLanceDB};
|
||||
use crate::{error::PythonErrorExt, index::class_name};
|
||||
@@ -80,6 +81,20 @@ where
|
||||
Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind()))
|
||||
}
|
||||
|
||||
fn query_execution_options(
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> QueryExecutionOptions {
|
||||
let mut options = QueryExecutionOptions::default();
|
||||
if let Some(max_batch_length) = max_batch_length {
|
||||
options.max_batch_length = max_batch_length;
|
||||
}
|
||||
if let Some(timeout) = timeout {
|
||||
options.timeout = Some(timeout);
|
||||
}
|
||||
options
|
||||
}
|
||||
|
||||
impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB<FtsQuery> {
|
||||
type Error = PyErr;
|
||||
|
||||
@@ -396,6 +411,7 @@ pub struct PyQueryRequest {
|
||||
pub postfilter: Option<bool>,
|
||||
pub norm: Option<String>,
|
||||
pub order_by: Option<Vec<PyColumnOrdering>>,
|
||||
pub scan_in_order: Option<bool>,
|
||||
}
|
||||
|
||||
impl From<AnyQuery> for PyQueryRequest {
|
||||
@@ -434,6 +450,7 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
order_by: query_request
|
||||
.order_by
|
||||
.map(|order_by| order_by.into_iter().map(PyColumnOrdering::from).collect()),
|
||||
scan_in_order: query_request.scan_in_order,
|
||||
},
|
||||
AnyQuery::VectorQuery(vector_query) => Self {
|
||||
limit: vector_query.base.limit,
|
||||
@@ -467,6 +484,7 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
.base
|
||||
.order_by
|
||||
.map(|order_by| order_by.into_iter().map(PyColumnOrdering::from).collect()),
|
||||
scan_in_order: vector_query.base.scan_in_order,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -685,6 +703,10 @@ impl Query {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn scan_in_order(&mut self, ordered: bool) {
|
||||
self.inner = self.inner.clone().scan_in_order(ordered);
|
||||
}
|
||||
|
||||
#[pyo3(signature = ())]
|
||||
pub fn output_schema(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
@@ -702,18 +724,35 @@ impl Query {
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let mut opts = QueryExecutionOptions::default();
|
||||
if let Some(max_batch_length) = max_batch_length {
|
||||
opts.max_batch_length = max_batch_length;
|
||||
}
|
||||
if let Some(timeout) = timeout {
|
||||
opts.timeout = Some(timeout);
|
||||
}
|
||||
let opts = query_execution_options(max_batch_length, timeout);
|
||||
let inner_stream = inner.execute_with_options(opts).await.infer_error()?;
|
||||
Ok(RecordBatchStream::new(inner_stream))
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute this local query and return a pull-driven synchronous iterator.
|
||||
///
|
||||
/// The query is started once. Each `__next__` fetches exactly one batch
|
||||
/// from the caller's thread while the GIL is released. `None` keeps the
|
||||
/// core's default 1024-row output cap, `0` lets the engine choose, and a
|
||||
/// positive value caps each returned batch.
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_sync(
|
||||
self_: PyRef<'_, Self>,
|
||||
py: Python<'_>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<SyncRecordBatchStream> {
|
||||
let inner = self_.inner.clone();
|
||||
let opts = query_execution_options(max_batch_length, timeout);
|
||||
let stream = py.detach(move || {
|
||||
crate::runtime::block_on_interruptible(async move {
|
||||
inner.execute_with_options(opts).await.infer_error()
|
||||
})
|
||||
})?;
|
||||
Ok(SyncRecordBatchStream::new(stream))
|
||||
}
|
||||
|
||||
/// Execute this query eagerly and return an Arrow C Stream reader.
|
||||
///
|
||||
/// The returned reader exposes batches already collected in Rust, so
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! A pull-driven synchronous reader over a query's record batch stream.
|
||||
//!
|
||||
//! The synchronous Python API used to drive one future per batch through the
|
||||
//! shared background event loop. This reader keeps the stream in Rust and
|
||||
//! fetches exactly one batch from the caller's thread for each `__next__`,
|
||||
//! while the caller's GIL is released.
|
||||
//!
|
||||
//! The stream is stored only while the reader is idle. Taking it out for a
|
||||
//! poll means an error, EOF, interrupt, or a dropped last owner releases the
|
||||
//! execution plan immediately instead of leaving a reader task behind. A
|
||||
//! successful batch puts the stream back so an early `break` can resume
|
||||
//! reading from the same cursor.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
use arrow::datatypes::SchemaRef;
|
||||
use arrow::pyarrow::{IntoPyArrow, ToPyArrow};
|
||||
use arrow::record_batch::RecordBatch;
|
||||
use futures::StreamExt;
|
||||
use lancedb::arrow::SendableRecordBatchStream;
|
||||
use pyo3::{Py, PyAny, PyRef, PyResult, Python, pyclass, pymethods};
|
||||
|
||||
use crate::error::PythonErrorExt;
|
||||
use crate::runtime::block_on_interruptible;
|
||||
|
||||
/// Synchronous iterator over the batches of one query execution.
|
||||
///
|
||||
/// Python wraps this in [`pyarrow.RecordBatchReader.from_batches`] so the
|
||||
/// public return type, schema capsule, and exception types stay the same as
|
||||
/// the existing sync reader. Creating the iterator does not poll the stream;
|
||||
/// the first `__next__` starts any configured query timeout.
|
||||
#[pyclass]
|
||||
pub struct SyncRecordBatchStream {
|
||||
schema: SchemaRef,
|
||||
stream: Mutex<Option<SendableRecordBatchStream>>,
|
||||
}
|
||||
|
||||
impl SyncRecordBatchStream {
|
||||
pub fn new(stream: SendableRecordBatchStream) -> Self {
|
||||
let schema = stream.schema();
|
||||
Self {
|
||||
schema,
|
||||
stream: Mutex::new(Some(stream)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the stream and hand it to one owned, one-shot read future.
|
||||
///
|
||||
/// The future owns the stream so an interrupt aborts it and drops the
|
||||
/// execution plan with the future. A successful batch returns the stream
|
||||
/// to the slot, which keeps an early `break` resumable. EOF and read
|
||||
/// errors drop the stream before returning. The lock is held only while
|
||||
/// taking or storing the stream, never while waiting, so another Python
|
||||
/// thread cannot deadlock against a read that needs the GIL.
|
||||
fn pull(&mut self) -> PyResult<Option<RecordBatch>> {
|
||||
match self.pull_with(|mut stream| {
|
||||
block_on_interruptible(async move {
|
||||
let next = stream.next().await;
|
||||
Ok::<_, pyo3::PyErr>((stream, next))
|
||||
})
|
||||
})? {
|
||||
Some(Ok(batch)) => Ok(Some(batch)),
|
||||
Some(Err(error)) => Err(into_py_error(error)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared state machine for one pull, with the wait injected for tests.
|
||||
fn pull_with<F>(
|
||||
&mut self,
|
||||
fetch: F,
|
||||
) -> Result<Option<Result<RecordBatch, lancedb::Error>>, pyo3::PyErr>
|
||||
where
|
||||
F: FnOnce(
|
||||
SendableRecordBatchStream,
|
||||
) -> PyResult<(
|
||||
SendableRecordBatchStream,
|
||||
Option<Result<RecordBatch, lancedb::Error>>,
|
||||
)>,
|
||||
{
|
||||
let Some(stream) = self
|
||||
.stream
|
||||
.lock()
|
||||
.expect("sync reader mutex poisoned")
|
||||
.take()
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (stream, next) = fetch(stream)?;
|
||||
match next {
|
||||
Some(Ok(batch)) => {
|
||||
*self.stream.lock().expect("sync reader mutex poisoned") = Some(stream);
|
||||
Ok(Some(Ok(batch)))
|
||||
}
|
||||
Some(Err(error)) => {
|
||||
drop(stream);
|
||||
Ok(Some(Err(error)))
|
||||
}
|
||||
None => {
|
||||
drop(stream);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
*self.stream.lock().expect("sync reader mutex poisoned") = None;
|
||||
}
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl SyncRecordBatchStream {
|
||||
#[getter]
|
||||
pub fn schema(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
(*self.schema)
|
||||
.clone()
|
||||
.into_pyarrow(py)
|
||||
.map(|obj| obj.unbind())
|
||||
}
|
||||
|
||||
fn __iter__(self_: PyRef<'_, Self>) -> PyRef<'_, Self> {
|
||||
self_
|
||||
}
|
||||
|
||||
fn __next__(&mut self, py: Python<'_>) -> PyResult<Option<Py<PyAny>>> {
|
||||
let batch = py.detach(|| self.pull())?;
|
||||
let Some(batch) = batch else {
|
||||
return Ok(None);
|
||||
};
|
||||
let batch = match batch.to_pyarrow(py) {
|
||||
Ok(batch) => batch,
|
||||
Err(error) => {
|
||||
self.release();
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
// A signal arriving after the fetch still terminates the reader, so
|
||||
// no execution plan outlives the KeyboardInterrupt.
|
||||
if let Err(error) = py.check_signals() {
|
||||
self.release();
|
||||
return Err(error);
|
||||
}
|
||||
Ok(Some(batch.unbind()))
|
||||
}
|
||||
}
|
||||
|
||||
fn into_py_error(error: lancedb::Error) -> pyo3::PyErr {
|
||||
match Err::<(), _>(error).infer_error() {
|
||||
Ok(()) => unreachable!("infer_error returned Ok for an Err value"),
|
||||
Err(error) => error,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::VecDeque;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use arrow::array::Int32Array;
|
||||
use arrow::datatypes::{DataType, Field, Schema};
|
||||
use futures::Stream;
|
||||
use lancedb::arrow::RecordBatchStream as LanceRecordBatchStream;
|
||||
|
||||
use super::*;
|
||||
|
||||
struct TestStream {
|
||||
schema: SchemaRef,
|
||||
batches: VecDeque<Result<RecordBatch, lancedb::Error>>,
|
||||
polls: Arc<AtomicUsize>,
|
||||
dropped: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl TestStream {
|
||||
fn new(batches: Vec<Result<RecordBatch, lancedb::Error>>) -> Self {
|
||||
let schema = test_schema();
|
||||
Self {
|
||||
schema,
|
||||
batches: batches.into(),
|
||||
polls: Arc::new(AtomicUsize::new(0)),
|
||||
dropped: Arc::new(AtomicBool::new(false)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for TestStream {
|
||||
type Item = Result<RecordBatch, lancedb::Error>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
self.polls.fetch_add(1, Ordering::SeqCst);
|
||||
Poll::Ready(self.batches.pop_front())
|
||||
}
|
||||
}
|
||||
|
||||
impl LanceRecordBatchStream for TestStream {
|
||||
fn schema(&self) -> SchemaRef {
|
||||
Arc::clone(&self.schema)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestStream {
|
||||
fn drop(&mut self) {
|
||||
self.dropped.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
fn test_schema() -> SchemaRef {
|
||||
Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]))
|
||||
}
|
||||
|
||||
fn test_batch(value: i32) -> RecordBatch {
|
||||
RecordBatch::try_new(test_schema(), vec![Arc::new(Int32Array::from(vec![value]))]).unwrap()
|
||||
}
|
||||
|
||||
fn boxed(stream: TestStream) -> SendableRecordBatchStream {
|
||||
Box::pin(stream)
|
||||
}
|
||||
|
||||
fn pull_fake(
|
||||
reader: &mut SyncRecordBatchStream,
|
||||
) -> Result<Option<Result<RecordBatch, lancedb::Error>>, pyo3::PyErr> {
|
||||
reader.pull_with(|mut stream| {
|
||||
let next = futures::executor::block_on(stream.next());
|
||||
Ok((stream, next))
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creation_does_not_poll() {
|
||||
let stream = TestStream::new(vec![Ok(test_batch(1))]);
|
||||
let polls = Arc::clone(&stream.polls);
|
||||
let _reader = SyncRecordBatchStream::new(boxed(stream));
|
||||
assert_eq!(polls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_pull_reads_one_batch_and_keeps_the_stream_resumable() {
|
||||
let stream = TestStream::new(vec![
|
||||
Ok(test_batch(1)),
|
||||
Ok(test_batch(2)),
|
||||
Ok(test_batch(3)),
|
||||
]);
|
||||
let polls = Arc::clone(&stream.polls);
|
||||
let dropped = Arc::clone(&stream.dropped);
|
||||
let mut reader = SyncRecordBatchStream::new(boxed(stream));
|
||||
|
||||
assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok());
|
||||
assert_eq!(polls.load(Ordering::SeqCst), 1);
|
||||
assert!(!dropped.load(Ordering::SeqCst));
|
||||
|
||||
assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok());
|
||||
assert_eq!(polls.load(Ordering::SeqCst), 2);
|
||||
assert!(!dropped.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eof_drops_the_stream_before_returning() {
|
||||
let stream = TestStream::new(vec![Ok(test_batch(1))]);
|
||||
let dropped = Arc::clone(&stream.dropped);
|
||||
let mut reader = SyncRecordBatchStream::new(boxed(stream));
|
||||
|
||||
assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok());
|
||||
assert!(!dropped.load(Ordering::SeqCst));
|
||||
assert!(pull_fake(&mut reader).unwrap().is_none());
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
assert!(pull_fake(&mut reader).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_drops_the_stream_before_returning() {
|
||||
let stream = TestStream::new(vec![Err(lancedb::Error::Runtime {
|
||||
message: "read failed".to_string(),
|
||||
})]);
|
||||
let dropped = Arc::clone(&stream.dropped);
|
||||
let mut reader = SyncRecordBatchStream::new(boxed(stream));
|
||||
|
||||
assert!(pull_fake(&mut reader).unwrap().unwrap().is_err());
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
assert!(pull_fake(&mut reader).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_an_unread_reader_drops_the_stream_without_polling() {
|
||||
let stream = TestStream::new(vec![Ok(test_batch(1))]);
|
||||
let polls = Arc::clone(&stream.polls);
|
||||
let dropped = Arc::clone(&stream.dropped);
|
||||
let reader = SyncRecordBatchStream::new(boxed(stream));
|
||||
|
||||
drop(reader);
|
||||
assert_eq!(polls.load(Ordering::SeqCst), 0);
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
}
|
||||
}
|
||||
@@ -2120,6 +2120,15 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
/// Return an independent handle pinned to the currently selected snapshot.
|
||||
pub fn _checkout_current(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let current = inner.checkout_current().await.infer_error()?;
|
||||
Ok(Table::new(current))
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (version=None))]
|
||||
pub fn restore(
|
||||
self_: PyRef<'_, Self>,
|
||||
@@ -2317,6 +2326,37 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
/// Explain Enterprise version cleanup without submitting a job.
|
||||
#[pyo3(signature = (min_age_seconds=None))]
|
||||
pub fn explain_cleanup<'py>(
|
||||
self_: PyRef<'py, Self>,
|
||||
min_age_seconds: Option<u64>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let mut options = lancedb::table::CleanupOptions::new();
|
||||
options.min_age_seconds = min_age_seconds;
|
||||
future_into_py(self_.py(), async move {
|
||||
let plan = inner.explain_cleanup(options).await.infer_error()?;
|
||||
serde_json::to_string(&plan)
|
||||
.map_err(|error| pyo3::exceptions::PyRuntimeError::new_err(error.to_string()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Submit Enterprise version cleanup and retain its durable job and result.
|
||||
#[pyo3(signature = (min_age_seconds=None))]
|
||||
pub fn cleanup_async<'py>(
|
||||
self_: PyRef<'py, Self>,
|
||||
min_age_seconds: Option<u64>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let mut options = lancedb::table::CleanupOptions::new();
|
||||
options.min_age_seconds = min_age_seconds;
|
||||
future_into_py(self_.py(), async move {
|
||||
let job = inner.cleanup_async(options).await.infer_error()?;
|
||||
Ok(crate::job::Job::new_typed(job))
|
||||
})
|
||||
}
|
||||
|
||||
/// Submit remote compaction and retain its durable job and actual result.
|
||||
#[pyo3(signature = (compaction_options=None))]
|
||||
pub fn compact_async<'py>(
|
||||
|
||||
@@ -15,7 +15,7 @@ use crate::{
|
||||
Error, Result, Table,
|
||||
arrow::{SendableRecordBatchStream, SendableRecordBatchStreamExt, SimpleRecordBatchStream},
|
||||
connect,
|
||||
database::{CreateTableRequest, Database},
|
||||
database::{CreateTableMode, CreateTableRequest, Database},
|
||||
dataloader::permutation::{
|
||||
shuffle::{Shuffler, ShufflerConfig},
|
||||
split::{SPLIT_ID_COLUMN, SplitStrategy, Splitter},
|
||||
@@ -43,7 +43,34 @@ enum PermutationDestination {
|
||||
#[default]
|
||||
Temporary,
|
||||
/// The permutation table is a permanent table in a database
|
||||
Permanent(Arc<dyn Database>, String),
|
||||
Permanent {
|
||||
database: Arc<dyn Database>,
|
||||
table_name: String,
|
||||
namespace_path: Vec<String>,
|
||||
mode: PermutationPersistMode,
|
||||
},
|
||||
}
|
||||
|
||||
/// How a persisted permutation table handles an existing table of the same name.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum PermutationPersistMode {
|
||||
/// Fail if the destination table already exists.
|
||||
#[default]
|
||||
Create,
|
||||
/// Replace the destination table with the new plan.
|
||||
///
|
||||
/// The previous table version remains readable by handles that were already
|
||||
/// opened against it.
|
||||
Overwrite,
|
||||
}
|
||||
|
||||
/// Options for storing a permutation table in a database.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct PermutationPersistOptions {
|
||||
/// The namespace path to create the table in. Empty means the root namespace.
|
||||
pub namespace_path: Vec<String>,
|
||||
/// Whether an existing table may be replaced.
|
||||
pub mode: PermutationPersistMode,
|
||||
}
|
||||
|
||||
/// Configuration for creating a permutation table
|
||||
@@ -161,9 +188,29 @@ impl PermutationBuilder {
|
||||
/// Stores the permutation as a table in a database
|
||||
///
|
||||
/// By default, the permutation is stored in memory. If this method is called then
|
||||
/// the permutation will be stored as a table in the given database.
|
||||
pub fn persist(mut self, database: Arc<dyn Database>, table_name: String) -> Self {
|
||||
self.config.destination = PermutationDestination::Permanent(database, table_name);
|
||||
/// the permutation will be stored as a table in the given database. The table is
|
||||
/// created in the root namespace and an existing table is not replaced; use
|
||||
/// [`Self::persist_with_options`] to choose a namespace or overwrite mode.
|
||||
pub fn persist(self, database: Arc<dyn Database>, table_name: String) -> Self {
|
||||
self.persist_with_options(database, table_name, PermutationPersistOptions::default())
|
||||
}
|
||||
|
||||
/// Stores the permutation as a table in a database with explicit options.
|
||||
///
|
||||
/// This is the same as [`Self::persist`] but lets the caller select the target
|
||||
/// namespace and whether an existing table may be overwritten.
|
||||
pub fn persist_with_options(
|
||||
mut self,
|
||||
database: Arc<dyn Database>,
|
||||
table_name: String,
|
||||
options: PermutationPersistOptions,
|
||||
) -> Self {
|
||||
self.config.destination = PermutationDestination::Permanent {
|
||||
database,
|
||||
table_name,
|
||||
namespace_path: options.namespace_path,
|
||||
mode: options.mode,
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
@@ -369,17 +416,31 @@ impl PermutationBuilder {
|
||||
let streaming_data = Self::add_config_metadata(renamed, metadata)?;
|
||||
|
||||
let (name, database) = match &self.config.destination {
|
||||
PermutationDestination::Permanent(database, table_name) => {
|
||||
(table_name.as_str(), database.clone())
|
||||
}
|
||||
PermutationDestination::Permanent {
|
||||
database,
|
||||
table_name,
|
||||
..
|
||||
} => (table_name.as_str(), database.clone()),
|
||||
PermutationDestination::Temporary => {
|
||||
let conn = connect("memory:///").execute().await?;
|
||||
("permutation", conn.database().clone())
|
||||
}
|
||||
};
|
||||
|
||||
let create_table_request =
|
||||
let mut create_table_request =
|
||||
CreateTableRequest::new(name.to_string(), Box::new(streaming_data));
|
||||
if let PermutationDestination::Permanent {
|
||||
namespace_path,
|
||||
mode,
|
||||
..
|
||||
} = &self.config.destination
|
||||
{
|
||||
create_table_request.namespace_path = namespace_path.clone();
|
||||
create_table_request.mode = match mode {
|
||||
PermutationPersistMode::Create => CreateTableMode::Create,
|
||||
PermutationPersistMode::Overwrite => CreateTableMode::Overwrite,
|
||||
};
|
||||
}
|
||||
|
||||
let table = database.create_table(create_table_request).await?;
|
||||
|
||||
@@ -1034,4 +1095,89 @@ mod tests {
|
||||
);
|
||||
assert!(metadata.contains_key(BASE_VERSION_CONFIG_KEY));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_permutation_persist_create_overwrite_and_namespace() {
|
||||
use lance_namespace::models::CreateNamespaceRequest;
|
||||
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let db = connect(temp_dir.path().to_str().unwrap())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let initial_data = lance_datagen::gen_batch()
|
||||
.col("col_a", lance_datagen::array::step::<Int32Type>())
|
||||
.into_ldb_stream(RowCount::from(100), BatchCount::from(1));
|
||||
let data_table = db
|
||||
.create_table("base_tbl", initial_data)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let namespace_path = vec!["plans".to_string()];
|
||||
db.create_namespace(CreateNamespaceRequest {
|
||||
id: Some(namespace_path.clone()),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let persist = |mode| PermutationPersistOptions {
|
||||
namespace_path: namespace_path.clone(),
|
||||
mode,
|
||||
};
|
||||
let first_plan = PermutationBuilder::new(data_table.clone())
|
||||
.persist_with_options(
|
||||
db.database().clone(),
|
||||
"splits".to_string(),
|
||||
persist(PermutationPersistMode::Create),
|
||||
)
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
let first_version = first_plan.version().await.unwrap();
|
||||
assert_eq!(first_plan.count_rows(None).await.unwrap(), 100);
|
||||
|
||||
let opened = db
|
||||
.open_table("splits")
|
||||
.namespace(namespace_path.clone())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(opened.count_rows(None).await.unwrap(), 100);
|
||||
|
||||
let err = PermutationBuilder::new(data_table.clone())
|
||||
.persist_with_options(
|
||||
db.database().clone(),
|
||||
"splits".to_string(),
|
||||
persist(PermutationPersistMode::Create),
|
||||
)
|
||||
.build()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, Error::TableAlreadyExists { .. }),
|
||||
"expected TableAlreadyExists, got: {err:?}"
|
||||
);
|
||||
|
||||
let more_data = lance_datagen::gen_batch()
|
||||
.col("col_a", lance_datagen::array::step::<Int32Type>())
|
||||
.into_ldb_stream(RowCount::from(50), BatchCount::from(1));
|
||||
data_table.add(more_data).execute().await.unwrap();
|
||||
|
||||
let second_plan = PermutationBuilder::new(data_table)
|
||||
.persist_with_options(
|
||||
db.database().clone(),
|
||||
"splits".to_string(),
|
||||
persist(PermutationPersistMode::Overwrite),
|
||||
)
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(second_plan.count_rows(None).await.unwrap(), 150);
|
||||
|
||||
// Overwrite creates a new table version; the old handle stays on its snapshot.
|
||||
assert_eq!(first_plan.count_rows(None).await.unwrap(), 100);
|
||||
assert_eq!(first_plan.version().await.unwrap(), first_version);
|
||||
}
|
||||
}
|
||||
|
||||
+159
-2
@@ -742,8 +742,14 @@ pub trait ExecutableQuery {
|
||||
/// an Stream of Arrow [`arrow_array::RecordBatch`] (and you can also independently
|
||||
/// access the [`arrow_schema::Schema`] without polling the stream).
|
||||
///
|
||||
/// Note: The size of the returned batches and the order of individual rows is
|
||||
/// not deterministic.
|
||||
/// Note: The size of the returned batches is not deterministic. Row order
|
||||
/// depends on the query shape: an ordinary unfiltered base-only scan of a
|
||||
/// fixed table version in Embedded returns manifest order unless
|
||||
/// [`Query::scan_in_order`] is set to `false` or a nonempty
|
||||
/// [`QueryBase::order_by`] adds a sort. RTE
|
||||
/// tables scan the LSM by default; use `use_rte(false)` for the base-only
|
||||
/// guarantee. Ranked searches return rank order, while Enterprise and
|
||||
/// namespace-pushed scans have no order guarantee.
|
||||
///
|
||||
/// LanceDb will use many threads to calculate results and, when
|
||||
/// the result set is large, multiple batches will be processed at one time.
|
||||
@@ -922,6 +928,11 @@ pub struct QueryRequest {
|
||||
/// This allows ordering query results by one or more columns in either ascending or descending order.
|
||||
pub order_by: Option<Vec<ColumnOrdering>>,
|
||||
|
||||
/// Require (`Some(true)`), allow (`Some(false)`), or leave unchanged (`None`)
|
||||
/// the scan order. See [`Query::scan_in_order`] for the contract and its
|
||||
/// boundaries.
|
||||
pub scan_in_order: Option<bool>,
|
||||
|
||||
/// Controls RTE read routing. When unset (the default), a query against a
|
||||
/// table that carries an RTE write spec (see
|
||||
/// [`crate::Table::enable_rte`]) is routed through the LSM scanner so
|
||||
@@ -956,6 +967,7 @@ impl Default for QueryRequest {
|
||||
norm: None,
|
||||
disable_scoring_autoprojection: false,
|
||||
order_by: None,
|
||||
scan_in_order: None,
|
||||
use_rte: None,
|
||||
}
|
||||
}
|
||||
@@ -1044,6 +1056,64 @@ impl Query {
|
||||
VectorQuery::new(self)
|
||||
}
|
||||
|
||||
/// Require the results to follow storage order instead of allowing an
|
||||
/// unordered scan.
|
||||
///
|
||||
/// An unfiltered plain base-only scan of an Embedded table, pinned to one
|
||||
/// dataset version, returns rows in that version's manifest order:
|
||||
/// fragments in manifest order, then rows in fragment order. Ordinary
|
||||
/// unfiltered base-only scans already use Lance's ordered scan by default,
|
||||
/// so leaving this unset preserves that behavior. RTE tables scan the LSM
|
||||
/// by default and do not provide this guarantee unless `use_rte(false)`
|
||||
/// selects the base table. Use `true` when a caller assigns meaning to row
|
||||
/// positions and must fail instead of silently receiving a different order.
|
||||
///
|
||||
/// Explicit `true` also disables scalar-index filter planning. Legacy
|
||||
/// scalar-index plans can materialize index rows in a different sequence,
|
||||
/// so filters are evaluated over the manifest-ordered scan instead. Default
|
||||
/// filtered scans can still use those plans and may not preserve manifest
|
||||
/// order. The filter result is unchanged, but the scan can read more data.
|
||||
///
|
||||
/// Leaving this unset preserves the backend default. In particular, a
|
||||
/// namespace-backed native table configured for `QueryTable` pushdown may
|
||||
/// not preserve order because the request has no order field; request
|
||||
/// `true` to execute against Embedded storage.
|
||||
///
|
||||
/// The order is fixed only for the dataset version being scanned.
|
||||
/// Compaction, updates, or opening a newer version can change it, so pin a
|
||||
/// version when positions must remain stable across executions. A latest
|
||||
/// handle can also observe a different version between two executions.
|
||||
///
|
||||
/// - `true` requires manifest order without adding a sort. A nonempty
|
||||
/// [`QueryBase::order_by`], take query, vector, full-text, hybrid, or
|
||||
/// reranked query conflicts with storage order and fails with
|
||||
/// [`Error::InvalidInput`].
|
||||
/// Enterprise tables and RTE/LSM reads fail with [`Error::NotSupported`]
|
||||
/// because they cannot uphold the requirement; set `use_rte(false)` to
|
||||
/// read the RTE base table in storage order. Namespace-backed native
|
||||
/// tables execute against Embedded storage instead of using `QueryTable`
|
||||
/// pushdown, which has no order field, and fail if that storage cannot be
|
||||
/// read.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use lancedb::query::ExecutableQuery;
|
||||
/// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> {
|
||||
/// let rows = table.query().scan_in_order(true).execute().await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
/// - `false` allows the backend to scan without preserving order. An
|
||||
/// explicit nonempty `order_by` still applies its sort.
|
||||
///
|
||||
/// A nonempty `order_by` replaces manifest order with a global sort. Vector
|
||||
/// and full-text searches return ranked results regardless of this option.
|
||||
pub fn scan_in_order(mut self, ordered: bool) -> Self {
|
||||
self.request.scan_in_order = Some(ordered);
|
||||
self
|
||||
}
|
||||
|
||||
/// Find the nearest vectors to the given query vector.
|
||||
///
|
||||
/// This converts the query from a plain query to a vector query.
|
||||
@@ -2086,6 +2156,20 @@ struct TakeLookup {
|
||||
output_projection: Option<Vec<(String, String)>>,
|
||||
}
|
||||
|
||||
/// Take queries restore rows in the requested offset or row-id order, so an
|
||||
/// explicit storage-order requirement cannot be honored. Check this before the
|
||||
/// lookup strips the take selectors and hands the inner request to a scan.
|
||||
pub(crate) fn validate_take_scan_in_order(request: &QueryRequest) -> Result<()> {
|
||||
if request.scan_in_order == Some(true) {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "scan_in_order(true) conflicts with take by row id or offset, which \
|
||||
defines its own result order"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl TakeQuery {
|
||||
/// Create a new `TakeQuery` that will return rows at the given offsets.
|
||||
///
|
||||
@@ -2200,6 +2284,7 @@ impl TakeQuery {
|
||||
request: &QueryRequest,
|
||||
preserve_order: bool,
|
||||
) -> Result<TakeLookup> {
|
||||
validate_take_scan_in_order(request)?;
|
||||
let (indices, by_row_id) = match (&request.take_offsets, &request.take_row_ids) {
|
||||
(Some(indices), None) => (indices.clone(), false),
|
||||
(None, Some(indices)) => (indices.clone(), true),
|
||||
@@ -4564,6 +4649,78 @@ mod tests {
|
||||
assert!(!analyzed.contains("CoalescePartitionsExec"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_take_scan_in_order_is_rejected_before_lookup() {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
let table = make_test_table(&tmp_dir).await;
|
||||
|
||||
let mut offsets = table
|
||||
.take_offsets(vec![5, 1, 17])
|
||||
.select(Select::Columns(vec!["id".to_string()]))
|
||||
.limit(2)
|
||||
.offset(1);
|
||||
offsets.mut_query().scan_in_order = Some(true);
|
||||
|
||||
let plan_err = offsets
|
||||
.create_plan(QueryExecutionOptions::default())
|
||||
.await
|
||||
.expect_err("take planning must reject scan_in_order(true)");
|
||||
assert!(
|
||||
matches!(&plan_err, Error::InvalidInput { message }
|
||||
if message.contains("take by row id or offset")),
|
||||
"unexpected error: {plan_err}"
|
||||
);
|
||||
|
||||
let execution_err = offsets
|
||||
.execute()
|
||||
.await
|
||||
.err()
|
||||
.expect("take execution must reject scan_in_order(true)");
|
||||
assert!(
|
||||
matches!(&execution_err, Error::InvalidInput { message }
|
||||
if message.contains("take by row id or offset")),
|
||||
"unexpected error: {execution_err}"
|
||||
);
|
||||
|
||||
let explain_err = offsets
|
||||
.explain_plan(false)
|
||||
.await
|
||||
.expect_err("take explain must reject scan_in_order(true)");
|
||||
assert!(
|
||||
matches!(&explain_err, Error::InvalidInput { message }
|
||||
if message.contains("take by row id or offset")),
|
||||
"unexpected error: {explain_err}"
|
||||
);
|
||||
|
||||
let mut row_ids = table.take_row_ids(vec![5, 1]);
|
||||
row_ids.mut_query().scan_in_order = Some(true);
|
||||
let row_id_err = row_ids
|
||||
.execute()
|
||||
.await
|
||||
.err()
|
||||
.expect("take by row id must reject scan_in_order(true)");
|
||||
assert!(
|
||||
matches!(&row_id_err, Error::InvalidInput { message }
|
||||
if message.contains("take by row id or offset")),
|
||||
"unexpected error: {row_id_err}"
|
||||
);
|
||||
|
||||
// Allowing unordered scans leaves an ordinary take unchanged.
|
||||
let mut allowed = table.take_offsets(vec![5, 1]);
|
||||
allowed.mut_query().scan_in_order = Some(false);
|
||||
let batches = allowed
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::unsorted(vec![5, 1, 17], vec![5, 1, 17])]
|
||||
#[case::duplicate_and_missing(vec![17, 5, 17, u64::MAX, 1], vec![17, 5, 17, 1])]
|
||||
|
||||
@@ -4802,6 +4802,84 @@ async fn remote_prewarm_rejects_historical_checkout_without_submitting() {
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_cleanup_tracks_registry_job_and_real_result() {
|
||||
use crate::table::CleanupOptions;
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
result: RecordBatch::try_from_iter([(
|
||||
"job_id",
|
||||
Arc::new(StringArray::from(vec!["cleanup-job"])) as ArrayRef,
|
||||
)])
|
||||
.unwrap(),
|
||||
..Default::default()
|
||||
};
|
||||
let statements = service.statements.clone();
|
||||
let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await;
|
||||
let polls = Arc::new(AtomicUsize::new(0));
|
||||
let observed = polls.clone();
|
||||
let client = client_with_handler(move |request| {
|
||||
assert_eq!(request.url().path(), "/v1/jobs/describe");
|
||||
observed.fetch_add(1, Ordering::SeqCst);
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body(
|
||||
serde_json::json!({
|
||||
"job_id":"cleanup-job","job_type":"cleanup","job_state":"DONE",
|
||||
"result":{"format_version":1,"min_age_seconds":0,"statistics_complete":true,
|
||||
"old_versions":2,"bytes_removed":123}
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
let table = RemoteTable::new_with_sql_client(
|
||||
client,
|
||||
"analytics".into(),
|
||||
"events".into(),
|
||||
vec!["team".into(), "inner".into()],
|
||||
"team$inner$events".into(),
|
||||
Default::default(),
|
||||
Some(sql),
|
||||
)
|
||||
.with_branch(Some("o'brien".into()));
|
||||
let job = table
|
||||
.cleanup_async(CleanupOptions::new().min_age_seconds(0))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(job.id(), Some("cleanup-job"));
|
||||
assert_eq!(polls.load(Ordering::SeqCst), 0);
|
||||
let result = job.wait().await.unwrap();
|
||||
assert_eq!(result.old_versions, Some(2));
|
||||
assert_eq!(result.bytes_removed, Some(123));
|
||||
assert_eq!(
|
||||
*statements.lock().unwrap(),
|
||||
["VACUUM \"events\" WITH (branch = 'o''brien', min_age_seconds = 0)"]
|
||||
);
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_cleanup_rejects_historical_checkout_without_submitting() {
|
||||
let table = RemoteTable::new_with_sql_client(
|
||||
client_with_handler(|request| {
|
||||
assert_eq!(request.url().path(), "/v1/table/events/describe/");
|
||||
http::Response::builder()
|
||||
.status(200)
|
||||
.body(r#"{"version":7,"schema":{"fields":[]}}"#.to_string())
|
||||
.unwrap()
|
||||
}),
|
||||
"analytics".into(),
|
||||
"events".into(),
|
||||
vec![],
|
||||
"events".into(),
|
||||
Default::default(),
|
||||
None,
|
||||
);
|
||||
table.checkout(7).await.unwrap();
|
||||
assert!(table.cleanup_async(Default::default()).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_compaction_tracks_registry_job_and_real_result() {
|
||||
use crate::table::optimize::CompactionOverrides;
|
||||
@@ -4943,3 +5021,48 @@ async fn remote_prewarm_preview_uses_sql_without_any_http_jobs() {
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_cleanup_preview_uses_sql_without_job_calls() {
|
||||
let payload = serde_json::json!({"format_version":1,"source_version":42,"min_age_seconds":0,
|
||||
"cutoff_millis":123,"versions_to_remove":2,"bytes_to_remove":100});
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
result: RecordBatch::try_from_iter([
|
||||
(
|
||||
"plan_type",
|
||||
Arc::new(StringArray::from(vec!["logical_plan"])) as ArrayRef,
|
||||
),
|
||||
(
|
||||
"plan",
|
||||
Arc::new(StringArray::from(vec![payload.to_string()])) as ArrayRef,
|
||||
),
|
||||
])
|
||||
.unwrap(),
|
||||
..Default::default()
|
||||
};
|
||||
let statements = service.statements.clone();
|
||||
let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await;
|
||||
let table = RemoteTable::new_with_sql_client(
|
||||
client_with_handler(|_| -> http::Response<String> {
|
||||
panic!("preview must not use HTTP jobs or execution fallback")
|
||||
}),
|
||||
"analytics".into(),
|
||||
"events".into(),
|
||||
vec!["team".into()],
|
||||
"team$events".into(),
|
||||
Default::default(),
|
||||
Some(sql),
|
||||
);
|
||||
let plan = table
|
||||
.explain_cleanup(crate::table::CleanupOptions::new().min_age_seconds(0))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(plan.source_version, 42);
|
||||
assert_eq!(plan.versions_to_remove, 2);
|
||||
assert_eq!(
|
||||
*statements.lock().unwrap(),
|
||||
["EXPLAIN (FORMAT JSON) VACUUM \"events\" WITH (min_age_seconds = 0)"]
|
||||
);
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
pub mod blobs;
|
||||
mod cleanup;
|
||||
pub mod insert;
|
||||
mod ipc_stream;
|
||||
mod optimize;
|
||||
@@ -1326,6 +1327,13 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
params: &QueryRequest,
|
||||
) -> Result<()> {
|
||||
params.check_filter()?;
|
||||
if params.scan_in_order == Some(true) {
|
||||
return Err(Error::NotSupported {
|
||||
message: "scan_in_order(true) requires an ordered scan of Embedded storage; \
|
||||
LanceDB Enterprise tables do not support storage-order scans yet"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
body["prefilter"] = params.prefilter.into();
|
||||
// Only forward use_rte when explicitly set; a server that predates it
|
||||
// ignores the field and routes as it would by default.
|
||||
@@ -4168,6 +4176,67 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
prune: None,
|
||||
})
|
||||
}
|
||||
async fn explain_cleanup(
|
||||
&self,
|
||||
options: crate::table::CleanupOptions,
|
||||
) -> Result<crate::table::CleanupPlan> {
|
||||
self.check_mutable().await?;
|
||||
let statement = format!(
|
||||
"EXPLAIN (FORMAT JSON) {}",
|
||||
cleanup::statement(&self.name, self.branch.as_deref(), &options)?
|
||||
);
|
||||
let client = self.sql_client.as_ref().ok_or_else(|| Error::NotSupported {
|
||||
message: "cleanup previews require a Flight SQL endpoint with EXPLAIN (FORMAT JSON) VACUUM support".into(),
|
||||
})?;
|
||||
let query = client
|
||||
.execute(crate::database::ExecuteQueryRequest {
|
||||
query: statement,
|
||||
default_namespace_path: self.namespace.clone(),
|
||||
parameters: None,
|
||||
})
|
||||
.await
|
||||
.map_err(cleanup::map_error)?;
|
||||
let mut reader = query.reader().await.map_err(cleanup::map_error)?;
|
||||
let mut batches = Vec::new();
|
||||
while let Some(batch) = reader.try_next().await.map_err(cleanup::map_error)? {
|
||||
batches.push(batch);
|
||||
}
|
||||
cleanup::plan(&batches)
|
||||
}
|
||||
|
||||
async fn cleanup_async(
|
||||
&self,
|
||||
options: crate::table::CleanupOptions,
|
||||
) -> Result<Job<crate::table::CleanupResult>> {
|
||||
self.check_mutable().await?;
|
||||
let statement = cleanup::statement(&self.name, self.branch.as_deref(), &options)?;
|
||||
let client = self
|
||||
.sql_client
|
||||
.as_ref()
|
||||
.ok_or_else(|| Error::NotSupported {
|
||||
message: "manual cleanup requires a Flight SQL endpoint and SQL VACUUM support"
|
||||
.into(),
|
||||
})?;
|
||||
let query = client
|
||||
.execute(crate::database::ExecuteQueryRequest {
|
||||
query: statement,
|
||||
default_namespace_path: self.namespace.clone(),
|
||||
parameters: None,
|
||||
})
|
||||
.await
|
||||
.map_err(cleanup::map_error)?;
|
||||
let mut reader = query.reader().await.map_err(cleanup::map_error)?;
|
||||
let mut batches = Vec::new();
|
||||
while let Some(batch) = reader.try_next().await.map_err(cleanup::map_error)? {
|
||||
batches.push(batch);
|
||||
}
|
||||
let job_id = cleanup::receipt(&batches)?;
|
||||
Ok(Job::new_typed(Box::new(RemoteJob::new(
|
||||
self.client.clone(),
|
||||
job_id,
|
||||
))))
|
||||
}
|
||||
|
||||
async fn compact_async(
|
||||
&self,
|
||||
options: crate::table::optimize::CompactionOverrides,
|
||||
@@ -6718,6 +6787,27 @@ mod tests {
|
||||
assert_eq!(result.version, if old_server { 0 } else { 43 });
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_query_scan_in_order_true_is_not_supported() {
|
||||
let table = Table::new_with_handler::<&str>("my_table", |_| {
|
||||
panic!("scan_in_order(true) must fail before sending a request")
|
||||
});
|
||||
|
||||
let err = table
|
||||
.query()
|
||||
.scan_in_order(true)
|
||||
.execute()
|
||||
.await
|
||||
.err()
|
||||
.expect("remote scans cannot guarantee manifest order");
|
||||
assert!(
|
||||
matches!(&err, Error::NotSupported { message }
|
||||
if message.contains("scan_in_order(true)")
|
||||
&& message.contains("Enterprise tables")),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_query_plain() {
|
||||
let expected_data = RecordBatch::try_new(
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! SQL VACUUM submission; never replay an ambiguous acceptance response.
|
||||
|
||||
use crate::{Error, Result, table::CleanupOptions};
|
||||
use arrow_array::{Array, RecordBatch, StringArray};
|
||||
|
||||
pub(super) fn statement(
|
||||
table: &str,
|
||||
branch: Option<&str>,
|
||||
options: &CleanupOptions,
|
||||
) -> Result<String> {
|
||||
let mut settings = Vec::new();
|
||||
if let Some(branch) = branch {
|
||||
if branch.trim().is_empty() {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "cleanup branch must not be empty".into(),
|
||||
});
|
||||
}
|
||||
settings.push(format!("branch = {}", super::quote_sql_string(branch)));
|
||||
}
|
||||
if let Some(age) = options.min_age_seconds {
|
||||
if i64::try_from(age)
|
||||
.ok()
|
||||
.and_then(chrono::Duration::try_seconds)
|
||||
.and_then(|duration| chrono::Utc::now().checked_sub_signed(duration))
|
||||
.is_none()
|
||||
{
|
||||
return Err(Error::InvalidInput {
|
||||
message: "min_age_seconds is out of range".into(),
|
||||
});
|
||||
}
|
||||
settings.push(format!("min_age_seconds = {age}"));
|
||||
}
|
||||
let mut sql = format!("VACUUM {}", super::quote_sql_identifier(table));
|
||||
if !settings.is_empty() {
|
||||
sql.push_str(&format!(" WITH ({})", settings.join(", ")));
|
||||
}
|
||||
Ok(sql)
|
||||
}
|
||||
|
||||
pub(super) fn receipt(batches: &[RecordBatch]) -> Result<String> {
|
||||
let invalid = || {
|
||||
Error::Runtime { message: "VACUUM did not return a single nonempty job_id receipt; inspect jobs before retrying because cleanup may already have been submitted".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 ids = batch
|
||||
.column_by_name("job_id")
|
||||
.and_then(|array| array.as_any().downcast_ref::<StringArray>())
|
||||
.ok_or_else(invalid)?;
|
||||
if ids.is_null(0) || ids.value(0).trim().is_empty() {
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(ids.value(0).to_string())
|
||||
}
|
||||
|
||||
pub(super) fn plan(batches: &[RecordBatch]) -> Result<crate::table::CleanupPlan> {
|
||||
let invalid = || {
|
||||
Error::Runtime { message: "EXPLAIN VACUUM did not return a valid versioned preview; a compatible EXPLAIN (FORMAT JSON) VACUUM server is required. No execution fallback was attempted".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 kind = batch
|
||||
.column_by_name("plan_type")
|
||||
.and_then(|column| column.as_any().downcast_ref::<StringArray>())
|
||||
.ok_or_else(invalid)?;
|
||||
let payload = batch
|
||||
.column_by_name("plan")
|
||||
.and_then(|column| column.as_any().downcast_ref::<StringArray>())
|
||||
.ok_or_else(invalid)?;
|
||||
if kind.is_null(0) || kind.value(0) != "logical_plan" || payload.is_null(0) {
|
||||
return Err(invalid());
|
||||
}
|
||||
serde_json::from_str(payload.value(0)).map_err(|_| invalid())
|
||||
}
|
||||
|
||||
pub(super) fn map_error(error: Error) -> Error {
|
||||
fn unsupported(error: &Error) -> Option<&Error> {
|
||||
match error {
|
||||
Error::Sql {
|
||||
message, grpc_code, ..
|
||||
} => {
|
||||
let message = message.to_ascii_lowercase();
|
||||
(*grpc_code == tonic::Code::Unimplemented as i32
|
||||
|| (*grpc_code == tonic::Code::Internal as i32
|
||||
&& message.contains("invalid explain format")
|
||||
&& message.contains("json"))
|
||||
|| (*grpc_code == tonic::Code::InvalidArgument as i32
|
||||
&& (message.contains("parsererror")
|
||||
|| message.contains("unknown vacuum option")
|
||||
|| message.contains("vacuum is not supported by this deployment"))))
|
||||
.then_some(error)
|
||||
}
|
||||
Error::JobFailed { failure, .. } => failure.source.as_deref().and_then(unsupported),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
if let Some(source) = unsupported(&error) {
|
||||
let diagnostic = if matches!(error, Error::Sql { .. }) {
|
||||
error.to_string()
|
||||
} else {
|
||||
format!("{error}; {source}")
|
||||
};
|
||||
Error::NotSupported {
|
||||
message: format!(
|
||||
"Manual cleanup requires a compatible SQL VACUUM server; upgrade the server. No options were removed and no REST fallback was attempted. Server diagnostic: {diagnostic}"
|
||||
),
|
||||
}
|
||||
} else {
|
||||
error
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn wrapped_cleanup_compatibility_keeps_job_and_request_identity() {
|
||||
let sql = Error::Sql {
|
||||
message: "ParserError: found VACUUM".into(),
|
||||
request_id: "cleanup-request".into(),
|
||||
grpc_code: tonic::Code::InvalidArgument as i32,
|
||||
metadata: Default::default(),
|
||||
};
|
||||
let error = Error::JobFailed {
|
||||
job_id: Some("query-job".into()),
|
||||
failure: Box::new(crate::error::JobFailure {
|
||||
phase: Some("planning".into()),
|
||||
message: Some("statement failed".into()),
|
||||
source: Some(Arc::new(sql)),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
let mapped = map_error(error);
|
||||
assert!(matches!(mapped, Error::NotSupported { .. }));
|
||||
let diagnostic = mapped.to_string();
|
||||
assert!(diagnostic.contains("query-job"));
|
||||
assert!(diagnostic.contains("cleanup-request"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_statement_preserves_inheritance_zero_and_quoting() {
|
||||
assert_eq!(
|
||||
statement("events", None, &CleanupOptions::new()).unwrap(),
|
||||
"VACUUM \"events\""
|
||||
);
|
||||
assert_eq!(
|
||||
statement(
|
||||
"a\"b",
|
||||
Some("o'brien"),
|
||||
&CleanupOptions::new().min_age_seconds(0)
|
||||
)
|
||||
.unwrap(),
|
||||
"VACUUM \"a\"\"b\" WITH (branch = 'o''brien', min_age_seconds = 0)"
|
||||
);
|
||||
assert!(statement("t", None, &CleanupOptions::new().min_age_seconds(u64::MAX)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_cleanup_receipts_never_become_query_handles() {
|
||||
let batch = |values: Vec<Option<&str>>| {
|
||||
RecordBatch::try_from_iter([(
|
||||
"job_id",
|
||||
Arc::new(StringArray::from(values)) as arrow_array::ArrayRef,
|
||||
)])
|
||||
.unwrap()
|
||||
};
|
||||
for batches in [
|
||||
vec![],
|
||||
vec![batch(vec![])],
|
||||
vec![batch(vec![None])],
|
||||
vec![batch(vec![Some("")])],
|
||||
vec![batch(vec![Some("one"), Some("two")])],
|
||||
] {
|
||||
assert!(
|
||||
receipt(&batches)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("inspect jobs before retrying")
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
receipt(&[batch(vec![]), batch(vec![Some("durable-job")])]).unwrap(),
|
||||
"durable-job"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_compatibility_preserves_permissions_and_transport_errors() {
|
||||
for (code, diagnostic, expected) in [
|
||||
(
|
||||
tonic::Code::InvalidArgument,
|
||||
"ParserError: found VACUUM",
|
||||
true,
|
||||
),
|
||||
(
|
||||
tonic::Code::InvalidArgument,
|
||||
"Unknown VACUUM option future",
|
||||
true,
|
||||
),
|
||||
(tonic::Code::PermissionDenied, "ParserError: denied", false),
|
||||
(tonic::Code::Unavailable, "transport unavailable", false),
|
||||
(
|
||||
tonic::Code::InvalidArgument,
|
||||
"min_age_seconds is out of range",
|
||||
false,
|
||||
),
|
||||
] {
|
||||
let error = Error::Sql {
|
||||
message: diagnostic.into(),
|
||||
request_id: "cleanup-request".into(),
|
||||
grpc_code: code as i32,
|
||||
metadata: Default::default(),
|
||||
};
|
||||
let mapped = map_error(error);
|
||||
assert_eq!(matches!(mapped, Error::NotSupported { .. }), expected);
|
||||
assert!(mapped.to_string().contains("cleanup-request"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,6 +89,8 @@ pub mod function_column_status;
|
||||
pub mod merge;
|
||||
pub mod optimize;
|
||||
pub use optimize::CompactionResult;
|
||||
mod cleanup;
|
||||
pub use cleanup::{CleanupOptions, CleanupPlan, CleanupResult};
|
||||
mod prewarm;
|
||||
pub use prewarm::{PrewarmDataOptions, PrewarmDataPlan, PrewarmDataResult, PrewarmPruningSummary};
|
||||
pub(crate) mod primary_key;
|
||||
@@ -907,6 +909,19 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
|
||||
async fn tags(&self) -> Result<Box<dyn Tags + '_>>;
|
||||
/// Optimize the dataset.
|
||||
async fn optimize(&self, action: OptimizeAction) -> Result<OptimizeStats>;
|
||||
/// Submit Enterprise version cleanup and retain its durable job and outcome.
|
||||
async fn cleanup_async(&self, _options: CleanupOptions) -> Result<Job<CleanupResult>> {
|
||||
Err(Error::NotSupported {
|
||||
message: "durable cleanup jobs are only supported on remote tables".into(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn explain_cleanup(&self, _options: CleanupOptions) -> Result<CleanupPlan> {
|
||||
Err(Error::NotSupported {
|
||||
message: "cleanup previews require LanceDB Enterprise".into(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Submit remote compaction and retain its durable job and actual outcome.
|
||||
async fn compact_async(
|
||||
&self,
|
||||
@@ -1897,10 +1912,17 @@ impl Table {
|
||||
/// Create a [`Query`] Builder.
|
||||
///
|
||||
/// Queries allow you to search your existing data. By default the query will
|
||||
/// return all the data in the table in no particular order. The builder
|
||||
/// return all the data in the table. The builder
|
||||
/// returned by this method can be used to control the query using filtering,
|
||||
/// vector similarity, sorting, and more.
|
||||
///
|
||||
/// An ordinary unfiltered base-only scan of a fixed table version in
|
||||
/// Embedded returns manifest order: fragments in manifest order, then rows
|
||||
/// in fragment order. RTE tables scan the LSM by default; use
|
||||
/// `use_rte(false)` for the base table guarantee. Compaction, updates, and
|
||||
/// newer versions can change that order. Use [`Query::scan_in_order`] to
|
||||
/// require it explicitly and fail on paths that cannot uphold it.
|
||||
///
|
||||
/// Note: By default, all columns are returned. For best performance, you should
|
||||
/// only fetch the columns you need. See [`Query::select_with_projection`] for
|
||||
/// more details.
|
||||
@@ -1967,8 +1989,10 @@ impl Table {
|
||||
///
|
||||
/// ## Full scan
|
||||
///
|
||||
/// This query will return everything in the table in no particular
|
||||
/// order.
|
||||
/// This query returns everything in the table. On an Embedded table, an
|
||||
/// ordinary unfiltered base-only scan of a fixed version returns manifest
|
||||
/// order. RTE tables scan the LSM by default and need `use_rte(false)` for
|
||||
/// base manifest order.
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use arrow_array::RecordBatch;
|
||||
@@ -2131,6 +2155,35 @@ impl Table {
|
||||
self.inner.compact_async(options).await
|
||||
}
|
||||
|
||||
/// Submit durable version cleanup through SQL VACUUM and return after acceptance.
|
||||
///
|
||||
/// Retention resolves invocation > selected table/branch > deployment. Requires
|
||||
/// Ownership and parent Usage. Local and historical handles are unsupported.
|
||||
/// Operators must disable/drain automatic cleanup and prevent other cleanup,
|
||||
/// tag/branch publication and restore until completion, including direct clients.
|
||||
/// The server does not enforce that coordination. Preview is available without deletion.
|
||||
/// Wait, cancel and reopen reuse the shared Job APIs; timeout does not cancel,
|
||||
/// and cancellation cannot undo deletion or prove storage I/O has stopped.
|
||||
///
|
||||
/// ```
|
||||
/// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> {
|
||||
/// let job = table.cleanup_async(lancedb::table::CleanupOptions::new()
|
||||
/// .min_age_seconds(604800)).await?;
|
||||
/// let result = job.wait().await?;
|
||||
/// println!("{:?}", result.old_versions);
|
||||
/// # Ok(()) }
|
||||
/// ```
|
||||
pub async fn cleanup_async(&self, options: CleanupOptions) -> Result<Job<CleanupResult>> {
|
||||
self.inner.cleanup_async(options).await
|
||||
}
|
||||
|
||||
/// Explain Enterprise version cleanup without deleting files or submitting a job.
|
||||
/// Requires the same ownership and retention options as [`Self::cleanup_async`].
|
||||
/// Counts are observational estimates, not a reservation for later execution.
|
||||
pub async fn explain_cleanup(&self, options: CleanupOptions) -> Result<CleanupPlan> {
|
||||
self.inner.explain_cleanup(options).await
|
||||
}
|
||||
|
||||
/// Language-binding entry point retaining optional compaction fields.
|
||||
#[doc(hidden)]
|
||||
pub async fn optimize_full_with_overrides(
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! Options and results for durable remote version cleanup.
|
||||
|
||||
/// Per-invocation retention. Omission inherits table/branch then deployment policy.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
#[non_exhaustive]
|
||||
pub struct CleanupOptions {
|
||||
/// Minimum old-version age in seconds. None inherits server policy.
|
||||
pub min_age_seconds: Option<u64>,
|
||||
}
|
||||
|
||||
impl CleanupOptions {
|
||||
/// Inherit selected table/branch and deployment retention.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Set the minimum old-version age in seconds; zero is explicit, not omitted.
|
||||
pub fn min_age_seconds(mut self, seconds: u64) -> Self {
|
||||
self.min_age_seconds = Some(seconds);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Successful remote version cleanup. Auxiliary sweeps are best effort and
|
||||
/// excluded from the counts. Retry/recovery can leave counts unknown (`None`).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(try_from = "CleanupResultWire")]
|
||||
#[non_exhaustive]
|
||||
pub struct CleanupResult {
|
||||
/// Objects that could not be deleted, if measured. Other removals remain committed.
|
||||
pub failed_deletes: Option<u64>,
|
||||
/// Public result schema version; currently 1.
|
||||
pub format_version: u32,
|
||||
/// Retention resolved and recorded when the server accepted this job.
|
||||
pub min_age_seconds: u64,
|
||||
/// Whether the entire invocation's version-deletion counts are known.
|
||||
pub statistics_complete: bool,
|
||||
/// Old versions removed, or None after uncertain retry/recovery.
|
||||
pub old_versions: Option<u64>,
|
||||
/// Bytes removed by version deletion, excluding auxiliary sweeps.
|
||||
pub bytes_removed: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct CleanupResultWire {
|
||||
failed_deletes: Option<u64>,
|
||||
format_version: u32,
|
||||
min_age_seconds: u64,
|
||||
statistics_complete: bool,
|
||||
old_versions: Option<u64>,
|
||||
bytes_removed: Option<u64>,
|
||||
}
|
||||
|
||||
impl TryFrom<CleanupResultWire> for CleanupResult {
|
||||
type Error = &'static str;
|
||||
fn try_from(value: CleanupResultWire) -> std::result::Result<Self, Self::Error> {
|
||||
if value.format_version != 1
|
||||
|| if value.statistics_complete {
|
||||
value.old_versions.is_none() || value.bytes_removed.is_none()
|
||||
} else {
|
||||
value.old_versions.is_some()
|
||||
|| value.bytes_removed.is_some()
|
||||
|| value.failed_deletes.is_some()
|
||||
}
|
||||
{
|
||||
return Err("unsupported or inconsistent cleanup result");
|
||||
}
|
||||
Ok(Self {
|
||||
failed_deletes: value.failed_deletes,
|
||||
format_version: value.format_version,
|
||||
min_age_seconds: value.min_age_seconds,
|
||||
statistics_complete: value.statistics_complete,
|
||||
old_versions: value.old_versions,
|
||||
bytes_removed: value.bytes_removed,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Read-only version-deletion estimate. Execution re-evaluates current state;
|
||||
/// no job or deletion snapshot is reserved and auxiliary sweeps are excluded.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[non_exhaustive]
|
||||
pub struct CleanupPlan {
|
||||
#[serde(deserialize_with = "preview_version")]
|
||||
pub format_version: u32,
|
||||
pub source_version: u64,
|
||||
pub min_age_seconds: u64,
|
||||
pub cutoff_millis: i64,
|
||||
pub versions_to_remove: u64,
|
||||
pub bytes_to_remove: u64,
|
||||
}
|
||||
|
||||
fn preview_version<'de, D: serde::Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> std::result::Result<u32, D::Error> {
|
||||
let version = <u32 as serde::Deserialize>::deserialize(deserializer)?;
|
||||
if version != 1 {
|
||||
return Err(serde::de::Error::custom(
|
||||
"unsupported cleanup preview format",
|
||||
));
|
||||
}
|
||||
Ok(version)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cleanup_result_distinguishes_known_zero_unknown_and_invalid() {
|
||||
let mut value = serde_json::json!({"format_version":1,"min_age_seconds":0,
|
||||
"statistics_complete":true,"old_versions":0,"bytes_removed":0,"future":true});
|
||||
assert_eq!(
|
||||
serde_json::from_value::<CleanupResult>(value.clone())
|
||||
.unwrap()
|
||||
.old_versions,
|
||||
Some(0)
|
||||
);
|
||||
value["statistics_complete"] = false.into();
|
||||
assert!(serde_json::from_value::<CleanupResult>(value.clone()).is_err());
|
||||
value["old_versions"] = serde_json::Value::Null;
|
||||
value["bytes_removed"] = serde_json::Value::Null;
|
||||
assert_eq!(
|
||||
serde_json::from_value::<CleanupResult>(value.clone())
|
||||
.unwrap()
|
||||
.old_versions,
|
||||
None
|
||||
);
|
||||
value["format_version"] = 2.into();
|
||||
assert!(serde_json::from_value::<CleanupResult>(value).is_err());
|
||||
}
|
||||
}
|
||||
@@ -121,11 +121,13 @@ async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> R
|
||||
|
||||
fn requires_local_namespace_execution(query: &AnyQuery) -> bool {
|
||||
// The namespace QueryTable request cannot represent approx_mode, search_effort,
|
||||
// use_rte or order_by. For use_rte that is worse than a tuning miss: RTE read
|
||||
// routing lives only in `create_plan`, so a pushed-down query would return
|
||||
// stale base-only data. A dropped order_by would return the wrong top-K rows.
|
||||
// use_rte, order_by or scan_in_order. For use_rte that is worse than a tuning miss:
|
||||
// RTE read routing lives only in `create_plan`, so a pushed-down query would return
|
||||
// stale base-only data. A dropped order_by would return the wrong top-K rows, and a
|
||||
// dropped ordered scan would silently stop guaranteeing manifest order.
|
||||
if query.base().use_rte.is_some()
|
||||
|| query.base().has_take()
|
||||
|| query.base().scan_in_order == Some(true)
|
||||
|| query
|
||||
.base()
|
||||
.order_by
|
||||
@@ -154,6 +156,47 @@ pub async fn analyze_query_plan(
|
||||
Ok(lance_analyze_plan(plan, Default::default()).await?)
|
||||
}
|
||||
|
||||
/// Reject requests that ask for storage order in a query shape that cannot
|
||||
/// preserve it, or that also define a different result order.
|
||||
fn validate_scan_in_order(query: &AnyQuery) -> Result<()> {
|
||||
if query.base().scan_in_order != Some(true) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let ranked = match query {
|
||||
AnyQuery::VectorQuery(_) => true,
|
||||
AnyQuery::Query(query) => {
|
||||
query.full_text_search.is_some() || query.reranker.is_some() || query.norm.is_some()
|
||||
}
|
||||
};
|
||||
if ranked {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "scan_in_order(true) is only supported for ordinary scans; vector, \
|
||||
full-text, hybrid, and reranked queries return ranked results"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
if query
|
||||
.base()
|
||||
.order_by
|
||||
.as_ref()
|
||||
.is_some_and(|order_by| !order_by.is_empty())
|
||||
{
|
||||
return Err(Error::InvalidInput {
|
||||
message: "scan_in_order(true) conflicts with a nonempty order_by; remove the \
|
||||
ordering to keep manifest order, or remove scan_in_order(true) to sort"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
if query.base().has_take() {
|
||||
return crate::query::validate_take_scan_in_order(query.base());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Local Execution Path (DataFusion)
|
||||
async fn execute_generic_query(
|
||||
table: &NativeTable,
|
||||
@@ -177,6 +220,7 @@ pub async fn create_plan(
|
||||
options: QueryExecutionOptions,
|
||||
) -> Result<Arc<dyn ExecutionPlan>> {
|
||||
let query = query.canonicalized()?;
|
||||
validate_scan_in_order(&query)?;
|
||||
if let AnyQuery::Query(request) = &query
|
||||
&& request.has_take()
|
||||
{
|
||||
@@ -435,6 +479,17 @@ pub async fn create_plan(
|
||||
scanner.order_by(Some(order_by.clone()))?;
|
||||
}
|
||||
|
||||
if let Some(scan_in_order) = query.base.scan_in_order {
|
||||
scanner.scan_in_order(scan_in_order);
|
||||
if scan_in_order {
|
||||
// Legacy scalar-index plans can union materialized index rows with
|
||||
// unindexed fragments and emit a different sequence. Explicit
|
||||
// storage order must come from the manifest scan, so filters fall
|
||||
// back to evaluating over the ordered fragments.
|
||||
scanner.use_scalar_index(false);
|
||||
}
|
||||
}
|
||||
|
||||
let mut plan = scanner
|
||||
.create_plan()
|
||||
.await
|
||||
@@ -1191,6 +1246,21 @@ mod tests {
|
||||
FixedSizeListArray::try_new_from_values(Float32Array::from(values), dimension).unwrap()
|
||||
}
|
||||
|
||||
fn collect_i32(batches: &[RecordBatch]) -> Vec<i32> {
|
||||
batches
|
||||
.iter()
|
||||
.flat_map(|batch| {
|
||||
batch
|
||||
.column(0)
|
||||
.as_any()
|
||||
.downcast_ref::<Int32Array>()
|
||||
.unwrap()
|
||||
.values()
|
||||
.to_vec()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_parse_arrow_ipc_response_handles_file_and_stream() {
|
||||
use arrow_array::{Int32Array, RecordBatch};
|
||||
@@ -2462,4 +2532,300 @@ mod tests {
|
||||
Some(ApproxMode::Accurate)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_scan_in_order_local_multi_fragment_contract() {
|
||||
use crate::connect;
|
||||
use crate::query::ColumnOrdering;
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
|
||||
let conn = connect("memory://").execute().await.unwrap();
|
||||
let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
|
||||
let batch = |ids: Vec<i32>| {
|
||||
RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(ids))]).unwrap()
|
||||
};
|
||||
|
||||
let table = conn
|
||||
.create_table("scan_in_order_contract", batch(vec![0, 1]))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
table.add(batch(vec![2, 3])).execute().await.unwrap();
|
||||
table.add(batch(vec![4, 5])).execute().await.unwrap();
|
||||
|
||||
let fragments = table
|
||||
.as_native()
|
||||
.unwrap()
|
||||
.dataset
|
||||
.get()
|
||||
.await
|
||||
.unwrap()
|
||||
.get_fragments()
|
||||
.len();
|
||||
assert_eq!(fragments, 3, "the test needs real multi-fragment data");
|
||||
|
||||
// An ordered scan must not introduce a global sort.
|
||||
let plan = table
|
||||
.query()
|
||||
.select(Select::columns(&["id"]))
|
||||
.scan_in_order(true)
|
||||
.explain_plan(false)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
!plan.contains("SortExec"),
|
||||
"scan_in_order(true) must not add a sort, got:\n{plan}"
|
||||
);
|
||||
|
||||
// Pin one version so repeated executions describe the same manifest.
|
||||
let version = table.version().await.unwrap();
|
||||
table.checkout(version).await.unwrap();
|
||||
for _ in 0..2 {
|
||||
let batches = table
|
||||
.query()
|
||||
.select(Select::columns(&["id"]))
|
||||
.scan_in_order(true)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(collect_i32(&batches), vec![0, 1, 2, 3, 4, 5]);
|
||||
}
|
||||
|
||||
// The default keeps the ordered local behavior.
|
||||
let batches = table
|
||||
.query()
|
||||
.select(Select::columns(&["id"]))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(collect_i32(&batches), vec![0, 1, 2, 3, 4, 5]);
|
||||
|
||||
// Allowing unordered scans changes no membership.
|
||||
let mut unordered = collect_i32(
|
||||
&table
|
||||
.query()
|
||||
.select(Select::columns(&["id"]))
|
||||
.scan_in_order(false)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
unordered.sort();
|
||||
assert_eq!(unordered, vec![0, 1, 2, 3, 4, 5]);
|
||||
|
||||
// An explicit sort still wins when storage order is not required.
|
||||
let batches = table
|
||||
.query()
|
||||
.select(Select::columns(&["id"]))
|
||||
.scan_in_order(false)
|
||||
.order_by(Some(vec![ColumnOrdering::desc_nulls_last(
|
||||
"id".to_string(),
|
||||
)]))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(collect_i32(&batches), vec![5, 4, 3, 2, 1, 0]);
|
||||
|
||||
// Deletions keep manifest order, and small output batches plus
|
||||
// limit/offset must not disturb it.
|
||||
table.checkout_latest().await.unwrap();
|
||||
table.delete("id = 3").await.unwrap();
|
||||
let version = table.version().await.unwrap();
|
||||
table.checkout(version).await.unwrap();
|
||||
let batches = table
|
||||
.query()
|
||||
.select(Select::columns(&["id"]))
|
||||
.scan_in_order(true)
|
||||
.offset(1)
|
||||
.limit(2)
|
||||
.execute_with_options(QueryExecutionOptions {
|
||||
max_batch_length: 1,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
batches.iter().all(|batch| batch.num_rows() <= 1),
|
||||
"max_batch_length must stay bounded"
|
||||
);
|
||||
assert_eq!(collect_i32(&batches), vec![1, 2]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_scan_in_order_rejects_ranked_and_sorted_queries() {
|
||||
use crate::connect;
|
||||
use crate::query::ColumnOrdering;
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
|
||||
let conn = connect("memory://").execute().await.unwrap();
|
||||
let vector = fixed_size_list_array(vec![0.0, 0.0, 1.0, 0.0, 2.0, 0.0], 2);
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int32, false),
|
||||
Field::new("vector", vector.data_type().clone(), false),
|
||||
]));
|
||||
let batch = RecordBatch::try_new(
|
||||
schema,
|
||||
vec![Arc::new(Int32Array::from(vec![0, 1, 2])), Arc::new(vector)],
|
||||
)
|
||||
.unwrap();
|
||||
let table = conn
|
||||
.create_table("scan_in_order_conflicts", batch)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let err = table
|
||||
.query()
|
||||
.scan_in_order(true)
|
||||
.order_by(Some(vec![ColumnOrdering::asc_nulls_last("id".to_string())]))
|
||||
.execute()
|
||||
.await
|
||||
.err()
|
||||
.expect("ranked and sorted scans must be rejected");
|
||||
assert!(
|
||||
matches!(&err, Error::InvalidInput { message }
|
||||
if message.contains("nonempty order_by")),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
|
||||
let err = table
|
||||
.query()
|
||||
.scan_in_order(true)
|
||||
.nearest_to(vec![0.0f32, 0.0])
|
||||
.unwrap()
|
||||
.execute()
|
||||
.await
|
||||
.err()
|
||||
.expect("ranked scans must be rejected");
|
||||
assert!(
|
||||
matches!(&err, Error::InvalidInput { message }
|
||||
if message.contains("ranked results")),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_scan_in_order_with_namespace_pushdown_runs_locally() {
|
||||
use crate::connect;
|
||||
use crate::query::ColumnOrdering;
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
|
||||
let conn = connect("memory://").execute().await.unwrap();
|
||||
let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
|
||||
let batch = |ids: Vec<i32>| {
|
||||
RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(ids))]).unwrap()
|
||||
};
|
||||
// Insertion order differs from sorted order so a dropped scan order or
|
||||
// an accidental sort changes the result.
|
||||
let table = conn
|
||||
.create_table("scan_in_order_namespace", batch(vec![3, 1]))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
table.add(batch(vec![2])).execute().await.unwrap();
|
||||
|
||||
let namespace_client = Arc::new(CountingNamespaceClient::default());
|
||||
let mut native_table = table.as_native().unwrap().clone();
|
||||
native_table.namespace_client = Some(namespace_client.clone());
|
||||
native_table
|
||||
.pushdown_operations
|
||||
.insert(NamespaceClientPushdownOperation::QueryTable);
|
||||
|
||||
let query = AnyQuery::Query(QueryRequest {
|
||||
filter: Some(QueryFilter::Sql("id >= 1".to_string())),
|
||||
select: Select::columns(&["id"]),
|
||||
limit: Some(2),
|
||||
scan_in_order: Some(true),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(requires_local_namespace_execution(&query));
|
||||
|
||||
let batches = execute_query(&native_table, &query, QueryExecutionOptions::default())
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(collect_i32(&batches), vec![3, 1]);
|
||||
assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0);
|
||||
|
||||
// Allowing unordered scans does not require local execution.
|
||||
let allow_unordered = AnyQuery::Query(QueryRequest {
|
||||
scan_in_order: Some(false),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(!requires_local_namespace_execution(&allow_unordered));
|
||||
|
||||
// An explicit sort is already local because the namespace request has
|
||||
// no order_by field.
|
||||
let sorted = AnyQuery::Query(QueryRequest {
|
||||
order_by: Some(vec![ColumnOrdering::asc_nulls_last("id".to_string())]),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(requires_local_namespace_execution(&sorted));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_scan_in_order_true_rejected_on_rte() {
|
||||
use crate::connect;
|
||||
use crate::table::RTEWriteSpec;
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let conn = connect(dir.path().to_str().unwrap())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
|
||||
let batch =
|
||||
RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![0, 1]))]).unwrap();
|
||||
let table = conn
|
||||
.create_table("scan_in_order_rte", batch)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
table.set_unenforced_primary_key(["id"]).await.unwrap();
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap();
|
||||
|
||||
let err = table
|
||||
.query()
|
||||
.scan_in_order(true)
|
||||
.execute()
|
||||
.await
|
||||
.err()
|
||||
.expect("RTE scans cannot guarantee manifest order");
|
||||
assert!(
|
||||
matches!(&err, Error::NotSupported { message }
|
||||
if message.contains("scan_in_order(true)") && message.contains("use_rte(false)")),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
|
||||
// The base table can still be read in storage order explicitly.
|
||||
let batches = table
|
||||
.query()
|
||||
.scan_in_order(true)
|
||||
.use_rte(false)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(collect_i32(&batches), vec![0, 1]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,6 +183,11 @@ fn reject_unsupported(query: &VectorQueryRequest) -> Result<()> {
|
||||
if query.base.order_by.is_some() {
|
||||
return unsupported("order_by");
|
||||
}
|
||||
if query.base.scan_in_order == Some(true) {
|
||||
return unsupported(
|
||||
"scan_in_order(true) (the LSM scanner does not preserve base manifest order)",
|
||||
);
|
||||
}
|
||||
// Vector-only knobs the LSM scanner cannot honor. Both change results rather
|
||||
// than just recall, so error instead of silently ignoring them: distance_range
|
||||
// would return rows outside the bound, and use_index(false) asks for a
|
||||
|
||||
Reference in New Issue
Block a user