mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat(sdk)!: add typed SQL job handles for compaction and data prewarm (#5056)
Remote data prewarm used REST even though SQL supported filters and concurrency, and both maintenance APIs returned after acceptance without exposing a consistent typed completion handle. Compaction's legacy statistics therefore could not describe the work committed by its durable job. This PR adds job-returning compaction and data-prewarm methods across Rust, Python sync/async and TypeScript, and moves data-prewarm submission to SQL. Legacy methods retain return-after-acceptance behavior; data prewarm now requires a compatible SQL PREWARM server and Flight SQL connectivity. This consolidates #5037, #5055 and #4906. This was accomplished with the following changes: - Added `compact_async()` / `compactAsync()` and `prewarm_data_async()` / `prewarmDataAsync()`, retaining the command receipt's durable job ID. - Added `PrewarmDataOptions` for columns, a metadata-pruning filter and concurrency; both operations inherit database, namespace and branch from the table handle. - Added filter/concurrency arguments to legacy Python `prewarm_data()` and a TypeScript `prewarmData(options)` overload, preserving the columns-array form and discarding the handle after acceptance. - Added typed `CompactionResult` and `PrewarmDataResult` decoding, including reopened jobs; missing result payloads fail explicitly and omitted measurements remain unknown. - Reused the shared Job lifecycle for status, refresh, progress callbacks, cancellation and events; Python maintenance progress bars display rewritten rows or completed executors. - Added TypeScript `wait({ timeoutMs, onProgress })` and Rust `wait_with_options(JobWaitOptions)`, complementing Python's existing timeout argument without cancelling the durable job. - Validated single unambiguous receipts, preserved compaction option presence/default inheritance, and returned actionable unsupported-server errors without dropping options or falling back to REST. - Updated native bindings, API references and maintenance documentation with job methods, result semantics, tuning and compatibility requirements. ### Usage and behaviour **New** = added here; **Enhanced** = existing support extended; **Existing** = already on main. This table describes remote SDK behavior; server-side SQL/CLI capabilities are prerequisites, not additions made by this SDK PR. | Surface | Capability | Compact | Data prewarm | Assessment | | --- | --- | --- | --- | --- | | Rust / Python sync+async / TypeScript | Submission transport | Existing SQL OPTIMIZE | **New:** REST → SQL PREWARM | Both now submit through SQL | | All SDKs | Durable job-returning API | **New:** `compact_async` / `compactAsync` | **New:** `prewarm_data_async` / `prewarmDataAsync` | Same lifecycle model | | All SDKs | Options and target scope | **New handle:** four existing compaction overrides, with omitted fields inherited | **New options:** columns/filter/concurrency | Namespace and branch preserved for both | | Python / TypeScript | Legacy convenience calls | Existing optimize acceptance behavior preserved | **Enhanced:** legacy methods accept filter/concurrency and use SQL | Return after acceptance; no completion wait | | All SDKs | Typed successful result | **New:** committed rows, file/fragment changes, partial commit and `more_work` | **New:** pinned version, fragments and executor outcomes | Different measurements are intentional | | All SDKs | Status / refresh / progress | Existing Job APIs reused by **new** maintenance handle | Existing Job APIs reused by **new** maintenance handle | HTTP monitoring remains | | Python / TypeScript | Progress presentation | **Enhanced:** rewrite rows/groups | **Enhanced:** executor progress | Shared callbacks; Python bars use operation counters | | All SDKs | Bounded wait | Python existing; **new** TS/Rust timeout controls | Same shared timeout support | Timeout stops this wait; job continues | | All SDKs | Reopen and await typed outcome | **New:** compaction result decoding on reopened handle | **New:** prewarm result decoding on reopened handle | Rust selects the typed result explicitly | | All SDKs | Cancel / events | Existing shared APIs available on **new** handle | Same | HTTP underneath; permissions unchanged | | All SDKs | Typed preview helper | Unavailable | Unavailable | General SQL where exposed; no helper added | | Authorization | Submission | Existing table Ownership plus parent Usage | SQL path uses Select plus parent Usage | Intentional difference | | All SDKs | Local / historical handles | New durable API rejects them | New durable API rejects them | Remote current-branch jobs only | ```python from datetime import timedelta # Legacy convenience call: returns None after acceptance. table.prewarm_data(["payload"], filter="id >= 1000", concurrency=4) warm = table.prewarm_data_async(["payload"], filter="id >= 1000", concurrency=4) warmed = warm.wait(timeout=timedelta(minutes=10), progress=print) print(warmed.table_version, warmed.executors_completed) compact = table.compact_async(compaction_options={"max_source_rows": 1000000}) committed = compact.wait(timeout=timedelta(minutes=10), progress=print) print(committed.rows_succeeded, committed.fragments_removed, committed.more_work) reopened_result = db.open_job(compact.id).wait() ``` ```typescript await table.prewarmData({ columns: ["payload"], filter: "id >= 1000", concurrency: 4 }); const job = await table.prewarmDataAsync({ columns: ["payload"], filter: "id >= 1000", concurrency: 4, }); const result = await job.wait({ timeoutMs: 600_000, onProgress: console.log }); ``` ```rust use std::time::Duration; use lancedb::job::JobWaitOptions; let job = table.compact_async(Default::default()).await?; let result = job.wait_with_options( JobWaitOptions::new().timeout(Duration::from_secs(600)), ).await?; ``` Python async tables await both submission and Job methods. Rust's legacy `prewarm_data(columns)` keeps its columns-only signature; use `PrewarmDataOptions` on the new job-returning method for filtering/concurrency. Wait deadlines cover pending status requests and polling delays. Existing `wait()`, TypeScript `wait(callback)` and Rust `wait_with_progress(callback)` remain supported. Status/progress/refresh/cancel/events still use generic HTTP job APIs; those endpoints and their read/event/cancel permissions must remain available. Cancelling or timing out does not roll back committed work. Compaction results describe committed rewrites and include deletion files in file counts. Prewarm results describe work against a pinned snapshot, with partial executors included in completed executors; nonempty byte/range measurements remain unknown. Missing results require compatible server/worker support rather than placeholder zero statistics. Filtering uses conservative metadata pruning, not an exact row-filter scan. ### Testing Six checked-in live Python sync/async cases pass against matching server/worker builds for compaction, job-returning prewarm and legacy filtered submission. Ten additional live Node scenarios pass for legacy/default/options forms, filters/concurrency, empty plans, validation, persisted specifications and readback. Targeted regressions pass: Python remote maintenance (80), shared jobs (82), local prewarm rejection (4); Node remote (107) and prewarm API cases (28), plus the previously exercised Rust remote regressions. Tests cover receipt parsing, typed results, reopening, unknown measurements, timeouts, and legacy calls returning None/undefined without polling. Dependency pins are unchanged. Azure account-hint acknowledgment was verified locally with filesystem storage; real Azure-backed storage still needs deployment-specific validation.
This commit is contained in:
@@ -645,6 +645,13 @@ class 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: ...
|
||||
async def prewarm_data_async(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> Job: ...
|
||||
async def list_indices(self) -> list[IndexConfig]: ...
|
||||
async def tokenize(
|
||||
self,
|
||||
@@ -787,6 +794,9 @@ class Table:
|
||||
async def update_field_metadata(
|
||||
self, updates: list[dict[str, Any]]
|
||||
) -> UpdateFieldMetadataResult: ...
|
||||
async def compact_async(
|
||||
self, compaction_options: Optional[Dict[str, Any]] = None
|
||||
) -> Job: ...
|
||||
async def optimize(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Results of durable remote compaction jobs."""
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CompactionResult:
|
||||
"""Actual committed outcome of one remote compaction invocation.
|
||||
|
||||
``rows_failed`` counts planned live rows that were not committed, including
|
||||
partial progress. ``more_work`` means a bounded run left eligible work for
|
||||
another invocation. File/fragment counts are None if an older worker did
|
||||
not report them; they are never inferred from unrelated table versions.
|
||||
File counts include deletion files as well as data files.
|
||||
"""
|
||||
|
||||
partial_commit: bool
|
||||
rows_succeeded: int
|
||||
rows_failed: int
|
||||
completion_percentage: float
|
||||
more_work: bool = False
|
||||
files_added: Optional[int] = None
|
||||
files_removed: Optional[int] = None
|
||||
fragments_added: Optional[int] = None
|
||||
fragments_removed: Optional[int] = None
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, raw: str) -> "CompactionResult":
|
||||
"""Decode a server result, ignoring additive fields from newer servers."""
|
||||
value = json.loads(raw)
|
||||
names = {field.name for field in fields(cls)}
|
||||
return cls(**{key: item for key, item in value.items() if key in names})
|
||||
@@ -21,6 +21,8 @@ from lancedb.background_loop import LOOP
|
||||
from . import _lancedb
|
||||
from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url
|
||||
from .functions import RefreshColumnResult
|
||||
from .compaction import CompactionResult
|
||||
from .prewarm import PrewarmDataResult
|
||||
from .remote.errors import HttpError, RetryError
|
||||
|
||||
T = TypeVar("T")
|
||||
@@ -148,6 +150,19 @@ def _job_progress_callback(progress, enrich):
|
||||
planned = snapshot.get("rows_planned")
|
||||
remaining = snapshot.get("rows_remaining")
|
||||
computed = snapshot.get("rows_computed")
|
||||
job_type = snapshot.get("job_type")
|
||||
maintenance = job_type in ("compact", "prewarm_page_cache")
|
||||
if job_type == "compact":
|
||||
computed = snapshot.get("rows_rewritten")
|
||||
remaining = None
|
||||
if hasattr(progress, "unit"):
|
||||
progress.unit = " rows"
|
||||
elif job_type == "prewarm_page_cache":
|
||||
planned = snapshot.get("executors_targeted")
|
||||
computed = snapshot.get("executors_completed")
|
||||
remaining = None
|
||||
if hasattr(progress, "unit"):
|
||||
progress.unit = " executors"
|
||||
if isinstance(planned, int):
|
||||
epoch = snapshot.get("execution_epoch")
|
||||
reset = (isinstance(last_planned, int) and planned < last_planned) or (
|
||||
@@ -173,7 +188,7 @@ def _job_progress_callback(progress, enrich):
|
||||
if completed is not None:
|
||||
if isinstance(planned, int):
|
||||
completed = min(completed, planned)
|
||||
if first_snapshot and completed < last_rows:
|
||||
if (first_snapshot or maintenance) and completed < last_rows:
|
||||
# The server may have started a new execution while a
|
||||
# caller-owned bar retained its old position.
|
||||
last_rows = completed
|
||||
@@ -287,6 +302,10 @@ class AsyncJob(Generic[T]):
|
||||
a caller-owned bar with the server's current completed rows and total;
|
||||
later observations in a stable execution epoch use a high-water mark. A
|
||||
new execution epoch or smaller plan resets the bar to that plan.
|
||||
Maintenance jobs display reported rewritten rows or completed executors;
|
||||
revised maintenance counters replace earlier retry observations. Totals
|
||||
remain unknown until the server reports them. Rewritten rows describe
|
||||
execution work, not committed compaction results.
|
||||
``False`` preserves the original wait behavior.
|
||||
|
||||
For SQL-backed Function registration, progress shows the query's
|
||||
@@ -841,4 +860,8 @@ def _typed_job(
|
||||
def _opened_job(inner: "_lancedb.Job") -> AsyncJob:
|
||||
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":
|
||||
return _typed_job(inner, PrewarmDataResult.from_json)
|
||||
if inner.job_type == "compact":
|
||||
return _typed_job(inner, CompactionResult.from_json)
|
||||
return AsyncJob(inner)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Results of remote data-cache prewarm jobs."""
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrewarmDataResult:
|
||||
"""Reported executor work for a pinned snapshot, not guaranteed cache residency.
|
||||
|
||||
Counts omitted by older workers remain None. I/O counts are unknown when
|
||||
executors do not report them. Partial completions are a subset of completed
|
||||
executors and may reflect cache pressure.
|
||||
"""
|
||||
|
||||
table_version: int
|
||||
executors_targeted: Optional[int] = None
|
||||
executors_completed: Optional[int] = None
|
||||
executors_partial: Optional[int] = None
|
||||
fragments_selected: Optional[int] = None
|
||||
ranges_completed: Optional[int] = None
|
||||
bytes_read: Optional[int] = None
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, raw: str) -> "PrewarmDataResult":
|
||||
value = json.loads(raw)
|
||||
names = {field.name for field in fields(cls)}
|
||||
return cls(**{key: item for key, item in value.items() if key in names})
|
||||
@@ -48,6 +48,7 @@ from lancedb.index import (
|
||||
Bitmap,
|
||||
LabelList,
|
||||
)
|
||||
from lancedb.prewarm import PrewarmDataResult
|
||||
from lancedb.job import Job
|
||||
from lancedb.functions import (
|
||||
FunctionProvenance,
|
||||
@@ -78,6 +79,7 @@ from ..table import (
|
||||
BlobMode,
|
||||
Branches,
|
||||
CompactionOptions,
|
||||
CompactionResult,
|
||||
IndexStatistics,
|
||||
Query,
|
||||
Table,
|
||||
@@ -1105,6 +1107,13 @@ class RemoteTable(Table):
|
||||
)
|
||||
pass
|
||||
|
||||
def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[CompactionResult]:
|
||||
return Job(
|
||||
LOOP.run(self._table.compact_async(compaction_options=compaction_options))
|
||||
)
|
||||
|
||||
def optimize(
|
||||
self,
|
||||
*,
|
||||
@@ -1433,7 +1442,13 @@ class RemoteTable(Table):
|
||||
"""
|
||||
return LOOP.run(self._table.prewarm_index(name))
|
||||
|
||||
def prewarm_data(self, columns: Optional[List[str]] = None) -> None:
|
||||
def prewarm_data(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> None:
|
||||
"""Prewarm data for the table.
|
||||
|
||||
This is a hint to the database that the given columns will be accessed
|
||||
@@ -1441,7 +1456,8 @@ class RemoteTable(Table):
|
||||
Currently only supported in LanceDB Enterprise.
|
||||
|
||||
This call initiates prewarming and returns once the request is accepted.
|
||||
It is idempotent and safe to call from multiple clients concurrently.
|
||||
Uses SQL PREWARM and requires Flight SQL connectivity. To track the
|
||||
durable warming job, use ``prewarm_data_async()``.
|
||||
|
||||
This operation has a large upfront cost but can speed up future queries
|
||||
that need to fetch the given columns. Large columns such as embeddings
|
||||
@@ -1452,8 +1468,34 @@ class RemoteTable(Table):
|
||||
----------
|
||||
columns: list of str, optional
|
||||
The columns to prewarm. If None, all columns are prewarmed.
|
||||
filter: str, optional
|
||||
A single SQL predicate for conservative metadata pruning.
|
||||
concurrency: int, optional
|
||||
Positive per-executor warming concurrency; omitted uses the server default.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> table.prewarm_data( # doctest: +SKIP
|
||||
... ["payload"], filter="quality > 0.7", concurrency=4)
|
||||
"""
|
||||
return LOOP.run(self._table.prewarm_data(columns))
|
||||
return LOOP.run(
|
||||
self._table.prewarm_data(columns, filter=filter, concurrency=concurrency)
|
||||
)
|
||||
|
||||
def prewarm_data_async(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> Job[PrewarmDataResult]:
|
||||
return Job(
|
||||
LOOP.run(
|
||||
self._table.prewarm_data_async(
|
||||
columns, filter=filter, concurrency=concurrency
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
def wait_for_index(
|
||||
self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300)
|
||||
|
||||
@@ -48,7 +48,9 @@ from ._blob import (
|
||||
from .types import BlobMode
|
||||
from lancedb.arrow import peek_reader
|
||||
from lancedb.background_loop import LOOP, embedding_executor
|
||||
from lancedb.prewarm import PrewarmDataResult
|
||||
from lancedb.job import AsyncJob, Job, _typed_job
|
||||
from lancedb.compaction import CompactionResult
|
||||
from .dependencies import (
|
||||
_check_for_hugging_face,
|
||||
_check_for_lance,
|
||||
@@ -2011,6 +2013,69 @@ class Table(ABC):
|
||||
"""
|
||||
raise NotImplementedError("create_index is not supported for this table type")
|
||||
|
||||
def prewarm_data(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> None:
|
||||
"""Submit remote data prewarm and return after acceptance.
|
||||
|
||||
Omitted or empty ``columns`` warm all fields. ``filter`` is a single
|
||||
SQL predicate for conservative metadata pruning; ``concurrency`` is
|
||||
a positive per-executor integer, or omitted for the server default.
|
||||
The table handle supplies the namespace and branch. Requires a
|
||||
compatible SQL PREWARM server and Flight SQL connectivity.
|
||||
|
||||
The operation continues in the background. Use
|
||||
[prewarm_data_async][lancedb.table.Table.prewarm_data_async] to retain
|
||||
the job handle and wait for completion.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> table.prewarm_data( # doctest: +SKIP
|
||||
... ["payload"], filter="quality > 0.7", concurrency=4)
|
||||
"""
|
||||
self.prewarm_data_async(columns, filter=filter, concurrency=concurrency)
|
||||
|
||||
def prewarm_data_async(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> Job[PrewarmDataResult]:
|
||||
"""Submit a remote data-cache prewarm and return its durable job.
|
||||
|
||||
Requires a compatible SQL PREWARM server and Flight SQL connectivity.
|
||||
The table handle supplies the branch and namespace. ``columns`` uses
|
||||
Lance field paths; an omitted/empty list warms all columns. ``filter``
|
||||
is one SQL predicate for conservative metadata pruning, not a row scan.
|
||||
``concurrency`` is a positive per-executor integer. Historical-version
|
||||
handles are unsupported; call ``checkout_latest()`` first.
|
||||
|
||||
Submission requires table Select and database/namespace Usage under
|
||||
Standard authorization. Status/wait use the generic HTTP job API;
|
||||
events and cancellation have their own privileges. Unsupported servers
|
||||
are not retried through REST or with settings removed.
|
||||
|
||||
Returns once accepted. ``job.wait()`` waits for warming to finish and
|
||||
returns [PrewarmDataResult][lancedb.prewarm.PrewarmDataResult].
|
||||
Save ``job.id`` to resume with ``db.open_job(id)``. A wait timeout does
|
||||
not cancel the operation. After ``job.refresh()``,
|
||||
``job.spec["table_version"]`` identifies the pinned source version.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> job = table.prewarm_data_async( # doctest: +SKIP
|
||||
... ["video"], filter="quality > 0.7", concurrency=4)
|
||||
>>> job.wait() # doctest: +SKIP
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
"data prewarm jobs are only supported on remote tables"
|
||||
)
|
||||
|
||||
def create_index_async(
|
||||
self,
|
||||
column: str,
|
||||
@@ -3024,6 +3089,33 @@ class Table(ABC):
|
||||
compaction for you automatically.
|
||||
"""
|
||||
|
||||
def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[CompactionResult]:
|
||||
"""Submit remote compaction and return a durable job after acceptance.
|
||||
|
||||
Uses SQL OPTIMIZE with the table handle's branch and namespace. Supports
|
||||
the four per-job settings in
|
||||
[CompactionOptions][lancedb.table.CompactionOptions].
|
||||
Requires a compatible remote server, table Ownership and parent Usage.
|
||||
Local and historical-version handles are unsupported. Existing
|
||||
``optimize()`` retains its return-on-submission behavior remotely.
|
||||
|
||||
``job.wait()`` waits for the actual rewrite and returns
|
||||
[CompactionResult][lancedb.compaction.CompactionResult]. Partial/bounded
|
||||
runs report uncommitted rows and ``more_work``; unknown file statistics
|
||||
are None. Servers without a result payload raise an error rather than
|
||||
returning fabricated zero statistics. Wait timeouts do not cancel work.
|
||||
Save ``job.id`` and reopen with ``db.open_job(id)``. Monitoring and
|
||||
cancellation use generic HTTP job APIs and their existing permissions.
|
||||
|
||||
>>> job = table.compact_async( # doctest: +SKIP
|
||||
... compaction_options={"target_rows_per_fragment": 1000})
|
||||
>>> result = job.wait() # doctest: +SKIP
|
||||
>>> print(result.rows_succeeded) # doctest: +SKIP
|
||||
"""
|
||||
raise NotImplementedError("compaction jobs are only supported on remote tables")
|
||||
|
||||
@abstractmethod
|
||||
def optimize(
|
||||
self,
|
||||
@@ -4843,7 +4935,13 @@ class LanceTable(Table):
|
||||
"""
|
||||
return LOOP.run(self._table.prewarm_index(name))
|
||||
|
||||
def prewarm_data(self, columns: Optional[List[str]] = None) -> None:
|
||||
def prewarm_data(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Prewarm data for the table.
|
||||
|
||||
@@ -4852,7 +4950,8 @@ class LanceTable(Table):
|
||||
Currently only supported in LanceDB Enterprise.
|
||||
|
||||
This call initiates prewarming and returns once the request is accepted.
|
||||
It is idempotent and safe to call from multiple clients concurrently.
|
||||
Uses SQL PREWARM and requires Flight SQL connectivity. To track the
|
||||
durable warming job, use ``prewarm_data_async()``.
|
||||
|
||||
This operation has a large upfront cost but can speed up future queries
|
||||
that need to fetch the given columns. Large columns such as embeddings
|
||||
@@ -4863,8 +4962,34 @@ class LanceTable(Table):
|
||||
----------
|
||||
columns: list of str, optional
|
||||
The columns to prewarm. If None, all columns are prewarmed.
|
||||
filter: str, optional
|
||||
A single SQL predicate for conservative metadata pruning.
|
||||
concurrency: int, optional
|
||||
Positive per-executor warming concurrency; omitted uses the server default.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> table.prewarm_data( # doctest: +SKIP
|
||||
... ["payload"], filter="quality > 0.7", concurrency=4)
|
||||
"""
|
||||
return LOOP.run(self._table.prewarm_data(columns))
|
||||
return LOOP.run(
|
||||
self._table.prewarm_data(columns, filter=filter, concurrency=concurrency)
|
||||
)
|
||||
|
||||
def prewarm_data_async(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> Job[PrewarmDataResult]:
|
||||
return Job(
|
||||
LOOP.run(
|
||||
self._table.prewarm_data_async(
|
||||
columns, filter=filter, concurrency=concurrency
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
def wait_for_index(
|
||||
self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300)
|
||||
@@ -5683,6 +5808,13 @@ class LanceTable(Table):
|
||||
self.checkout_latest()
|
||||
return stats
|
||||
|
||||
def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[CompactionResult]:
|
||||
return Job(
|
||||
LOOP.run(self._table.compact_async(compaction_options=compaction_options))
|
||||
)
|
||||
|
||||
def optimize(
|
||||
self,
|
||||
*,
|
||||
@@ -7324,7 +7456,13 @@ class AsyncTable:
|
||||
"""
|
||||
await self._inner.prewarm_index(name)
|
||||
|
||||
async def prewarm_data(self, columns: Optional[List[str]] = None) -> None:
|
||||
async def prewarm_data(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Prewarm data for the table.
|
||||
|
||||
@@ -7333,7 +7471,8 @@ class AsyncTable:
|
||||
Currently only supported in LanceDB Enterprise.
|
||||
|
||||
This call initiates prewarming and returns once the request is accepted.
|
||||
It is idempotent and safe to call from multiple clients concurrently.
|
||||
Uses SQL PREWARM and requires Flight SQL connectivity. To track the
|
||||
durable warming job, use ``prewarm_data_async()``.
|
||||
|
||||
This operation has a large upfront cost but can speed up future queries
|
||||
that need to fetch the given columns. Large columns such as embeddings
|
||||
@@ -7344,8 +7483,43 @@ class AsyncTable:
|
||||
----------
|
||||
columns: list of str, optional
|
||||
The columns to prewarm. If None, all columns are prewarmed.
|
||||
filter: str, optional
|
||||
A single SQL predicate for conservative metadata pruning.
|
||||
concurrency: int, optional
|
||||
Positive per-executor warming concurrency; omitted uses the server default.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> await table.prewarm_data( # doctest: +SKIP
|
||||
... ["payload"], filter="quality > 0.7", concurrency=4)
|
||||
"""
|
||||
await self._inner.prewarm_data(columns)
|
||||
await self.prewarm_data_async(columns, filter=filter, concurrency=concurrency)
|
||||
|
||||
async def prewarm_data_async(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
) -> AsyncJob[PrewarmDataResult]:
|
||||
"""Submit data prewarm and return a durable handle after acceptance.
|
||||
|
||||
See [Table.prewarm_data_async][lancedb.table.Table.prewarm_data_async]
|
||||
for options, permissions, and compatibility. Awaiting this method does
|
||||
not wait for warming; use ``await job.wait()`` for completion.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> job = await table.prewarm_data_async( # doctest: +SKIP
|
||||
... ["video"], filter="quality > 0.7", concurrency=4)
|
||||
>>> await job.wait() # doctest: +SKIP
|
||||
"""
|
||||
return _typed_job(
|
||||
await self._inner.prewarm_data_async(
|
||||
columns, filter=filter, concurrency=concurrency
|
||||
),
|
||||
PrewarmDataResult.from_json,
|
||||
)
|
||||
|
||||
async def wait_for_index(
|
||||
self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300)
|
||||
@@ -9273,6 +9447,19 @@ class AsyncTable:
|
||||
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
|
||||
return self._inner.current_branch()
|
||||
|
||||
async def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> AsyncJob[CompactionResult]:
|
||||
"""Submit remote compaction; await the returned job for actual results.
|
||||
|
||||
See [Table.compact_async][lancedb.table.Table.compact_async] for options,
|
||||
permissions, completion semantics and compatibility requirements.
|
||||
"""
|
||||
return _typed_job(
|
||||
await self._inner.compact_async(compaction_options),
|
||||
CompactionResult.from_json,
|
||||
)
|
||||
|
||||
async def optimize(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -11,11 +11,139 @@ import numpy as np
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
from lancedb import LanceDBConnection, function
|
||||
from lancedb.compaction import CompactionResult
|
||||
from lancedb.index import FTS
|
||||
from lancedb.prewarm import PrewarmDataResult
|
||||
|
||||
# TODO: setup integ test mark and script
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def maintenance_connection_options():
|
||||
uri = os.environ.get("LANCEDB_URI")
|
||||
if not uri:
|
||||
pytest.skip(
|
||||
"Set LANCEDB_URI to a server supporting SQL maintenance job results"
|
||||
)
|
||||
assert uri.startswith("db://")
|
||||
return {
|
||||
"uri": uri,
|
||||
"api_key": os.environ.get("LANCEDB_API_KEY"),
|
||||
"region": os.environ.get("LANCEDB_REGION", "us-east-1"),
|
||||
"host_override": os.environ.get("LANCEDB_HOST_OVERRIDE"),
|
||||
"sql_host_override": os.environ.get("LANCEDB_SQL_HOST_OVERRIDE"),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
||||
@pytest.mark.parametrize("operation", ["compact", "prewarm", "prewarm_legacy"])
|
||||
async def test_maintenance_job_result_and_reopen_against_server(
|
||||
maintenance_connection_options, asynchronous, operation
|
||||
):
|
||||
"""Exercise real SQL receipts, workers and HTTP job results with matching versions.
|
||||
|
||||
Configure LANCEDB_URI, LANCEDB_API_KEY and the REST/Flight SQL endpoint
|
||||
overrides for a writable database. Workers must publish maintenance results;
|
||||
an unsupported server fails the contract rather than silently skipping it.
|
||||
"""
|
||||
if asynchronous:
|
||||
connection = await lancedb.connect_async(**maintenance_connection_options)
|
||||
else:
|
||||
connection = lancedb.connect(**maintenance_connection_options)
|
||||
|
||||
async def call(method, *args, **kwargs):
|
||||
result = method(*args, **kwargs)
|
||||
return await result if asynchronous else result
|
||||
|
||||
name = f"maintenance_{uuid4().hex}"
|
||||
created = False
|
||||
expected = [{"id": i, "payload": i * 10} for i in range(16)]
|
||||
timeout = timedelta(minutes=5)
|
||||
try:
|
||||
table = await call(
|
||||
connection.create_table, name, pa.Table.from_pylist(expected[:4])
|
||||
)
|
||||
created = True
|
||||
for start in (4, 8, 12):
|
||||
await call(table.add, pa.Table.from_pylist(expected[start : start + 4]))
|
||||
version = await table.version() if asynchronous else table.version
|
||||
if operation == "compact":
|
||||
job = await call(
|
||||
table.compact_async,
|
||||
compaction_options={
|
||||
"target_rows_per_fragment": 100,
|
||||
"batch_size": 128,
|
||||
"io_buffer_size": 0,
|
||||
},
|
||||
)
|
||||
elif operation == "prewarm_legacy":
|
||||
assert (
|
||||
await call(
|
||||
table.prewarm_data,
|
||||
["payload"],
|
||||
filter="id >= 8",
|
||||
concurrency=2,
|
||||
)
|
||||
is None
|
||||
)
|
||||
reader = await call(
|
||||
connection.execute_query, f'SHOW JOBS FOR TABLE "{name}"'
|
||||
)
|
||||
batches = await call(reader.read_all)
|
||||
jobs = pa.Table.from_batches(batches) if asynchronous else batches
|
||||
ids = [
|
||||
row["job_id"]
|
||||
for row in jobs.to_pylist()
|
||||
if row["job_type"] == "prewarm_page_cache"
|
||||
]
|
||||
assert len(ids) == 1, jobs.to_pylist()
|
||||
job = await call(connection.open_job, ids[0])
|
||||
else:
|
||||
job = await call(
|
||||
table.prewarm_data_async,
|
||||
["payload"],
|
||||
filter="id >= 8",
|
||||
concurrency=2,
|
||||
)
|
||||
assert job.id
|
||||
progress = []
|
||||
result = await call(job.wait, timeout=timeout, progress=progress.append)
|
||||
assert any(snapshot["state"] == "finished" for snapshot in progress)
|
||||
await call(job.refresh)
|
||||
assert await call(job.status) == "finished"
|
||||
if operation == "compact":
|
||||
assert isinstance(result, CompactionResult)
|
||||
assert job.job_type == "compact"
|
||||
assert not result.partial_commit and result.rows_failed == 0
|
||||
assert result.completion_percentage == 100
|
||||
assert 0 <= result.rows_succeeded <= len(expected)
|
||||
assert result.files_added is not None and result.files_removed is not None
|
||||
else:
|
||||
assert isinstance(result, PrewarmDataResult)
|
||||
assert job.job_type == "prewarm_page_cache"
|
||||
assert result.table_version == version == job.spec["table_version"]
|
||||
assert job.spec["columns"] == ["payload"]
|
||||
assert job.spec["concurrency"] == 2
|
||||
assert result.fragments_selected > 0
|
||||
assert result.executors_completed == result.executors_targeted
|
||||
assert result.executors_partial == 0
|
||||
assert result.bytes_read is None and result.ranges_completed is None
|
||||
reopened = await call(connection.open_job, job.id)
|
||||
assert await call(reopened.wait, timeout=timeout) == result
|
||||
query = table.query() if asynchronous else table.search()
|
||||
actual = await call(
|
||||
query.select(["id", "payload"]).limit(len(expected) + 1).to_arrow
|
||||
)
|
||||
assert sorted(actual.to_pylist(), key=lambda row: row["id"]) == expected
|
||||
finally:
|
||||
try:
|
||||
if created:
|
||||
await call(connection.drop_table, name)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not os.environ.get("LANCEDB_URI"), reason="Set LANCEDB_URI to a JSON FTS server"
|
||||
)
|
||||
|
||||
@@ -1072,3 +1072,95 @@ async def test_stack_propagates_errors_and_rejects_local_handles(sync):
|
||||
Job(None).stack("worker")
|
||||
else:
|
||||
await AsyncJob(None).stack("worker")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"kind,planned_key,completed_key,unit",
|
||||
[
|
||||
("compact", "rows_planned", "rows_rewritten", " rows"),
|
||||
(
|
||||
"prewarm_page_cache",
|
||||
"executors_targeted",
|
||||
"executors_completed",
|
||||
" executors",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_maintenance_progress_bar_uses_operation_counters_and_handles_retry(
|
||||
monkeypatch, kind, planned_key, completed_key, unit
|
||||
):
|
||||
tqdm_module = pytest.importorskip("tqdm.auto")
|
||||
|
||||
class Bar:
|
||||
total = None
|
||||
n = 0
|
||||
unit = " rows"
|
||||
closed = False
|
||||
|
||||
def update(self, delta):
|
||||
self.n += delta
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
bar = Bar()
|
||||
monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar)
|
||||
|
||||
class MaintenanceJob:
|
||||
id = "maintenance-job"
|
||||
job_type = kind
|
||||
|
||||
async def wait(self, progress):
|
||||
progress({"job_type": kind, "phase": "planning"})
|
||||
assert bar.total is None
|
||||
progress({"job_type": kind, planned_key: 4, completed_key: 2})
|
||||
assert bar.n == 2
|
||||
# Older responses can omit an epoch; revised observations still
|
||||
# replace the previous attempt's displayed work.
|
||||
progress({"job_type": kind, planned_key: 4, completed_key: 1})
|
||||
assert bar.n == 1
|
||||
progress({"job_type": kind, planned_key: 4, completed_key: 4})
|
||||
|
||||
assert await AsyncJob(MaintenanceJob()).wait(progress=True) is None
|
||||
assert bar.n == 4
|
||||
assert bar.total == 4
|
||||
assert bar.unit == unit
|
||||
assert bar.closed
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("known_empty", [False, True])
|
||||
async def test_prewarm_progress_bar_preserves_unknown_and_zero_totals(
|
||||
monkeypatch, known_empty
|
||||
):
|
||||
tqdm_module = pytest.importorskip("tqdm.auto")
|
||||
|
||||
class Bar:
|
||||
total = None
|
||||
n = 0
|
||||
unit = " rows"
|
||||
|
||||
def update(self, delta):
|
||||
self.n += delta
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
bar = Bar()
|
||||
monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar)
|
||||
|
||||
class PrewarmJob:
|
||||
id = "prewarm-job"
|
||||
job_type = "prewarm_page_cache"
|
||||
|
||||
async def wait(self, progress):
|
||||
snapshot = {"job_type": self.job_type, "phase": "succeeded"}
|
||||
if known_empty:
|
||||
snapshot.update(executors_targeted=0, executors_completed=0)
|
||||
progress(snapshot)
|
||||
|
||||
assert await AsyncJob(PrewarmJob()).wait(progress=True) is None
|
||||
assert bar.n == 0
|
||||
assert bar.total == (0 if known_empty else None)
|
||||
assert bar.unit == " executors"
|
||||
|
||||
@@ -7408,10 +7408,10 @@ def _create_table_handler(request):
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _mock_remote_sql_connection(flight_server):
|
||||
def _mock_remote_sql_connection(flight_server, handler=_create_table_handler):
|
||||
"""Connection arguments for mock REST and Flight SQL servers."""
|
||||
with http.server.ThreadingHTTPServer(
|
||||
("127.0.0.1", 0), make_mock_http_handler(_create_table_handler)
|
||||
("127.0.0.1", 0), make_mock_http_handler(handler)
|
||||
) as rest_server:
|
||||
rest_port = rest_server.server_address[1]
|
||||
handle = start_server_thread(rest_server)
|
||||
@@ -8054,3 +8054,373 @@ def test_exact_function_retries_fail_before_writing_to_older_servers():
|
||||
with pytest.raises(NotImplementedError, match="server does not support"):
|
||||
table.function_errors().summary()
|
||||
assert writes == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("mode", ["job", "columns", "filtered", "defaults"])
|
||||
async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mode):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
polls = []
|
||||
|
||||
class PrewarmServer(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": ["warming-job"],
|
||||
"table_version": pa.array([42], pa.uint64()),
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
def handler(request):
|
||||
if request.path == "/v1/jobs/describe":
|
||||
body = json.loads(
|
||||
request.rfile.read(int(request.headers["Content-Length"]))
|
||||
)
|
||||
assert body == {"job_id": "warming-job"}
|
||||
polls.append(body)
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.end_headers()
|
||||
request.wfile.write(
|
||||
json.dumps(
|
||||
{
|
||||
"job_id": "warming-job",
|
||||
"job_type": "prewarm_page_cache",
|
||||
"job_state": "DONE",
|
||||
"creation_ms": 1,
|
||||
"spec": {"table_version": 42},
|
||||
"result": {
|
||||
"table_version": 42,
|
||||
"executors_targeted": 2,
|
||||
"executors_completed": 2,
|
||||
"fragments_selected": 4,
|
||||
},
|
||||
"operation_progress": {
|
||||
"phase": "reading",
|
||||
"executors_completed": 2,
|
||||
"fragments_selected": 4,
|
||||
},
|
||||
}
|
||||
).encode()
|
||||
)
|
||||
else:
|
||||
# No operation-specific REST prewarm endpoint is accepted.
|
||||
_create_table_handler(request)
|
||||
|
||||
server = PrewarmServer()
|
||||
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}])
|
||||
if mode == "columns":
|
||||
assert await table.prewarm_data(["payload"]) is None
|
||||
elif mode == "filtered":
|
||||
assert (
|
||||
await table.prewarm_data(
|
||||
columns=["attrs.score"], filter="id >= 8", concurrency=4
|
||||
)
|
||||
is None
|
||||
)
|
||||
elif mode == "defaults":
|
||||
assert await table.prewarm_data() is None
|
||||
else:
|
||||
job = await table.prewarm_data_async(
|
||||
["attrs.score"], filter="id >= 8", concurrency=4
|
||||
)
|
||||
assert job.id == "warming-job"
|
||||
assert not polls
|
||||
assert (await job.wait()).table_version == 42
|
||||
await job.refresh()
|
||||
assert job.spec["table_version"] == 42
|
||||
reopened = await db.open_job(job.id)
|
||||
assert (await reopened.wait()).executors_completed == 2
|
||||
assert (await job.progress())["executors_completed"] == 2
|
||||
assert (await job.wait()).bytes_read is None
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
if mode == "columns":
|
||||
assert table.prewarm_data(["payload"]) is None
|
||||
elif mode == "filtered":
|
||||
assert (
|
||||
table.prewarm_data(
|
||||
columns=["attrs.score"], filter="id >= 8", concurrency=4
|
||||
)
|
||||
is None
|
||||
)
|
||||
elif mode == "defaults":
|
||||
assert table.prewarm_data() is None
|
||||
else:
|
||||
job = table.prewarm_data_async(
|
||||
["attrs.score"], filter="id >= 8", concurrency=4
|
||||
)
|
||||
assert job.id == "warming-job"
|
||||
assert not polls
|
||||
assert job.wait().table_version == 42
|
||||
job.refresh()
|
||||
assert job.spec["table_version"] == 42
|
||||
assert db.open_job(job.id).wait().executors_completed == 2
|
||||
assert job.progress()["executors_completed"] == 2
|
||||
assert job.wait().bytes_read is None
|
||||
assert len(server.tickets) == 1
|
||||
assert b"PREWARM" in server.tickets[0]
|
||||
if mode != "job":
|
||||
assert not polls
|
||||
if mode == "columns":
|
||||
assert b'"payload"' in server.tickets[0]
|
||||
elif mode == "defaults":
|
||||
assert b"SELECT *" in server.tickets[0]
|
||||
else:
|
||||
assert b'"attrs"."score"' in server.tickets[0]
|
||||
assert b"concurrency = 4" in server.tickets[0]
|
||||
assert b"id >= 8" in server.tickets[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"options",
|
||||
[
|
||||
{"filter": ""},
|
||||
{"filter": "id > 0; DROP TABLE test"},
|
||||
{"filter": "id > 0 LIMIT 1"},
|
||||
{"concurrency": 0},
|
||||
{"concurrency": -1},
|
||||
{"concurrency": 2**32},
|
||||
{"concurrency": True},
|
||||
{"concurrency": 1.5},
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("method", ["prewarm_data", "prewarm_data_async"])
|
||||
def test_remote_data_prewarm_validates_before_submission(options, method):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class UnusedServer(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)
|
||||
raise AssertionError("invalid options must not submit SQL")
|
||||
|
||||
server = UnusedServer()
|
||||
with _mock_remote_table_with_sql(server) as table:
|
||||
with pytest.raises(ValueError):
|
||||
getattr(table, method)(**options)
|
||||
assert not server.tickets
|
||||
|
||||
|
||||
def test_remote_data_prewarm_malformed_receipt_is_not_retried():
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class MalformedServer(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": ["warming-job"]}))
|
||||
|
||||
server = MalformedServer()
|
||||
with _mock_remote_table_with_sql(server) as table:
|
||||
with pytest.raises(Exception, match="inspect jobs before retrying"):
|
||||
table.prewarm_data_async()
|
||||
assert len(server.tickets) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"outcome",
|
||||
[
|
||||
"counts",
|
||||
"legacy",
|
||||
"partial",
|
||||
"bounded",
|
||||
"no_op",
|
||||
"missing",
|
||||
"FAILED",
|
||||
"CANCELLED",
|
||||
],
|
||||
)
|
||||
async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
polls = []
|
||||
result = {
|
||||
"partial_commit": False,
|
||||
"rows_succeeded": 12,
|
||||
"rows_failed": 0,
|
||||
"completion_percentage": 100.0,
|
||||
}
|
||||
if outcome == "counts":
|
||||
result.update(
|
||||
files_added=1, files_removed=3, fragments_added=1, fragments_removed=3
|
||||
)
|
||||
|
||||
if outcome == "partial":
|
||||
result.update(
|
||||
partial_commit=True,
|
||||
rows_succeeded=8,
|
||||
rows_failed=4,
|
||||
completion_percentage=100 * 8 / 12,
|
||||
)
|
||||
if outcome == "bounded":
|
||||
result.update(more_work=True)
|
||||
if outcome == "no_op":
|
||||
result.update(
|
||||
rows_succeeded=0,
|
||||
files_added=0,
|
||||
files_removed=0,
|
||||
fragments_added=0,
|
||||
fragments_removed=0,
|
||||
)
|
||||
|
||||
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": ["compacting-job"]}))
|
||||
|
||||
def handler(request):
|
||||
if request.path != "/v1/jobs/describe":
|
||||
return _create_table_handler(request)
|
||||
body = json.loads(request.rfile.read(int(request.headers["Content-Length"])))
|
||||
assert body == {"job_id": "compacting-job"}
|
||||
polls.append(body)
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.end_headers()
|
||||
request.wfile.write(
|
||||
json.dumps(
|
||||
{
|
||||
"job_id": "compacting-job",
|
||||
"job_type": "compact",
|
||||
"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.compact_async(
|
||||
compaction_options={"target_rows_per_fragment": 100}
|
||||
)
|
||||
assert job.id == "compacting-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],
|
||||
):
|
||||
await job.wait()
|
||||
else:
|
||||
stats = await job.wait()
|
||||
reopened = await db.open_job(job.id)
|
||||
assert await reopened.wait() == stats
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
job = table.compact_async(
|
||||
compaction_options={"target_rows_per_fragment": 100}
|
||||
)
|
||||
assert job.id == "compacting-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],
|
||||
):
|
||||
job.wait()
|
||||
else:
|
||||
stats = job.wait()
|
||||
assert db.open_job(job.id).wait() == stats
|
||||
if outcome in ("counts", "legacy", "partial", "bounded", "no_op"):
|
||||
from lancedb.compaction import CompactionResult
|
||||
|
||||
assert isinstance(stats, CompactionResult)
|
||||
assert stats.rows_succeeded == (
|
||||
0 if outcome == "no_op" else 8 if outcome == "partial" else 12
|
||||
)
|
||||
assert stats.rows_failed == (4 if outcome == "partial" else 0)
|
||||
assert stats.partial_commit == (outcome == "partial")
|
||||
assert stats.more_work == (outcome == "bounded")
|
||||
assert stats.fragments_removed == (
|
||||
3 if outcome == "counts" else 0 if outcome == "no_op" else None
|
||||
)
|
||||
assert len(server.tickets) == 1
|
||||
assert b"OPTIMIZE" in server.tickets[0]
|
||||
assert b"target_rows_per_fragment = 100" in server.tickets[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ids", [[], [None], [""], ["a", "b"]])
|
||||
def test_remote_compaction_rejects_ambiguous_receipt_without_resubmission(ids):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class Server(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.calls = 0
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.calls += 1
|
||||
return flight.RecordBatchStream(
|
||||
pa.table({"job_id": pa.array(ids, pa.string())})
|
||||
)
|
||||
|
||||
server = Server()
|
||||
with _mock_remote_sql_connection(server) as kwargs:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
with pytest.raises(Exception, match="inspect jobs before retrying"):
|
||||
table.compact_async()
|
||||
assert server.calls == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["compact_async", "optimize"])
|
||||
@pytest.mark.parametrize(
|
||||
"option",
|
||||
["target_rows_per_fragment", "max_source_rows", "io_buffer_size", "batch_size"],
|
||||
)
|
||||
@pytest.mark.parametrize("value", [False, True])
|
||||
def test_remote_compaction_rejects_boolean_budgets_without_submitting(
|
||||
method, option, value
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class UnusedServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.calls = 0
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.calls += 1
|
||||
raise AssertionError("boolean compaction settings must not submit SQL")
|
||||
|
||||
server = UnusedServer()
|
||||
with _mock_remote_table_with_sql(server) as table:
|
||||
with pytest.raises(ValueError, match="must be an integer, not a bool"):
|
||||
getattr(table, method)(compaction_options={option: value})
|
||||
assert server.calls == 0
|
||||
|
||||
@@ -6414,3 +6414,22 @@ def test_fts_exist_ok_matches_quoted_default_name(mem_db):
|
||||
table.create_index("`body-text`", config=FTS(), exist_ok=True)
|
||||
assert table.version == before
|
||||
assert len(table.list_indices()) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("method", ["prewarm_data", "prewarm_data_async"])
|
||||
async def test_data_prewarm_job_is_unsupported_locally(tmp_path, asynchronous, method):
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("prewarm", [{"id": 1}])
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="only supported on remote tables"
|
||||
):
|
||||
await getattr(table, method)(filter="id > 0", concurrency=2)
|
||||
else:
|
||||
table = lancedb.connect(tmp_path).create_table("prewarm", [{"id": 1}])
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="only supported on remote tables"
|
||||
):
|
||||
getattr(table, method)(filter="id > 0", concurrency=2)
|
||||
|
||||
Reference in New Issue
Block a user