fix!: preserve job attempt lineage, retries, and lifecycle states

BREAKING CHANGE: JobDescription, JobEventsRequest, FunctionErrorsRequest, and FunctionErrors gain optional Rust metadata/cursor fields. Existing struct literals must initialize them; use None when unavailable.

Preserve typed attempt state, pinned retry lineage, result decoders and freshness fences, and retained diagnostic paging across SDKs. Keep Python job data access method-only.
This commit is contained in:
Jack Ye
2026-11-20 20:35:59 -08:00
committed by GitHub
parent bfb55c72e9
commit b44807e4db
35 changed files with 1822 additions and 55 deletions
+2 -1
View File
@@ -40,7 +40,7 @@ from .remote.db import RemoteDBConnection
from .expr import Expr, col, lit, func
from .schema import BasePath, blob, blob_uri_array, vector
from ._blob_reader import BlobReader as BlobReader
from .job import AsyncJob, Job
from .job import AsyncJob, Job, JobState
from .sql import AsyncQuery as AsyncSqlQuery
from .sql import Query as SqlQuery
from .sql import QueryDescription
@@ -701,6 +701,7 @@ __all__ = [
"vector",
"DBConnection",
"Job",
"JobState",
"QueryDescription",
"SqlQuery",
"LanceDBConnection",
+32
View File
@@ -439,6 +439,20 @@ class BlobFile:
def read_up_to(self, length: int) -> bytes: ...
class Job:
@property
def job_id(self) -> Optional[str]: ...
@property
def operation_id(self) -> Optional[str]: ...
@property
def attempt(self) -> Optional[int]: ...
@property
def retry_of(self) -> Optional[str]: ...
@property
def lifecycle_state(self) -> Optional[str]: ...
@property
def source_table_version(self) -> Optional[int]: ...
@property
def execution_epoch(self) -> Optional[int]: ...
@property
def id(self) -> Optional[str]: ...
@property
@@ -453,6 +467,7 @@ class Job:
progress: Optional[Callable[[dict[str, Any]], None]] = None,
) -> Optional[str]: ...
async def cancel(self) -> None: ...
async def retry(self) -> Job: ...
async def refresh(self) -> None: ...
async def timeline(self) -> str: ...
async def stack(self, worker_id: str) -> str: ...
@@ -462,6 +477,7 @@ class Job:
*,
limit: Optional[int] = None,
filter: Optional[str] = None,
page_token: Optional[str] = None,
) -> pa.Table: ...
class JobInfo:
@@ -526,6 +542,18 @@ class JobFailureInfo:
def sql_job_id(self) -> Optional[str]: ...
class JobDescription:
@property
def operation_id(self) -> Optional[str]: ...
@property
def attempt(self) -> Optional[int]: ...
@property
def retry_of(self) -> Optional[str]: ...
@property
def lifecycle_state(self) -> Optional[str]: ...
@property
def source_table_version(self) -> Optional[int]: ...
@property
def execution_epoch(self) -> Optional[int]: ...
@property
def job_id(self) -> str: ...
@property
@@ -766,6 +794,7 @@ class Table:
column: Optional[str] = None,
limit: Optional[int] = None,
history: bool = False,
page_token: Optional[str] = None,
) -> FunctionErrors: ...
async def quarantine_function_errors(
self,
@@ -1250,6 +1279,7 @@ class FunctionErrorRecord:
input: Optional[str]
attempts: Optional[int]
job_id: str
attempt_job_id: Optional[str]
fragment_id: int
row_offset: Optional[int]
row_id: Optional[int]
@@ -1273,6 +1303,8 @@ class FunctionErrorFragment:
class FunctionErrors:
workflow_version: Optional[int]
error_groups_json: str
@property
def page_token(self) -> Optional[str]: ...
records: list[FunctionErrorRecord]
fragments: list[FunctionErrorFragment]
truncated: bool
+1
View File
@@ -1176,6 +1176,7 @@ class _FunctionErrors:
self.records = raw.records
self.fragments = raw.fragments
self.truncated = raw.truncated
self.page_token = getattr(raw, "page_token", None)
def __repr__(self) -> str:
return repr(self._raw)
+213 -5
View File
@@ -10,9 +10,20 @@ import reprlib
import time
from contextlib import suppress
from datetime import timedelta
from enum import Enum
from os import PathLike
from pathlib import Path
from typing import Any, Callable, Generic, Optional, TypeVar, cast
from typing import (
Any,
AsyncIterator,
Callable,
Generic,
Iterator,
Optional,
TypeVar,
cast,
)
from uuid import uuid4
import pyarrow as pa
@@ -34,9 +45,49 @@ __all__ = [
"JobDescription",
"JobFailureInfo",
"JobInfo",
"JobState",
]
class JobState(str, Enum):
"""Detailed lifecycle of one attempt, retaining unknown future values."""
CREATED = "created"
QUEUED = "queued"
IN_PROGRESS = "in_progress"
SUCCEEDED = "succeeded"
FAILED = "failed"
CANCELED = "canceled"
TIMED_OUT = "timed_out"
@classmethod
def _missing_(cls, value):
if not isinstance(value, str):
return None
aliases = {
"running": cls.IN_PROGRESS,
"finished": cls.SUCCEEDED,
"cancelled": cls.CANCELED,
}
if value in aliases:
return aliases[value]
member = str.__new__(cls, value)
member._name_ = None
member._value_ = value
return member
@property
def is_terminal(self) -> bool:
return self in (self.SUCCEEDED, self.FAILED, self.CANCELED, self.TIMED_OUT)
@property
def is_success(self) -> bool:
return self == self.SUCCEEDED
def __str__(self) -> str:
return self.value
def _timeout_message(
job_id: Optional[str], timeout: timedelta, job_type: Optional[str]
) -> str:
@@ -45,7 +96,7 @@ def _timeout_message(
if job_id is None:
return (
f"operation still running after {seconds} {unit}; "
"it continues on the server"
"keep this handle to continue waiting"
)
if job_type == "query":
return (
@@ -231,6 +282,7 @@ class AsyncJob(Generic[T]):
self._result_decoder = result_decoder
self._last_progress_snapshot = None
self._created_at = time.monotonic()
self._local_job_id = str(uuid4()) if inner is None else None
def _enrich_progress(self, snapshot):
enriched = _with_progress_eta(self._last_progress_snapshot, snapshot)
@@ -263,6 +315,54 @@ class AsyncJob(Generic[T]):
return "finished"
return await self._inner.status()
def job_id(self) -> Optional[str]:
"""Identity of the selected attempt last observed by this handle.
For operation handles, ``refresh()`` or ``status()`` can select a
different attempt while ``id()`` stays unchanged. Save this value after
refreshing and use it throughout paged diagnostics. Embedded IDs cannot
be reopened on a server.
"""
return (
getattr(self._inner, "job_id", self.id())
if self._inner is not None
else self._local_job_id
)
def operation_id(self) -> Optional[str]:
"""Root of the explicit retry lineage, when known."""
return (
getattr(self._inner, "operation_id", None)
if self._inner is not None
else self._local_job_id
)
def attempt(self) -> Optional[int]:
"""One-based attempt ordinal; worker replacement does not increment it."""
return getattr(self._inner, "attempt", None) if self._inner is not None else 1
def retry_of(self) -> Optional[str]:
"""Immediate predecessor attempt, when supplied by the backend."""
return getattr(self._inner, "retry_of", None)
def lifecycle_state(self) -> Optional[JobState]:
"""Detailed state last observed; unknown values never imply success."""
raw = getattr(self._inner, "lifecycle_state", None) or self.state()
return JobState(raw) if raw is not None else None
async def status_typed(self) -> JobState:
"""Refresh and return the detailed, forward-compatible lifecycle state."""
state = await self.status()
return self.lifecycle_state() or JobState(state)
def source_table_version(self) -> Optional[int]:
"""Source snapshot pinned for this attempt, when reported."""
return getattr(self._inner, "source_table_version", None)
def execution_epoch(self) -> Optional[int]:
"""Most recent execution's fencing token, when reported."""
return getattr(self._inner, "execution_epoch", None)
async def progress(self) -> Optional[dict[str, Any]]:
"""Fetch a structured progress snapshot.
@@ -446,6 +546,18 @@ class AsyncJob(Generic[T]):
return
await self._inner.cancel()
async def retry(self) -> "AsyncJob[T]":
"""Select a successor for this exact failed attempt using pinned inputs.
Repeated requests select the same successor even after it finishes.
Requires a supporting server and a safely retryable Function job.
In-process operations do not retain a replayable specification and
raise ``NotImplementedError``.
"""
if self._inner is None:
raise NotImplementedError("retry requires a registry-backed job")
return AsyncJob(await self._inner.retry(), self._result_decoder)
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 read methods below.
@@ -644,6 +756,7 @@ class AsyncJob(Generic[T]):
*,
limit: Optional[int] = None,
filter: Optional[str] = None,
page_token: Optional[str] = None,
) -> "pa.Table":
"""This job's recorded lifecycle events.
@@ -675,7 +788,29 @@ class AsyncJob(Generic[T]):
"jobs",
)
)
return await self._inner.events(limit=limit, filter=filter)
if page_token is None:
return await self._inner.events(limit=limit, filter=filter)
return await self._inner.events(
limit=limit, filter=filter, page_token=page_token
)
async def history(
self, *, limit: Optional[int] = None, filter: Optional[str] = None
) -> AsyncIterator["pa.Table"]:
"""Walk retained history in pages, following opaque server continuations."""
token = None
while True:
page = await self.events(limit=limit, filter=filter, page_token=token)
yield page
next_token = (page.schema.metadata or {}).get(
b"lancedb.job_coordinator.page_token"
)
if next_token is None:
return
next_token = next_token.decode()
if next_token == token:
raise RuntimeError("job history repeated its page token")
token = next_token
def __repr__(self) -> str:
return _job_repr("AsyncJob", self)
@@ -738,7 +873,62 @@ class Job(Generic[T]):
"""
def __init__(self, inner: Optional[AsyncJob[T]]):
self._inner = inner
self._inner = inner if inner is not None else AsyncJob(None)
def job_id(self) -> Optional[str]:
"""Selected attempt ID; refresh can change it while ``id()`` stays fixed.
Save the value after refreshing for paged diagnostics.
See [AsyncJob.job_id()][lancedb.job.AsyncJob.job_id].
"""
return self._inner.job_id()
def operation_id(self) -> Optional[str]:
"""Root retry identity.
See [AsyncJob.operation_id()][lancedb.job.AsyncJob.operation_id].
"""
return self._inner.operation_id()
def attempt(self) -> Optional[int]:
"""One-based attempt ordinal.
See [AsyncJob.attempt()][lancedb.job.AsyncJob.attempt].
"""
return self._inner.attempt()
def retry_of(self) -> Optional[str]:
"""Immediate predecessor.
See [AsyncJob.retry_of()][lancedb.job.AsyncJob.retry_of].
"""
return self._inner.retry_of()
def lifecycle_state(self) -> Optional[JobState]:
"""Detailed state last observed.
See [AsyncJob.lifecycle_state()][lancedb.job.AsyncJob.lifecycle_state].
"""
return self._inner.lifecycle_state()
def status_typed(self) -> JobState:
"""Refresh the detailed lifecycle state. See :meth:`AsyncJob.status_typed`."""
return LOOP.run(self._inner.status_typed())
def source_table_version(self) -> Optional[int]:
"""Pinned source snapshot.
See the async handle's
[source_table_version()][lancedb.job.AsyncJob.source_table_version].
"""
return self._inner.source_table_version()
def execution_epoch(self) -> Optional[int]:
"""Execution fencing token.
See [AsyncJob.execution_epoch()][lancedb.job.AsyncJob.execution_epoch].
"""
return self._inner.execution_epoch()
def id(self) -> Optional[str]:
"""Return the operation's opaque server ID without a backend call.
@@ -800,6 +990,10 @@ class Job(Generic[T]):
return
LOOP.run(self._inner.cancel())
def retry(self) -> "Job[T]":
"""Select this attempt's pinned successor. See :meth:`AsyncJob.retry`."""
return Job(LOOP.run(self._inner.retry()))
def refresh(self) -> None:
"""Ask the backend for this job's current state and record.
@@ -954,6 +1148,7 @@ class Job(Generic[T]):
*,
limit: Optional[int] = None,
filter: Optional[str] = None,
page_token: Optional[str] = None,
) -> "pa.Table":
"""This job's recorded lifecycle events.
@@ -966,7 +1161,20 @@ class Job(Generic[T]):
"jobs",
)
)
return LOOP.run(self._inner.events(limit=limit, filter=filter))
return LOOP.run(
self._inner.events(limit=limit, filter=filter, page_token=page_token)
)
def history(
self, *, limit: Optional[int] = None, filter: Optional[str] = None
) -> Iterator["pa.Table"]:
"""Walk retained history in pages. See :meth:`AsyncJob.history`."""
pages = self._inner.history(limit=limit, filter=filter)
try:
while (page := LOOP.run(anext(pages, None))) is not None:
yield page
finally:
LOOP.run(pages.aclose())
def __repr__(self) -> str:
return _job_repr("Job", self)
+6 -1
View File
@@ -1334,10 +1334,15 @@ class RemoteTable(Table):
column: Optional[str] = None,
limit: Optional[int] = None,
history: bool = False,
page_token: Optional[str] = None,
):
return LOOP.run(
self._table.function_errors(
job_id=job_id, column=column, limit=limit, history=history
job_id=job_id,
column=column,
limit=limit,
history=history,
page_token=page_token,
)
).as_sync(self)
+23 -4
View File
@@ -3272,7 +3272,7 @@ class Table(ABC):
The server does not enforce coordination. Cancellation cannot undo deletion
or prove storage I/O stopped. Preview is available without deletion.
Save ``job.id`` to reopen with ``db.open_job(id)``. Waiting returns
Save ``job.id()`` to reopen with ``db.open_job(id)``. Waiting returns
[CleanupResult][lancedb.cleanup.CleanupResult]; timeout leaves work running.
Unknown totals after retry/recovery remain None. Auxiliary sweeps are
best effort and excluded from the version-deletion counts.
@@ -3952,6 +3952,7 @@ class Table(ABC):
column: Optional[str] = None,
limit: Optional[int] = None,
history: bool = False,
page_token: Optional[str] = None,
) -> "FunctionErrors":
"""
The per-row errors Function refreshes recorded on this table.
@@ -3977,6 +3978,10 @@ class Table(ABC):
Include retained historical errors instead of current failures.
Requires Enterprise workflow version 1 or later. Historical records
cannot be used with the current-input ``rows()`` helper.
page_token: str, optional
Empty starts retained history, including repaired rows, for an exact
job_id. Continue with the response's
page_token until it is None, keeping all filters unchanged.
Returns
-------
@@ -6621,12 +6626,17 @@ class LanceTable(Table):
column: Optional[str] = None,
limit: Optional[int] = None,
history: bool = False,
page_token: Optional[str] = None,
) -> "FunctionErrors":
"""The per-row errors Function refreshes recorded on this table. See
[`Table.function_errors`][lancedb.table.Table.function_errors]."""
return LOOP.run(
self._table.function_errors(
job_id=job_id, column=column, limit=limit, history=history
job_id=job_id,
column=column,
limit=limit,
history=history,
page_token=page_token,
)
).as_sync(self)
@@ -9435,6 +9445,7 @@ class AsyncTable:
column: Optional[str] = None,
limit: Optional[int] = None,
history: bool = False,
page_token: Optional[str] = None,
) -> "AsyncFunctionErrors":
"""
The per-row errors Function refreshes recorded on this table.
@@ -9460,6 +9471,10 @@ class AsyncTable:
Include retained historical errors instead of current failures.
Requires Enterprise workflow version 1 or later. Historical records
cannot be used with the current-input ``rows()`` helper.
page_token: str, optional
Empty starts retained history, including repaired rows, for an exact
job_id. Continue with the response's
page_token until it is None, keeping all filters unchanged.
Returns
-------
@@ -9522,9 +9537,13 @@ class AsyncTable:
... print("listing stopped at the limit")
"""
raw = await self._inner.function_errors(
job_id=job_id, column=column, limit=limit, history=history
job_id=job_id,
column=column,
limit=limit,
history=history,
page_token=page_token,
)
return AsyncFunctionErrors(raw, self, history=history)
return AsyncFunctionErrors(raw, self, history=history or page_token is not None)
async def column_statuses(
self, column: Optional[str] = None
+2 -2
View File
@@ -114,7 +114,7 @@ async def test_cleanup_submission_wait_and_reopen(asynchronous, outcome):
db = lancedb.connect(**kwargs)
table = db.create_table("test", [{"id": 1}])
job = table.cleanup_async(min_age_seconds=0)
assert job.id == "cleanup-job" and not polls
assert job.id() == "cleanup-job" and not polls
if outcome in ("missing", "FAILED", "CANCELLED"):
with pytest.raises(
Exception,
@@ -133,7 +133,7 @@ async def test_cleanup_submission_wait_and_reopen(asynchronous, outcome):
assert isinstance(stats, CleanupResult)
assert stats.old_versions == result["old_versions"]
reopened = (
await db.open_job(job.id) if asynchronous else db.open_job(job.id)
await db.open_job(job.id()) if asynchronous else db.open_job(job.id())
)
assert (await reopened.wait() if asynchronous else reopened.wait()) == stats
assert len(server.tickets) == 1
+56 -2
View File
@@ -9,10 +9,11 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
import pyarrow as pa
from lancedb.exceptions import JobCancelledError, JobFailedError
from lancedb.db import DBConnection
from lancedb.job import AsyncJob, Job, _progress_eta
from lancedb.job import AsyncJob, Job, JobState, _progress_eta
from lancedb.remote.errors import HttpError, RetryError
@@ -69,17 +70,30 @@ async def test_job_checkout_latest_refreshes_the_complete_snapshot(
creation_ms=2000, spec=spec, result=result, failure=failure
)
inner = SimpleNamespace(
_state=None, _description=None, job_type=None, status=AsyncMock()
id="operation-1",
_state=None,
_description=None,
job_type=None,
status=AsyncMock(),
)
async def observe():
inner._state = state
inner.job_type = "refresh_column"
inner._description = description
inner.job_id = "attempt-2"
inner.operation_id = "operation-1"
inner.attempt = 2
inner.retry_of = "attempt-1"
inner.lifecycle_state = str(JobState(state))
inner.source_table_version = 7
inner.execution_epoch = 3
inner.refresh = AsyncMock(side_effect=observe)
job, call = job_snapshot(inner)
assert job.state() is None
assert job.job_id() == "operation-1"
assert job.lifecycle_state() is None
assert job.job_type() is None
assert job.creation_ms() is None
assert job.spec() is None
@@ -94,6 +108,14 @@ async def test_job_checkout_latest_refreshes_the_complete_snapshot(
assert job.spec() is spec
assert job.result() is result
assert job.failure() is failure
assert job.id() == "operation-1"
assert job.job_id() == "attempt-2"
assert job.operation_id() == "operation-1"
assert job.attempt() == 2
assert job.retry_of() == "attempt-1"
assert job.lifecycle_state() == JobState(state)
assert job.source_table_version() == 7
assert job.execution_epoch() == 3
inner.refresh.assert_awaited_once_with()
inner.status.assert_not_called()
@@ -151,6 +173,38 @@ async def test_job_checkout_latest_for_completed_local_jobs(job_snapshot):
assert Job(None).checkout_latest() is None
@pytest.mark.parametrize("sync", [False, True])
def test_local_jobs_retain_identity_and_typed_state(sync):
job = AsyncJob(None)
if sync:
job = Job(job)
assert job.job_id() == job.operation_id()
assert job.job_id() == job.job_id()
assert job.attempt() == 1
assert job.retry_of() is None
assert job.lifecycle_state() is JobState.SUCCEEDED
def test_unknown_job_state_is_preserved_without_becoming_success():
state = JobState("future_publication_state")
assert state.value == "future_publication_state"
assert str(state) == "future_publication_state"
assert not state.is_terminal
assert not state.is_success
@pytest.mark.asyncio
async def test_history_follows_page_tokens():
first = pa.table({"event_seq": [2, 1]}).replace_schema_metadata(
{b"lancedb.job_coordinator.page_token": b"next"}
)
last = pa.table({"event_seq": [0]})
inner = SimpleNamespace(events=AsyncMock(side_effect=[first, last]))
pages = [page async for page in AsyncJob(inner).history(limit=2)]
assert [page["event_seq"].to_pylist() for page in pages] == [[2, 1], [0]]
assert inner.events.call_args_list[1].kwargs["page_token"] == "next"
@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
View File
@@ -9034,3 +9034,47 @@ def test_remote_prewarm_preview_reports_old_server_format_support():
):
table.explain_prewarm_data()
assert len(server.tickets) == 1
@pytest.mark.parametrize("async_table", [False, True])
@pytest.mark.asyncio
async def test_paged_function_errors_retain_history_and_expose_continuation(
async_table,
):
received = []
def handler(request):
length = int(request.headers.get("content-length", 0))
body = json.loads(request.rfile.read(length)) if length else {}
if request.path == "/v1/table/test/describe/":
response = {"version": 8, "schema": {"fields": []}}
else:
assert request.path == "/v1/table/test/errors"
received.append(body)
response = {
"records": [],
"fragments": [],
"truncated": False,
"workflow_version": 1,
"page_token": "next",
}
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(json.dumps(response).encode())
if async_table:
async with mock_lancedb_connection_async(handler) as db:
table = await db.open_table("test")
errors = await table.function_errors(job_id="attempt-1", page_token="")
assert errors.page_token == "next"
with pytest.raises(ValueError, match="current failures"):
await errors.rows()
else:
with mock_lancedb_connection(handler) as db:
table = db.open_table("test")
errors = table.function_errors(job_id="attempt-1", page_token="")
assert errors.page_token == "next"
with pytest.raises(ValueError, match="current failures"):
errors.rows()
assert received == [{"job_id": "attempt-1", "page_token": "", "history": True}]