fix(python): show Function registration progress and image details (#5040)

Report registration lifecycle and client elapsed time through existing job handles, and provide concise image inspection. Preserve quiet wait behavior, environment-lock forwarding, failure diagnostics and timeout recovery.
This commit is contained in:
Jack Ye
2026-11-15 02:05:06 -08:00
committed by GitHub
parent 1feec84d2b
commit 3aed07c396
6 changed files with 396 additions and 13 deletions
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
import warnings
from collections import UserDict
from pathlib import Path
from types import MappingProxyType
@@ -13,6 +14,7 @@ import lancedb.functions as functions
from lancedb.functions import (
FunctionApplication,
FunctionBinding,
FunctionImage,
FunctionVersion,
PythonRuntimeSpec,
SecretBinding,
@@ -149,6 +151,59 @@ def test_function_version_identity_is_immutable_and_exact():
FunctionVersion(**{**value, "version": invalid})
@pytest.mark.parametrize("gpu", [False, True])
def test_image_inspection_is_concise_warning_free_and_preserves_wire_state(gpu):
value = job_result("remote_function_job.json")["image"]
value["descriptor"]["future_metadata"] = "x" * 100_000
if gpu:
value["descriptor"]["requires"]["capabilities"] = [
{
"type": "lance.cuda",
"version": 1,
"device_count": 1,
"cuda_toolkit": "12.4",
}
]
image = FunctionImage(**value)
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
details = image.describe()
rendered = repr(image)
assert "manifest_digest=" in str(image)
encoded = json.loads(image.to_canonical_json())
assert details == {
"manifest_digest": value["manifest_digest"],
"python_version": "3.12.14",
"requires_gpu": gpu,
"cuda_toolkit": "12.4" if gpu else None,
"platforms": None,
"base_image": None,
"size_bytes": None,
}
assert len(rendered) < 350
assert f"requires_gpu={gpu}" in rendered
assert "future_metadata" not in rendered
assert encoded == value
@pytest.mark.parametrize(
"descriptor",
[
{},
{"format_version": 2, "requires": {"capabilities": []}},
{"format_version": 1, "requires": {"capabilities": [None]}},
{"python": {"version": {"future": "x" * 100_000}}},
],
)
def test_image_inspection_leaves_missing_or_unrecognized_metadata_unknown(descriptor):
image = FunctionImage(
manifest_digest="sha256:example", descriptor=descriptor, source=True
)
assert image.describe()["requires_gpu"] is None
assert image.describe()["python_version"] is None
assert len(repr(image)) < 350
@pytest.mark.parametrize(
"case", json.loads(fixture("runtime_identity.json")), ids=lambda case: case["name"]
)
+187 -3
View File
@@ -11,6 +11,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from lancedb.exceptions import JobCancelledError, JobFailedError
from lancedb.db import DBConnection
from lancedb.job import AsyncJob, Job, _progress_eta
from lancedb.remote.errors import HttpError, RetryError
@@ -729,15 +730,198 @@ async def test_wait_progress_bar_tracks_late_planning_without_regressing(
@pytest.mark.asyncio
async def test_wait_progress_false_keeps_legacy_inner_wait_call():
@pytest.mark.parametrize("progress", [False, None])
async def test_wait_progress_false_keeps_legacy_inner_wait_call(progress):
class NoProgressArgument:
id = "job-legacy"
job_type = None
@property
def job_type(self):
raise AssertionError("quiet waits must not inspect progress metadata")
async def wait(self):
return None
assert await AsyncJob(NoProgressArgument()).wait(progress=False) is None
assert await AsyncJob(NoProgressArgument()).wait(progress=progress) is None
class _RegistrationQuery:
id = "registration-query"
job_type = "query"
_description = None
def __init__(self, error=None):
self.ready = asyncio.Event()
self.error = error
self.state = "running"
self.wait_calls = 0
self.cancel_calls = 0
async def status(self):
return self.state
async def wait(self, progress=None):
self.wait_calls += 1
await self.ready.wait()
if self.error is not None:
self.state = (
"cancelled" if isinstance(self.error, JobCancelledError) else "failed"
)
raise self.error
self.state = "finished"
return '{"version": "1"}'
async def cancel(self):
self.cancel_calls += 1
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_query_progress_observes_one_registration_waiter(sync, monkeypatch):
monkeypatch.setattr("lancedb.job._QUERY_PROGRESS_INTERVAL_SECONDS", 0)
inner = _RegistrationQuery()
job = AsyncJob(inner, json.loads)
updates = []
def observe(snapshot):
updates.append(snapshot)
if len(updates) == 2:
inner.ready.set()
if sync:
result = await asyncio.to_thread(Job(job).wait, progress=observe)
else:
result = await job.wait(progress=observe)
assert result == {"version": "1"}
assert inner.wait_calls == 1
assert inner.cancel_calls == 0
assert updates[0]["state"] == "running"
assert updates[-1]["state"] == "finished"
assert all(snapshot["job_id"] == inner.id for snapshot in updates)
elapsed = [snapshot["client_elapsed_time_millis"] for snapshot in updates]
assert elapsed == sorted(elapsed)
assert elapsed[0] >= 0
assert all("phase" not in snapshot for snapshot in updates)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"error",
[
JobFailedError("bake failed", job_id="registration-query"),
JobCancelledError("cancelled"),
],
)
async def test_query_progress_preserves_terminal_exceptions(error):
inner = _RegistrationQuery(error)
inner.ready.set()
updates = []
with pytest.raises(type(error)) as raised:
await AsyncJob(inner).wait(progress=updates.append)
assert raised.value is error
assert updates[-1]["state"] == inner.state
assert inner.wait_calls == 1
@pytest.mark.asyncio
async def test_query_progress_display_has_no_row_counter_and_closes_on_failure(
monkeypatch,
):
tqdm_module = pytest.importorskip("tqdm.auto")
bar = SimpleNamespace(
n=0,
total=None,
update=MagicMock(),
set_postfix_str=MagicMock(),
close=MagicMock(),
)
constructor = MagicMock(return_value=bar)
monkeypatch.setattr(tqdm_module, "tqdm", constructor)
inner = _RegistrationQuery(JobFailedError("bake failed"))
inner.ready.set()
with pytest.raises(JobFailedError, match="bake failed"):
await AsyncJob(inner).wait(progress=True)
assert "elapsed" in constructor.call_args.kwargs["bar_format"]
assert "rows" not in str(constructor.call_args)
assert bar.set_postfix_str.call_args.args == ("failed",)
bar.close.assert_called_once_with()
@pytest.mark.asyncio
@pytest.mark.parametrize("failed", [False, True])
@pytest.mark.parametrize("observer_error", ["status", "callback"])
async def test_query_progress_observer_errors_do_not_replace_result_or_server_failure(
failed, observer_error, caplog
):
error = (
JobFailedError("bake failed", job_id="registration-query") if failed else None
)
inner = _RegistrationQuery(error)
inner.ready.set()
if observer_error == "status":
inner.status = AsyncMock(side_effect=RuntimeError("observer failed"))
def observe(snapshot):
if observer_error == "callback":
raise RuntimeError("observer failed")
job = AsyncJob(inner, json.loads)
if failed:
with pytest.raises(JobFailedError) as raised:
await job.wait(progress=observe)
assert raised.value is error
else:
assert await job.wait(progress=observe) == {"version": "1"}
assert inner.wait_calls == 1
assert inner.cancel_calls == 0
assert "job progress observer failed" in caplog.text
@pytest.mark.asyncio
async def test_query_progress_timeout_keeps_registration_available_on_same_handle():
inner = _RegistrationQuery()
job = AsyncJob(inner, json.loads)
updates = []
with pytest.raises(TimeoutError, match="keep this handle"):
await job.wait(timeout=timedelta(seconds=0.01), progress=updates.append)
assert inner.state == "running"
assert inner.cancel_calls == 0
inner.ready.set()
assert await job.wait(progress=updates.append) == {"version": "1"}
assert inner.wait_calls == 2
assert updates[-1]["state"] == "finished"
@pytest.mark.parametrize("refresh_lock", [False, True])
def test_blocking_create_function_forwards_progress_to_registration_handle(
refresh_lock,
):
connection = MagicMock()
definition = object()
progress = object()
result = DBConnection.create_function(
connection, definition, refresh_lock=refresh_lock, progress=progress
)
connection.create_function_async.assert_called_once_with(
definition,
secrets=None,
exist_ok=False,
namespace_path=None,
refresh_lock=refresh_lock,
)
connection.create_function_async.return_value.wait.assert_called_once_with(
progress=progress
)
assert result is connection.create_function_async.return_value.wait.return_value
@pytest.mark.parametrize("progress", [False, None])
def test_blocking_create_function_preserves_quiet_wait_call(progress):
connection = MagicMock()
result = DBConnection.create_function(connection, object(), progress=progress)
connection.create_function_async.return_value.wait.assert_called_once_with()
assert result is connection.create_function_async.return_value.wait.return_value
@pytest.mark.asyncio