feat(python)!: make job data access method-only (#5095)

Make all Python `Job` and `AsyncJob` data access method-only. Cached
property accessors are private and underscore-prefixed; public reads use
`id()`, `state()`, `job_type()`, `creation_ms()`, `spec()`, `result()`
and `failure()`. `checkout_latest()` refreshes the complete cached
registry record in place and returns `None`.

```python
job.checkout_latest()
print(job.state(), job.result(), job.failure())
print(job.id(), job.job_type(), job.creation_ms(), job.spec())
```

Cached read methods are synchronous on both handle types. Async handles
use `await job.checkout_latest()` for the live refresh; event history
remains a separate request through `events()`. Update Python SDK
callers, tests and guides to use method calls, including
progress/timeout handling and bounded repr. Cover method-only visibility
and holistic snapshot freshness through both sync and async clients.

BREAKING CHANGE: Python job data access now requires method calls, such
as `job.state()` instead of `job.state`. No property compatibility
aliases remain.

Fixes
https://linear.app/lancedb/issue/ENT-3902/sdk-make-cached-versus-live-job-accessors-unambiguous
This commit is contained in:
Jack Ye
2026-11-20 17:37:12 -08:00
committed by GitHub
parent 8b814731c3
commit bfb55c72e9
14 changed files with 544 additions and 202 deletions
+1 -1
View File
@@ -1581,7 +1581,7 @@ class DBConnection(EnforceOverrides):
[RefreshColumnResult][lancedb.functions.RefreshColumnResult], including
when the refresh was started through SQL. Other job types return
``None`` from ``wait()``; their persisted result is available through
``job.result`` after ``job.refresh()``.
``job.result()`` after ``job.checkout_latest()``.
Raises `JobNotFoundError` when the server has no such job, the way
`open_table` does for a missing table.
+179 -58
View File
@@ -215,6 +215,11 @@ class AsyncJob(Generic[T]):
The operation may already be complete when the handle is created. ``T``
is the endpoint's terminal result type; unit-result jobs resolve to
``None``.
Methods such as ``state()``, ``result()``, ``failure()`` and ``spec()`` read
cached values without contacting the backend, including on async handles. Use
``await job.checkout_latest()`` to refresh the cached state and registry
details together. ``events()`` makes a separate request for event history.
"""
def __init__(
@@ -232,15 +237,18 @@ class AsyncJob(Generic[T]):
self._last_progress_snapshot = enriched
return enriched
@property
def id(self) -> Optional[str]:
"""The operation's opaque ID, interpreted according to :attr:`job_type`.
"""Return the operation's opaque ID, interpreted according to ``job_type()``.
Registry jobs expose a registry job ID; SQL-backed jobs expose a
connection-scoped query ID as a string. Local operations return ``None``.
Query IDs cannot be used with registry job APIs or to resume after a
client restart.
"""
return self._id
@property
def _id(self) -> Optional[str]:
return self._inner.id if self._inner is not None else None
async def status(self) -> str:
@@ -272,9 +280,9 @@ class AsyncJob(Generic[T]):
state = await self._inner.status()
description = getattr(self._inner, "_description", None)
if description is None or description.progress is None:
if self.job_type == "query":
if self.job_type() == "query":
return {
"job_id": self.id,
"job_id": self.id(),
"job_type": "query",
"state": state,
"client_elapsed_time_millis": int(
@@ -332,7 +340,9 @@ class AsyncJob(Generic[T]):
if self._inner is None:
return cast(T, None)
query_progress = (
progress is not False and progress is not None and self.job_type == "query"
progress is not False
and progress is not None
and self.job_type() == "query"
)
progress_obj, owns = _normalize_job_progress(progress, query=query_progress)
progress_callback = _job_progress_callback(progress_obj, self._enrich_progress)
@@ -406,15 +416,15 @@ class AsyncJob(Generic[T]):
if timeout is None:
raise
raise TimeoutError(
_timeout_message(self.id, timeout, self.job_type)
_timeout_message(self.id(), timeout, self.job_type())
) from error
identity = (
f"job {self.id!r}" if self.id is not None else "the operation"
f"job {self.id()!r}" if self.id() is not None else "the operation"
)
if self.id is not None and self.job_type != "query":
if self.id() is not None and self.job_type() != "query":
reconnect = (
f"Use db.open_job({self.id!r}) to reconnect, then call wait() "
"on the returned job."
f"Use db.open_job({self.id()!r}) to reconnect, "
"then call wait() on the returned job."
)
else:
reconnect = "Call wait() on this job handle to reconnect."
@@ -438,7 +448,7 @@ class AsyncJob(Generic[T]):
async def refresh(self) -> None:
"""Ask the backend for this job's current state, and for a server-side
job its full record, then cache it for the properties below.
job its full record, then cache it for the read methods below.
Registry details are `None` until this runs, because submitting an
operation does not fetch its full registry record. Query-backed jobs
@@ -450,49 +460,96 @@ class AsyncJob(Generic[T]):
return
await self._inner.refresh()
@property
def state(self) -> Optional[str]:
"""The last observed lifecycle state, without contacting the backend.
async def checkout_latest(self) -> None:
"""Refresh this handle's cached state and complete job record together.
`None` until the handle has talked to it. See :meth:`AsyncJob.refresh`.
For a registry job, each call fetches one current record and updates
the values returned by ``state()``, ``job_type()``, ``creation_ms()``,
``spec()``, ``result()`` and ``failure()`` from that observation. Calling
those read methods afterward does not contact the backend. Query-backed
and in-process jobs update their lifecycle state without registry details.
Updates this handle in place and returns ``None``. It does not wait for
completion or restart the operation. Failed or cancelled states are
cached without raising a job-failure exception; request errors propagate
and leave the cached record unchanged. Event history remains a separate
live request through [events()][lancedb.job.AsyncJob.events].
[refresh()][lancedb.job.AsyncJob.refresh] remains available with the
same behavior.
Examples
--------
>>> await job.checkout_latest() # doctest: +SKIP
>>> print(job.state(), job.result(), job.failure()) # doctest: +SKIP
"""
if self._inner is None:
return "finished"
return self._inner._state
await self.refresh()
def state(self) -> Optional[str]:
"""Return the last observed lifecycle state without contacting the backend.
`None` until the handle has talked to it. Call
[checkout_latest()][lancedb.job.AsyncJob.checkout_latest] to refresh
the state and registry details together.
"""
return self._state
@property
def _state(self) -> Optional[str]:
return self._inner._state if self._inner is not None else "finished"
def job_type(self) -> Optional[str]:
"""The job's kind of work, without contacting the backend.
"""Return the job's kind of work without contacting the backend.
SQL-backed handles report ``"query"`` immediately. Registry handles
report the server's job type after :meth:`refresh` or :meth:`status`.
In-process handles return ``None``.
"""
return self._job_type
@property
def _job_type(self) -> Optional[str]:
return self._inner.job_type if self._inner is not None else None
@property
def creation_ms(self) -> Optional[int]:
"""When the job was created, in milliseconds since the epoch."""
"""Return the cached creation time in epoch milliseconds; no backend call."""
return self._creation_ms
@property
def _creation_ms(self) -> Optional[int]:
return self._field("creation_ms")
@property
def spec(self) -> Optional[Any]:
"""The job-type-specific specification it was submitted with."""
"""Return the complete cached job specification without a backend call."""
return self._spec
@property
def _spec(self) -> Optional[Any]:
return self._field("spec")
@property
def result(self) -> Optional[Any]:
"""The job-type-specific terminal result, as reported data rather than
the typed model :meth:`AsyncJob.wait` returns.
"""Return the cached job-specific terminal result without a backend call.
`None` until the job succeeds, so a job that never terminates reports
its progress through :meth:`AsyncJob.events` instead.
This is reported data rather than the typed model
[wait()][lancedb.job.AsyncJob.wait] returns. It can remain `None` until
a successful registry record is fetched with
[checkout_latest()][lancedb.job.AsyncJob.checkout_latest] or another
live status request. For ongoing progress, use
[progress()][lancedb.job.AsyncJob.progress] or
[events()][lancedb.job.AsyncJob.events].
"""
return self._result
@property
def _result(self) -> Optional[Any]:
return self._field("result")
@property
def failure(self) -> Optional[JobFailureInfo]:
"""Why the job failed, when it failed and the server reports a reason."""
"""Return cached failure details, when reported, without a backend call."""
return self._failure
@property
def _failure(self) -> Optional[JobFailureInfo]:
return self._field("failure")
@property
@@ -590,7 +647,11 @@ class AsyncJob(Generic[T]):
) -> "pa.Table":
"""This job's recorded lifecycle events.
Where the properties above report a terminal result only once the job
Each call requests event history without updating the cached record.
Use [checkout_latest()][lancedb.job.AsyncJob.checkout_latest] to refresh
the job's state and registry details together.
Where the read methods above report a terminal result only once the job
reaches one, events are written as the job runs and outlive the workers
that produced them. A distributed job records a `claim`/`claim_complete`
pair per unit of work, each carrying `rows_processed`, so a job that
@@ -642,45 +703,53 @@ def _repr_payload(value: Any) -> str:
def _job_repr(kind: str, job: Any) -> str:
"""Show cached job identity and bounded previews without backend calls.
The complete payloads remain available through ``spec`` and ``result``.
The complete payloads remain available through ``spec()`` and ``result()``.
"""
state = job.state
state = job.state()
if state is None:
# Nothing has been fetched yet, so there is nothing to lay out.
known = f"id={_repr_payload(job.id)}, " if job.id is not None else ""
known = f"id={_repr_payload(job.id())}, " if job.id() is not None else ""
return f"{kind}({known}not refreshed)"
fields = []
if job.id is not None:
fields.append(f"id={_repr_payload(job.id)}")
if job.id() is not None:
fields.append(f"id={_repr_payload(job.id())}")
fields.append(f"state={_repr_payload(state)}")
for name in ("job_type", "creation_ms"):
value = getattr(job, name)
value = getattr(job, name)()
if value is not None:
fields.append(f"{name}={_repr_payload(value)}")
for name in ("spec", "result"):
value = getattr(job, name)
value = getattr(job, name)()
if value is not None:
fields.append(f"{name}={_repr_payload(value)}")
if job.failure is not None:
fields.append(f"failure={_repr_payload(job.failure)}")
if job.failure() is not None:
fields.append(f"failure={_repr_payload(job.failure())}")
body = "".join(f"\n{_REPR_INDENT}{field}," for field in fields)
return f"{kind}({body}\n)"
class Job(Generic[T]):
"""Synchronous counterpart of `AsyncJob` with the same result type."""
"""Synchronous counterpart of `AsyncJob` with the same result type.
Call ``state()``, ``result()``, ``failure()`` and ``spec()`` to read the
cached record after ``job.checkout_latest()`` refreshes it holistically.
``events()`` makes a separate live request for event history.
"""
def __init__(self, inner: Optional[AsyncJob[T]]):
self._inner = inner
@property
def id(self) -> Optional[str]:
"""Identifies the operation on the server that is running it.
"""Return the operation's opaque server ID without a backend call.
See :attr:`AsyncJob.id`.
See [AsyncJob.id()][lancedb.job.AsyncJob.id].
"""
return self._inner.id if self._inner is not None else None
return self._id
@property
def _id(self) -> Optional[str]:
return self._inner._id if self._inner is not None else None
def status(self) -> str:
"""The operation's current lifecycle state: "running", "finished",
@@ -740,35 +809,87 @@ class Job(Generic[T]):
return
LOOP.run(self._inner.refresh())
@property
def checkout_latest(self) -> None:
"""Refresh this handle's cached state and complete job record together.
Updates this handle in place and returns ``None`` without waiting for
completion. See
[AsyncJob.checkout_latest()][lancedb.job.AsyncJob.checkout_latest]
for refreshed fields and availability. ``refresh()`` remains available
with the same behavior.
Examples
--------
>>> job.checkout_latest() # doctest: +SKIP
>>> print(job.state(), job.result(), job.failure()) # doctest: +SKIP
"""
self.refresh()
def state(self) -> Optional[str]:
"""The last observed lifecycle state. See :attr:`AsyncJob.state`."""
return self._inner.state if self._inner is not None else "finished"
"""Return the cached lifecycle state without a backend call.
See [AsyncJob.state()][lancedb.job.AsyncJob.state].
"""
return self._state
@property
def _state(self) -> Optional[str]:
return self._inner._state if self._inner is not None else "finished"
def job_type(self) -> Optional[str]:
"""The job's type. See :attr:`AsyncJob.job_type`."""
return self._inner.job_type if self._inner is not None else None
"""Return the cached job type without a backend call.
See [AsyncJob.job_type()][lancedb.job.AsyncJob.job_type].
"""
return self._job_type
@property
def _job_type(self) -> Optional[str]:
return self._inner._job_type if self._inner is not None else None
def creation_ms(self) -> Optional[int]:
"""When the job was created. See :attr:`AsyncJob.creation_ms`."""
return self._field("creation_ms")
"""Return the cached creation time in epoch milliseconds.
See [AsyncJob.creation_ms()][lancedb.job.AsyncJob.creation_ms].
"""
return self._creation_ms
@property
def _creation_ms(self) -> Optional[int]:
return self._field("_creation_ms")
def spec(self) -> Optional[Any]:
"""The job's specification. See :attr:`AsyncJob.spec`."""
return self._field("spec")
"""Return the complete cached specification without a backend call.
See [AsyncJob.spec()][lancedb.job.AsyncJob.spec].
"""
return self._spec
@property
def _spec(self) -> Optional[Any]:
return self._field("_spec")
def result(self) -> Optional[Any]:
"""The job's terminal result. See :attr:`AsyncJob.result`."""
return self._field("result")
"""Return the cached terminal result without a backend call.
See [AsyncJob.result()][lancedb.job.AsyncJob.result].
"""
return self._result
@property
def _result(self) -> Optional[Any]:
return self._field("_result")
def failure(self) -> Optional[JobFailureInfo]:
"""Why the job failed. See :attr:`AsyncJob.failure`."""
return self._field("failure")
"""Return cached failure details without a backend call.
See [AsyncJob.failure()][lancedb.job.AsyncJob.failure].
"""
return self._failure
@property
def _failure(self) -> Optional[JobFailureInfo]:
return self._field("_failure")
@property
def _spec_json(self) -> Optional[str]:
+4 -4
View File
@@ -2165,9 +2165,9 @@ class Table(ABC):
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.
Save ``job.id()`` to resume with ``db.open_job(id)``. A wait timeout does
not cancel the operation. After ``job.checkout_latest()``,
``job.spec()["table_version"]`` identifies the pinned source version.
Examples
--------
@@ -3301,7 +3301,7 @@ class Table(ABC):
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
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
+2 -2
View File
@@ -985,7 +985,7 @@ def test_drop_table_async(tmp_db: lancedb.DBConnection):
assert tmp_db.table_names() == ["test"]
job = tmp_db.drop_table_async("test")
assert job.id is None
assert job.id() is None
assert job.status() == "finished"
assert job.wait() is None
assert tmp_db.table_names() == []
@@ -1001,7 +1001,7 @@ async def test_drop_table_async_connection(tmp_db_async: lancedb.AsyncConnection
await tmp_db_async.create_table("test", data=pa.table({"id": [1, 2]}))
job = await tmp_db_async.drop_table_async("test")
assert job.id is None
assert job.id() is None
assert await job.status() == "finished"
assert await job.wait() is None
assert await tmp_db_async.table_names() == []
+7 -7
View File
@@ -106,7 +106,7 @@ async def test_maintenance_job_result_and_reopen_against_server(
filter="id >= 8",
concurrency=2,
)
assert job.id
assert job.id()
progress = []
result = await call(job.wait, timeout=timeout, progress=progress.append)
assert any(snapshot["state"] == "finished" for snapshot in progress)
@@ -114,22 +114,22 @@ async def test_maintenance_job_result_and_reopen_against_server(
assert await call(job.status) == "finished"
if operation == "compact":
assert isinstance(result, CompactionResult)
assert job.job_type == "compact"
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 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)
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(
+2 -2
View File
@@ -92,7 +92,7 @@ async def binary_table(db_async):
@pytest.mark.asyncio
async def test_create_index_async_returns_done_job(some_table: AsyncTable):
job = await some_table.create_index_async("id", config=BTree())
assert job.id is None
assert job.id() is None
assert await job.wait() is None
assert len(await some_table.list_indices()) == 1
await job.cancel()
@@ -1045,7 +1045,7 @@ async def test_named_index_exist_ok_checks_before_column_validation(
method = some_table.create_index_async if background else some_table.create_index
result = await method("missing", config=BTree(), name="kept", exist_ok=True)
if background:
assert result.id is None
assert result.id() is None
await result.wait()
assert await some_table.version() == version
assert [index.name for index in await some_table.list_indices()] == ["kept"]
+138 -3
View File
@@ -16,6 +16,141 @@ from lancedb.job import AsyncJob, Job, _progress_eta
from lancedb.remote.errors import HttpError, RetryError
@pytest.mark.parametrize("job_class", [AsyncJob, Job])
def test_job_handle_data_access_uses_methods(job_class):
assert all(
name.startswith("_")
for name, member in vars(job_class).items()
if isinstance(member, property)
)
job = job_class(None)
expected = {
"id": None,
"state": "finished",
"job_type": None,
"creation_ms": None,
"spec": None,
"result": None,
"failure": None,
}
for name, value in expected.items():
assert callable(getattr(job, name))
assert getattr(job, name)() == value
assert getattr(job, f"_{name}") == value
@pytest.fixture(params=[False, True], ids=["async", "sync"])
def job_snapshot(request):
def create(inner):
job = AsyncJob(inner)
if request.param:
job = Job(job)
async def call(method="checkout_latest"):
if request.param:
return await asyncio.to_thread(getattr(job, method))
return await getattr(job, method)()
return job, call
return create
@pytest.mark.asyncio
@pytest.mark.parametrize("method", ["checkout_latest", "refresh"])
@pytest.mark.parametrize("state", ["finished", "failed", "cancelled", "future_state"])
async def test_job_checkout_latest_refreshes_the_complete_snapshot(
job_snapshot, method, state
):
spec = {"column": "vector", "initialization": list(range(1000))}
result = {"rows_assigned": 1000} if state == "finished" else None
failure = SimpleNamespace(message="worker failed") if state == "failed" else None
description = SimpleNamespace(
creation_ms=2000, spec=spec, result=result, failure=failure
)
inner = SimpleNamespace(
_state=None, _description=None, job_type=None, status=AsyncMock()
)
async def observe():
inner._state = state
inner.job_type = "refresh_column"
inner._description = description
inner.refresh = AsyncMock(side_effect=observe)
job, call = job_snapshot(inner)
assert job.state() is None
assert job.job_type() is None
assert job.creation_ms() is None
assert job.spec() is None
assert job.result() is None
assert job.failure() is None
inner.refresh.assert_not_called()
assert await call(method) is None
assert job.state() == state
assert job.job_type() == "refresh_column"
assert job.creation_ms() == 2000
assert job.spec() is spec
assert job.result() is result
assert job.failure() is failure
inner.refresh.assert_awaited_once_with()
inner.status.assert_not_called()
@pytest.mark.asyncio
async def test_job_checkout_latest_keeps_cached_details_on_request_error(job_snapshot):
error = HttpError("not found", "req-job", 404)
description = SimpleNamespace(
creation_ms=2000, spec={"column": "vector"}, result=None, failure=None
)
inner = SimpleNamespace(
_state="running",
_description=description,
job_type="refresh_column",
refresh=AsyncMock(side_effect=error),
)
job, call = job_snapshot(inner)
with pytest.raises(HttpError) as exc:
await call()
assert exc.value is error
assert job.state() == "running"
assert job.spec() is description.spec
assert job.result() is None
assert job.failure() is None
inner.refresh.assert_awaited_once_with()
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_job_checkout_latest_preserves_refresh_overrides(sync, monkeypatch):
job = AsyncJob(None)
if sync:
job = Job(job)
refresh = MagicMock() if sync else AsyncMock()
monkeypatch.setattr(job, "refresh", refresh)
if sync:
assert await asyncio.to_thread(job.checkout_latest) is None
else:
assert await job.checkout_latest() is None
refresh.assert_awaited_once_with()
refresh.assert_called_once_with()
@pytest.mark.asyncio
async def test_job_checkout_latest_for_completed_local_jobs(job_snapshot):
job, call = job_snapshot(None)
assert await call() is None
assert job.state() == "finished"
assert job.job_type() is None
assert job.spec() is None
assert job.result() is None
assert job.failure() is None
assert Job(None).checkout_latest() is None
@pytest.mark.parametrize("sync", [False, True])
def test_job_repr_bounds_large_payloads_without_fetching(sync):
spec = {"initialization": list(range(100000)), "source": "x" * 100000}
@@ -44,9 +179,9 @@ def test_job_repr_bounds_large_payloads_without_fetching(sync):
assert "worker failed" in rendered
assert "..." in rendered
assert len(repr(job.status)) < 1700
assert job.spec is spec
assert job.result is result
assert len(job.spec["initialization"]) == 100000
assert job.spec() is spec
assert job.result() is result
assert len(job.spec()["initialization"]) == 100000
@pytest.mark.parametrize("sync", [False, True])
+14 -14
View File
@@ -269,21 +269,21 @@ def test_create_and_refresh_jobs(tmp_path):
create_job = db.create_materialized_view_async(
"adults", "people", where="age >= 18", with_no_data=True
)
assert create_job.id is None
assert create_job.job_type is None
assert create_job.id() is None
assert create_job.job_type() is None
assert create_job.wait() is None
view = db.open_materialized_view("adults")
refresh_job = view.refresh_async()
assert refresh_job.id is None
assert refresh_job.job_type is None
assert refresh_job.id() is None
assert refresh_job.job_type() is None
result = refresh_job.wait()
assert result.mode == "rebuild"
assert result.rows_written == 2
assert view.table.count_rows() == 2
drop_job = db.drop_materialized_view_async("adults")
assert drop_job.id is None
assert drop_job.id() is None
assert drop_job.wait() is None
assert "adults" not in list(db.list_materialized_views())
@@ -442,20 +442,20 @@ async def test_async_create_and_refresh_jobs(tmp_path):
create_job = await db.create_materialized_view_async(
"adults", "people", with_no_data=True
)
assert create_job.id is None
assert create_job.job_type is None
assert create_job.id() is None
assert create_job.job_type() is None
assert await create_job.wait() is None
view = await db.open_materialized_view("adults")
refresh_job = await view.refresh_async()
assert refresh_job.id is None
assert refresh_job.job_type is None
assert refresh_job.id() is None
assert refresh_job.job_type() is None
result = await refresh_job.wait()
assert result.mode == "rebuild"
assert result.rows_written == 1
drop_job = await db.drop_materialized_view_async("adults")
assert drop_job.id is None
assert drop_job.id() is None
assert await drop_job.wait() is None
assert "adults" not in [item async for item in db.list_materialized_views()]
@@ -716,8 +716,8 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options
db = RemoteDBConnection.__new__(RemoteDBConnection)
db._conn = AsyncConnection(native)
job = db.create_materialized_view_async("adults", "people", **options)
assert job.id == QueryBackedCreateJob.id
assert job.job_type == "query"
assert job.id() == QueryBackedCreateJob.id
assert job.job_type() == "query"
assert not hasattr(job, "query_id")
assert job.wait() is None
assert job.status() == "finished"
@@ -747,8 +747,8 @@ async def test_async_remote_create_keeps_interval_unspecified():
job = await db.create_materialized_view_async(
"adults", "people", auto_refresh_enabled=True
)
assert job.id == QueryBackedCreateJob.id
assert job.job_type == "query"
assert job.id() == QueryBackedCreateJob.id
assert job.job_type() == "query"
assert not hasattr(job, "query_id")
assert await job.wait() is None
assert await job.status() == "finished"
+122 -74
View File
@@ -1,5 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import asyncio
from concurrent.futures import ThreadPoolExecutor
import contextlib
import copy
@@ -2331,7 +2332,7 @@ def test_remote_create_index_async_returns_job():
with mock_lancedb_connection(handler) as db:
table = db.create_table("test", [{"id": 1}])
job = table.create_index_async("id", config=BTree())
assert job.id == "job-1"
assert job.id() == "job-1"
observed = []
assert job.wait(timeout=timedelta(seconds=30), progress=observed.append) is None
assert len(describe_calls) == 2
@@ -2499,13 +2500,13 @@ async def test_remote_refresh_async_returns_typed_terminal_result(
async with mock_lancedb_connection_async(handler) as db:
table = await db.create_table("test", [{"id": 1}])
job = await table.refresh_column_async("derived", **refresh_kwargs)
assert job.id == "refresh-1"
assert job.id() == "refresh-1"
result = await job.wait(timeout=timedelta(seconds=30))
else:
with mock_lancedb_connection(handler) as db:
table = db.create_table("test", [{"id": 1}])
job = table.refresh_column_async("derived", **refresh_kwargs)
assert job.id == "refresh-1"
assert job.id() == "refresh-1"
result = job.wait(timeout=timedelta(seconds=30))
assert isinstance(result, lancedb.RefreshColumnResult)
@@ -3032,12 +3033,12 @@ async def test_remote_job_wait_recovers_from_disconnection(sync, failure):
with mock_lancedb_connection(handler, **config) as db:
job = db.open_job("job-1")
assert job.wait(timeout=timedelta(seconds=5)) is None
assert job.state == "finished"
assert job.state() == "finished"
else:
async with mock_lancedb_connection_async(handler, **config) as db:
job = await db.open_job("job-1")
assert await job.wait(timeout=timedelta(seconds=5)) is None
assert job.state == "finished"
assert job.state() == "finished"
assert polls == 5
@@ -3171,23 +3172,23 @@ async def test_reopened_refresh_job_wait_returns_typed_result(
if sync:
with mock_lancedb_connection(handler) as db:
job = db.open_job("refresh-1")
assert job.id == "refresh-1"
assert job.spec == {"column": "derived"}
assert job.id() == "refresh-1"
assert job.spec() == {"column": "derived"}
result = job.wait(timeout=timedelta(seconds=5), progress=observed.append)
assert job.wait() == result
job.refresh()
assert job.result == terminal_result
assert job.result() == terminal_result
else:
async with mock_lancedb_connection_async(handler) as db:
job = await db.open_job("refresh-1")
assert job.id == "refresh-1"
assert job.spec == {"column": "derived"}
assert job.id() == "refresh-1"
assert job.spec() == {"column": "derived"}
result = await job.wait(
timeout=timedelta(seconds=5), progress=observed.append
)
assert await job.wait() == result
await job.refresh()
assert job.result == terminal_result
assert job.result() == terminal_result
assert isinstance(result, lancedb.RefreshColumnResult)
assert result == lancedb.RefreshColumnResult.model_validate(terminal_result)
@@ -3256,12 +3257,12 @@ async def test_reopened_unit_job_ignores_additive_result_payload(sync):
with mock_lancedb_connection(handler) as db:
job = db.open_job("index-1")
assert job.wait() is None
assert job.result == terminal_result
assert job.result() == terminal_result
else:
async with mock_lancedb_connection_async(handler) as db:
job = await db.open_job("index-1")
assert await job.wait() is None
assert job.result == terminal_result
assert job.result() == terminal_result
@pytest.mark.parametrize("payload", [b"{", b"{}"])
@@ -3399,9 +3400,9 @@ async def test_remote_job_wait_preserves_terminal_build(sync, with_terminal_serv
expected += " (in function_refresh_attempt_failed)"
assert str(caught.value) == expected
assert caught.value.job_id == "job-provenance"
assert job.failure.message == message
assert job.failure.traceback == "Traceback: original user code"
assert job.result == result
assert job.failure().message == message
assert job.failure().traceback == "Traceback: original user code"
assert job.result() == result
@pytest.mark.parametrize("server_version", ["0.2.0", "0.6.0"])
@@ -7109,14 +7110,14 @@ def test_remote_connection_jobs_surface():
with pytest.raises(JobNotFoundError, match="missing"):
db.open_job("missing")
finished = db.open_job("job-2")
assert finished.state == "finished"
assert finished.result == {"rows_assigned": 1000000, "rows_failed": 0}
assert finished.state() == "finished"
assert finished.result() == {"rows_assigned": 1000000, "rows_failed": 0}
job = db.open_job("job-1")
assert job.id == "job-1"
assert job.id() == "job-1"
# Opening already populated the handle.
assert job.state == "failed"
assert job.spec == {"column": "vec"}
assert job.state() == "failed"
assert job.spec() == {"column": "vec"}
progress = job.progress()
assert progress["state"] == "failed"
assert progress["rows_computed"] == 4
@@ -7125,12 +7126,12 @@ def test_remote_connection_jobs_surface():
assert progress["queue_reason"] == "waiting for capacity"
assert progress["waiting_for_job_id"] == "job-maintenance"
assert progress["paused_at_millis"] == 1200
assert job.failure.message == "worker died"
assert job.failure.traceback == (
assert job.failure().message == "worker died"
assert job.failure().traceback == (
"Traceback (most recent call last):\nRuntimeError: worker died"
)
assert job.failure.sql_job_id == "sql-job-1"
assert repr(job.failure) == (
assert job.failure().sql_job_id == "sql-job-1"
assert repr(job.failure()) == (
'JobFailureInfo(phase="execute", message="worker died", retryable=True, '
'sql_job_id="sql-job-1")'
)
@@ -7145,7 +7146,13 @@ def test_remote_connection_jobs_surface():
assert finished.progress()["paused"] is False
def test_remote_job_handle_reports_its_own_detail():
@pytest.mark.asyncio
@pytest.mark.parametrize("is_async", [False, True])
@pytest.mark.parametrize("refresh_method", ["checkout_latest", "refresh"])
@pytest.mark.parametrize("terminal_state", ["DONE", "FAILED"])
async def test_remote_job_handle_reports_its_own_detail(
is_async, refresh_method, terminal_state
):
schema = pa.schema([("state", pa.string())])
batch = pa.record_batch([pa.array(["claim_complete"])], schema=schema)
sink = pa.BufferOutputStream()
@@ -7153,27 +7160,25 @@ def test_remote_job_handle_reports_its_own_detail():
writer.write_batch(batch)
events_body = sink.getvalue().to_pybytes()
event_payloads = []
descriptions = []
description = dict(
job_id="job-1",
job_type="refresh_column",
job_state="IN_PROGRESS",
creation_ms=2000,
spec=dict(column="vec"),
)
def handler(request):
content_len = int(request.headers.get("Content-Length", 0))
body = request.rfile.read(content_len) if content_len > 0 else b""
payload = json.loads(body) if body else {}
if request.path == "/v1/jobs/describe":
descriptions.append(payload)
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(
json.dumps(
dict(
job_id="job-1",
job_type="refresh_column",
job_state="DONE",
creation_ms=2000,
spec=dict(column="vec"),
result=dict(rows_assigned=1000000),
)
).encode()
)
request.wfile.write(json.dumps(description).encode())
elif request.path == "/v1/jobs/query_events":
event_payloads.append(payload)
request.send_response(200)
@@ -7184,39 +7189,75 @@ def test_remote_job_handle_reports_its_own_detail():
request.send_response(404)
request.end_headers()
with mock_lancedb_connection(handler) as db:
job = db.open_job("job-1")
async def check_job(db):
job = (
await db.open_job("job-1")
if is_async
else await asyncio.to_thread(db.open_job, "job-1")
)
# Opening populates the handle in the same round trip.
assert job.state == "finished"
job.refresh()
assert job.job_type == "refresh_column"
assert job.creation_ms == 2000
assert job.spec == {"column": "vec"}
assert job.result == {"rows_assigned": 1000000}
assert job.failure is None
assert job.state() == "running"
assert job.result() is None
assert job.failure() is None
description["job_state"] = terminal_state
expected_result = (
{"rows_assigned": 1000000} if terminal_state == "DONE" else None
)
description["result"] = expected_result
if terminal_state == "FAILED":
description["failure"] = {"phase": "execute", "message": "worker failed"}
assert job.state() == "running"
assert job.result() is None
assert job.failure() is None
assert len(descriptions) == 1
refresh = getattr(job, refresh_method)
if is_async:
assert await refresh() is None
else:
assert await asyncio.to_thread(refresh) is None
expected_state = "finished" if terminal_state == "DONE" else "failed"
assert job.state() == expected_state
assert job.job_type() == "refresh_column"
assert job.creation_ms() == 2000
assert job.spec() == {"column": "vec"}
assert job.result() == expected_result
if terminal_state == "FAILED":
assert job.failure().phase == "execute"
assert job.failure().message == "worker failed"
else:
assert job.failure() is None
# The JSON payloads stay reachable, but as internal APIs.
assert json.loads(job._spec_json) == {"column": "vec"}
assert json.loads(job._result_json) == {"rows_assigned": 1000000}
if expected_result is not None:
assert json.loads(job._result_json) == expected_result
assert repr(job) == "\n".join(
[
f"{type(job).__name__}(",
" id='job-1',",
" state='finished',",
" job_type='refresh_column',",
" creation_ms=2000,",
" spec={'column': 'vec'},",
" result={'rows_assigned': 1000000},",
")",
]
)
assert "failure" not in repr(job)
assert repr(job) == "\n".join(
[
"Job(",
" id='job-1',",
" state='finished',",
" job_type='refresh_column',",
" creation_ms=2000,",
" spec={'column': 'vec'},",
" result={'rows_assigned': 1000000},",
")",
]
events = (
await job.events(filter="state = 'claim_complete'", limit=500)
if is_async
else await asyncio.to_thread(
job.events, filter="state = 'claim_complete'", limit=500
)
)
# Nothing it does not know shows up.
assert "failure" not in repr(job)
events = job.events(filter="state = 'claim_complete'", limit=500)
assert isinstance(events, pa.Table)
assert events.column("state").to_pylist() == ["claim_complete"]
assert len(descriptions) == 2
assert job.state() == expected_state
assert job.result() == expected_result
# The handle supplies job_id; the caller only narrows the query.
assert event_payloads[-1] == {
"job_id": "job-1",
@@ -7224,6 +7265,13 @@ def test_remote_job_handle_reports_its_own_detail():
"filter": "state = 'claim_complete'",
}
if is_async:
async with mock_lancedb_connection_async(handler) as db:
await check_job(db)
else:
with mock_lancedb_connection(handler) as db:
await check_job(db)
@pytest.mark.parametrize("is_async", [False, True])
@pytest.mark.parametrize("known_build", [False, True])
@@ -8489,12 +8537,12 @@ async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mod
job = await table.prewarm_data_async(
["attrs.score"], filter="id >= 8", concurrency=4
)
assert job.id == "warming-job"
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 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
@@ -8516,12 +8564,12 @@ async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mod
job = table.prewarm_data_async(
["attrs.score"], filter="id >= 8", concurrency=4
)
assert job.id == "warming-job"
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.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
@@ -8647,7 +8695,7 @@ async def test_prewarm_bound_parameters_reach_flight(asynchronous, method, named
assert result.table_version == 42
assert result.pruning.selected_fragments == 1
else:
assert result.id == "bound-job"
assert result.id() == "bound-job"
((command, received),) = server.calls
assert b"PREWARM" in command and predicate.encode() in command
if method == "explain_prewarm_data":
@@ -8762,7 +8810,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome):
job = await table.compact_async(
compaction_options={"target_rows_per_fragment": 100}
)
assert job.id == "compacting-job" and not polls
assert job.id() == "compacting-job" and not polls
if outcome in ("missing", "FAILED", "CANCELLED"):
with pytest.raises(
Exception,
@@ -8775,7 +8823,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome):
await job.wait()
else:
stats = await job.wait()
reopened = await db.open_job(job.id)
reopened = await db.open_job(job.id())
assert await reopened.wait() == stats
else:
db = lancedb.connect(**kwargs)
@@ -8783,7 +8831,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome):
job = table.compact_async(
compaction_options={"target_rows_per_fragment": 100}
)
assert job.id == "compacting-job" and not polls
assert job.id() == "compacting-job" and not polls
if outcome in ("missing", "FAILED", "CANCELLED"):
with pytest.raises(
Exception,
@@ -8796,7 +8844,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome):
job.wait()
else:
stats = job.wait()
assert db.open_job(job.id).wait() == stats
assert db.open_job(job.id()).wait() == stats
if outcome in ("counts", "legacy", "partial", "bounded", "no_op"):
from lancedb.compaction import CompactionResult
+2 -2
View File
@@ -2312,7 +2312,7 @@ async def test_async_open_table_with_branch_version(tmp_path):
def test_create_index_async_returns_done_job(mem_db: DBConnection):
table = mem_db.create_table("job_test", [{"id": i} for i in range(10)])
job = table.create_index_async("id", config=BTree())
assert job.id is None
assert job.id() is None
assert job.wait() is None
assert len(table.list_indices()) == 1
job.cancel()
@@ -6646,7 +6646,7 @@ def test_refresh_column_async_returns_job(tmp_path, batch_size):
table.add_columns(computed={"doubled": "x * 2"})
job = table.refresh_column_async("doubled", batch_size=batch_size)
assert job.id is None # in-process jobs have no server id
assert job.id() is None # in-process jobs have no server id
result = job.wait()
assert isinstance(result, lancedb.RefreshColumnResult)
assert result.rows_assigned == 2