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:
@@ -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