From fb34b1c7837b525b4ebb27b71800d63efa2026fc Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Tue, 17 Nov 2026 03:26:45 -0800 Subject: [PATCH] feat(functions): add row failure recovery APIs (#5048) Function failures currently require callers to assemble row predicates and manage retry/version/quarantine state themselves. Add exact failed-row retry and Function upgrades through the Rust and Python refresh APIs, plus Python helpers for grouped causes, failing input rows, quarantine, and per-row producing-version metadata. ```python errors = table.function_errors(column="sharpness") errors.summary() errors.rows(columns=["frame_index", "frame"]) table.retry_failed("sharpness", function_version="2").wait() table.quarantine_failed("sharpness", after_attempts=3) table.retry_failed("sharpness", include_quarantined=True).wait() table.function_provenance("sharpness") ``` `upgrade_column(..., recompute="failed" | "all" | "none")` keeps the column available while selecting the intended work. `history=True` reads retained past errors. Capability checks reject these operations on servers that cannot honor the workflow, before any refresh is submitted. Includes synchronous/asynchronous API and older-server compatibility coverage. Formatting applied; local builds and tests were not run. --- docs/src/python/python.md | 10 +- docs/web/management/function-failures.mdx | 133 +++++++- nodejs/src/table.rs | 1 + python/python/lancedb/__init__.py | 11 +- python/python/lancedb/_lancedb.pyi | 35 ++ python/python/lancedb/functions.py | 221 +++++++++++++ python/python/lancedb/remote/table.py | 60 +++- python/python/lancedb/table.py | 370 ++++++++++++++++++++-- python/python/tests/test_remote_db.py | 211 +++++++++++- python/src/table.rs | 115 ++++++- rust/lancedb/src/function.rs | 106 +++++++ rust/lancedb/src/remote/table.rs | 104 ++++++ rust/lancedb/src/table.rs | 105 ++++++ rust/lancedb/src/table/refresh.rs | 85 +++++ 14 files changed, 1540 insertions(+), 27 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index b64940e39..d3713b634 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -640,7 +640,15 @@ with BlobReader(read_range, len(payload)) as reader: ::: lancedb.functions.RefreshColumnResult -::: lancedb.FunctionErrors +::: lancedb.functions.FunctionErrorGroup + +::: lancedb.functions.FunctionProvenance + +::: lancedb.functions.FunctionValueProvenance + +::: lancedb.functions.AsyncFunctionErrors + +::: lancedb.functions.FunctionErrors ::: lancedb.FunctionErrorRecord diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx index 4546129fa..131204382 100644 --- a/docs/web/management/function-failures.mdx +++ b/docs/web/management/function-failures.mdx @@ -10,8 +10,137 @@ availability: A Function refresh can encounter a bad row, fail to initialize a model, lose a worker, or fail while publishing results. These need different remedies. -This guide uses the existing [refresh error policy](/sql/dml/refresh-column#options) -and Python error records; it does not require a new retry or quarantine API. +The native workflow below is draft guidance for an unreleased SDK and a +matching Enterprise server. The recipes that follow it remain available for +older deployments. + +## Draft native workflow: server contract version 1 {#native} + +This section requires the SDK changes in [PR #5048](https://github.com/lancedb/lancedb/pull/5048) +and an Enterprise deployment advertising `workflow_version >= 1` in its +Function error response. No released SDK or Enterprise version is implied by +this draft. The SDK checks this capability before submitting native retry, +upgrade, quarantine, history or provenance requests, and rejects unsupported +servers before changing the column. + +New Function refreshes default to `error_policy="skip"` with a 5% failed-row +ceiling. Successful outputs are published before a threshold failure is +reported; failed rows and grouped causes remain available. Explicit `fail` +still stops on a row error. Initialization, infrastructure and publication +failures remain job failures. External effects can repeat during recovery. + +Read current unresolved failures, group their causes and inspect their inputs: + +```python +errors = table.function_errors(column="embedding") +print(errors.summary()) +inputs = errors.rows(columns=["text"]) +print(inputs) # Includes a __function_error struct for each failed column. + +history = table.function_errors(column="embedding", history=True) +print(history.records) # Retained attempts, including repaired failures. +``` + +The default listing deduplicates failures by row and Function column, retaining +attempt counts and first/last failure times. `summary()` and `rows()` refuse +incomplete selections; narrow a truncated request before inspecting it. +Historical records cannot be joined to current inputs through `rows()`. +Stable row IDs survive compaction; older physical-only records are rejected +for exact retry if their fragments have been rewritten. + +Select retry rows on the server, optionally by exception class or job: + +```python +retry_job = table.retry_failed("embedding", error_type="ValueError") +retry_job.wait() +``` + +Upgrade the existing Function binding and choose which values to recompute: + +```python +upgrade_job = table.upgrade_column("embedding", version="2", recompute="failed") +upgrade_job.wait() +provenance = table.function_provenance("embedding") +if not provenance.truncated: + print(provenance.records) +``` + +The immutable target version must already exist for the same Function. +`recompute="failed"` selects current failures; `"all"` recomputes all live rows; +`"none"` changes the binding while preserving existing values. The default is +`"all"`. New and changed inputs use the new version. Producing-version records +identify successful values written by this workflow; older values without +recorded provenance do not acquire an invented producing version. + +Quarantine failures that need input repair, then explicitly include them when +they are ready to retry: + +```python +table.quarantine_failed("embedding", after_attempts=3) +retry_job = table.retry_failed("embedding", include_quarantined=True) +retry_job.wait() +``` + +Ordinary and automatic refreshes exclude quarantined rows, including during +an `"all"` upgrade. Explicit inclusion releases quarantine before the retry. +Async tables expose the same operations with `await`; `function_errors()` +returns `AsyncFunctionErrors`, and its `rows()` method is also awaited. +These native recovery APIs are available in Python and Rust. TypeScript does +not yet expose them; its SDK support is tracked as a separate follow-up. + +The equivalent Rust operations use explicit request options: + +```rust +use lancedb::{Table, table::RefreshColumnOptions}; +use lancedb::function::{ + FunctionProvenanceOptions, FunctionQuarantineOptions, FunctionRecompute, +}; + +async fn recover(table: &Table) -> lancedb::Result<()> { + let retry = table.refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default() + .retry_errors(true) + .retry_error_type("ValueError"), + ).await?; + retry.wait().await?; + + let upgrade = table.refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default().upgrade("2", FunctionRecompute::Failed), + ).await?; + upgrade.wait().await?; + + table.quarantine_function_errors( + "embedding", + FunctionQuarantineOptions { + after_attempts: Some(3), + ..Default::default() + }, + ).await?; + let provenance = table.function_provenance( + "embedding", FunctionProvenanceOptions::default(), + ).await?; + if !provenance.truncated { + println!("{:?}", provenance.records); + } + Ok(()) +} +``` + +Set `include_quarantined(true)` on a Rust failed-row retry to explicitly +release quarantine before recomputing those failures. + +The native contract also applies skip/5% defaults to newly created materialized +views, with errors identified by Function invocation and source input. Column +retry and upgrade helpers apply to Function columns; use the materialized-view +refresh reference for view refresh options. + +## Older-deployment recipes {#older-deployments} + +The following sections describe deployments without workflow version 1. Their +legacy defaults, error-history semantics and application-managed quarantine +remain unchanged. ## Choose a row-error policy {#policy} diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index a0a220e24..c9e03b2a3 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -581,6 +581,7 @@ impl Table { }) .transpose()?; let request = lancedb::function::FunctionErrorsRequest { + history: false, job_id: options.job_id, column: options.column, limit, diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index acf25d35c..129a4b1c5 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -29,7 +29,6 @@ from ._lancedb import ( ) from ._lancedb import FunctionErrorFragment as FunctionErrorFragment from ._lancedb import FunctionErrorRecord as FunctionErrorRecord -from ._lancedb import FunctionErrors as FunctionErrors from ._lancedb import GpuClass as GpuClass from ._lancedb import RTEWriteSpec from ._lancedb import tokenize as _tokenize @@ -46,6 +45,11 @@ from .sql import AsyncQuery as AsyncSqlQuery from .sql import Query as SqlQuery from .sql import QueryDescription from .functions import ( + FunctionErrors as FunctionErrors, + AsyncFunctionErrors as AsyncFunctionErrors, + FunctionErrorGroup as FunctionErrorGroup, + FunctionProvenance as FunctionProvenance, + FunctionValueProvenance as FunctionValueProvenance, AssignmentMapping as AssignmentMapping, FunctionArtifactRequest as FunctionArtifactRequest, FunctionApplication as FunctionApplication, @@ -678,6 +682,11 @@ __all__ = [ "FunctionColumnLastRefreshJob", "FunctionColumnStatus", "FunctionColumnVersionStatus", + "FunctionErrors", + "AsyncFunctionErrors", + "FunctionErrorGroup", + "FunctionProvenance", + "FunctionValueProvenance", "col", "Expr", "func", diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 2273e8628..19454790a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -694,6 +694,12 @@ class Table: init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> RefreshColumnResult: ... async def refresh_column_async( self, @@ -716,13 +722,36 @@ class Table: init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> Job: ... async def function_errors( self, job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, + history: bool = False, ) -> FunctionErrors: ... + async def quarantine_function_errors( + self, + column: str, + *, + quarantined: bool = True, + job_id: Optional[str] = None, + error_type: Optional[str] = None, + after_attempts: Optional[int] = None, + ) -> int: ... + async def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> str: ... async def column_statuses( self, column: Optional[str] = None ) -> list[FunctionColumnStatus]: ... @@ -1128,6 +1157,10 @@ class RefreshColumnResult: version: int class FunctionErrorRecord: + first_seen_at_millis: Optional[int] + last_seen_at_millis: Optional[int] + quarantined: bool + input: Optional[str] attempts: Optional[int] job_id: str fragment_id: int @@ -1151,6 +1184,8 @@ class FunctionErrorFragment: rows_recorded: int class FunctionErrors: + workflow_version: Optional[int] + error_groups_json: str records: list[FunctionErrorRecord] fragments: list[FunctionErrorFragment] truncated: bool diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 9178d5194..5ea45a6a6 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1132,6 +1132,220 @@ class FunctionBinding(_RemoteValue): return reader.read_all().to_pylist()[0] +class FunctionErrorGroup(_RemoteValue): + """A grouped cause among returned Function failures.""" + + column: str + error_type: str + error_message: str + rows_failed: _UInt64 + + +class FunctionValueProvenance(_RemoteValue): + """The Function version and job that produced one stored value.""" + + column: str + job_id: str + function_name: str + function_version: str + row_id: Optional[_UInt64] = None + row_address: Optional[_UInt64] = None + source_version: _UInt64 + published_version: _UInt64 + + +class FunctionProvenance(_RemoteValue): + """A bounded per-row producing-version listing for a table snapshot.""" + + records: tuple[FunctionValueProvenance, ...] + truncated: bool = False + + +class _FunctionErrors: + """Current Function failures, with grouped causes and source-row lookup. + + Check ``truncated`` and ``fragments`` before treating a listing as complete. + ``history=True`` on ``table.function_errors`` returns retained past records. + """ + + def __init__(self, raw: Any, table: Any, *, history: bool = False): + self._raw = raw + self._table = table + self._history = history + self.records = raw.records + self.fragments = raw.fragments + self.truncated = raw.truncated + + def __repr__(self) -> str: + return repr(self._raw) + + def as_sync(self, table: Any) -> FunctionErrors: + return FunctionErrors(self._raw, table, history=self._history) + + def summary(self) -> list[FunctionErrorGroup]: + """Group returned failures by column, exception class, and message. + + Raises when records are incomplete, so sampled counts cannot be mistaken + for totals. Narrow the request by column or job, or raise its limit. + """ + if (getattr(self._raw, "workflow_version", None) or 0) < 1: + raise NotImplementedError( + "The server does not support the current Function failure workflow" + ) + if ( + self.truncated + or self.fragments + or any( + record.row_offset is None and record.input is None + for record in self.records + ) + ): + raise ValueError( + "Function errors are incomplete; narrow the request or raise limit" + ) + groups: dict[tuple[str, str, str], int] = {} + for record in self.records: + if record.row_offset is None and record.input is None: + continue + message = record.error_message + if record.input is not None: + message = message.split("\nSource input: ", 1)[0].split( + "\nFunction input ", 1 + )[0] + key = (record.column, record.error_type, message) + groups[key] = groups.get(key, 0) + 1 + return [ + FunctionErrorGroup( + column=column, error_type=kind, error_message=message, rows_failed=count + ) + for (column, kind, message), count in sorted(groups.items()) + ] + + def _identities(self) -> dict[tuple[str, int], list[Any]]: + if (getattr(self._raw, "workflow_version", None) or 0) < 1: + raise NotImplementedError( + "The server does not support the current Function failure workflow" + ) + if self._history: + raise ValueError( + "Source-row lookup requires current failures; " + "read retained history through records" + ) + if self.truncated or self.fragments: + raise ValueError( + "Function errors are incomplete; narrow the request or raise limit" + ) + result = {} + for record in self.records: + if record.input is not None or record.row_offset is None: + raise ValueError( + "This error names a Function invocation; " + "inspect its input source identities" + ) + identity = ( + record.row_id if record.row_id is not None else record.row_address + ) + if identity is None: + raise ValueError("This error has no source row identity") + key = ("_rowid" if record.row_id is not None else "_rowaddr", identity) + result.setdefault(key, []).append(record) + return result + + def _predicate(self, identities: dict[tuple[str, int], list[Any]]) -> str: + clauses = [] + for field in ("_rowid", "_rowaddr"): + selected = [identity for (kind, identity) in identities if kind == field] + if selected: + clauses.append(field + " IN (" + ",".join(map(str, selected)) + ")") + return " OR ".join(clauses) if clauses else "false" + + def _join_rows( + self, rows: pa.Table, identities: dict[tuple[str, int], list[Any]] + ) -> pa.Table: + matches = [] + indices = [] + found = set() + for index, (row_id, address) in enumerate( + zip(rows.column("_rowid").to_pylist(), rows.column("_rowaddr").to_pylist()) + ): + for key in (("_rowid", row_id), ("_rowaddr", address)): + for record in identities.get(key, []): + found.add(key) + indices.append(index) + matches.append(record) + if found != identities.keys(): + raise ValueError( + "Some failed inputs are no longer addressable in this snapshot; " + "refresh the error listing or use a historical snapshot" + ) + rows = rows.take(pa.array(indices, type=pa.int64())) + fields = [ + "column", + "error_type", + "error_message", + "attempts", + "function_version", + "job_id", + "first_seen_at_millis", + "last_seen_at_millis", + "quarantined", + ] + arrays = [ + pa.array([getattr(record, field) for record in matches]) for field in fields + ] + if "__function_error" in rows.column_names: + raise ValueError("Source columns already contain __function_error") + return rows.append_column( + "__function_error", pa.StructArray.from_arrays(arrays, names=fields) + ) + + +class FunctionErrors(_FunctionErrors): + """Current failures with grouped causes and synchronous source-row lookup.""" + + def rows(self, columns: Optional[list[str]] = None) -> pa.Table: + """Return current failing inputs with a ``__function_error`` struct. + + Row IDs come from the error records. The server joins stable identities + correctly after compaction; callers need no physical-address arithmetic. + """ + identities = self._identities() + predicate = self._predicate(identities) + query = ( + self._table.search() + .where(predicate) + .with_row_id(True) + .with_row_address() + .limit(max(1, len(identities))) + ) + selected = list(self._table.schema.names if columns is None else columns) + selected.extend(name for name in ("_rowid", "_rowaddr") if name not in selected) + query = query.select(selected) + return self._join_rows(query.to_arrow(), identities) + + +class AsyncFunctionErrors(_FunctionErrors): + """Current Function failures returned by an asynchronous table.""" + + async def rows(self, columns: Optional[list[str]] = None) -> pa.Table: + """Return current failing inputs with their ``__function_error`` metadata.""" + identities = self._identities() + predicate = self._predicate(identities) + query = ( + self._table.query() + .where(predicate) + .with_row_id() + .with_row_address() + .limit(max(1, len(identities))) + ) + selected = list( + (await self._table.schema()).names if columns is None else columns + ) + selected.extend(name for name in ("_rowid", "_rowaddr") if name not in selected) + query = query.select(selected) + return self._join_rows(await query.to_arrow(), identities) + + class RefreshColumnResult(_RemoteValue): """Terminal result of an expression-backed or Function-backed refresh Job. @@ -1169,6 +1383,8 @@ class RefreshColumnResult(_RemoteValue): """Exact table version the refresh read.""" published_version: Optional[_UInt64] = None + error_groups: tuple[FunctionErrorGroup, ...] = () + error_groups_truncated: bool = False """Table version made visible by the refresh, when one was published.""" @property @@ -3487,6 +3703,11 @@ __all__ = [ "ResolvedEnvironmentProvenance", "ResolvedPackage", "RefreshColumnResult", + "FunctionErrors", + "AsyncFunctionErrors", + "FunctionErrorGroup", + "FunctionProvenance", + "FunctionValueProvenance", "FunctionDefinition", ] diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 2d068536e..19e7ff454 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -50,6 +50,7 @@ from lancedb.index import ( ) from lancedb.job import Job from lancedb.functions import ( + FunctionProvenance, FunctionApplication, FunctionRetryPolicy, RefreshColumnResult, @@ -1185,6 +1186,12 @@ class RemoteTable(Table): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ): return LOOP.run( self._table.refresh_column( @@ -1206,6 +1213,12 @@ class RemoteTable(Table): init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ) ) @@ -1230,6 +1243,12 @@ class RemoteTable(Table): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> Job[RefreshColumnResult]: return Job( LOOP.run( @@ -1252,6 +1271,12 @@ class RemoteTable(Table): init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ) ) ) @@ -1261,9 +1286,42 @@ class RemoteTable(Table): job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, + history: bool = False, ): return LOOP.run( - self._table.function_errors(job_id=job_id, column=column, limit=limit) + self._table.function_errors( + job_id=job_id, column=column, limit=limit, history=history + ) + ).as_sync(self) + + def quarantine_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + after_attempts: Optional[int] = None, + quarantined: bool = True, + ) -> int: + return LOOP.run( + self._table.quarantine_failed( + column, + error_type=error_type, + job_id=job_id, + after_attempts=after_attempts, + quarantined=quarantined, + ) + ) + + def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> FunctionProvenance: + return LOOP.run( + self._table.function_provenance(column, limit=limit, version=version) ) def column_statuses( diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 7f378a34c..8d996d32e 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -84,6 +84,9 @@ from .index import ( ) from .expr import Expr from .functions import ( + FunctionErrors, + AsyncFunctionErrors, + FunctionProvenance, FunctionRetryPolicy, FunctionApplication, RefreshColumnResult as RefreshColumnJobResult, @@ -300,7 +303,6 @@ if TYPE_CHECKING: CompactionStats, Tag, AddColumnsResult, - FunctionErrors, RefreshColumnResult, AddResult, AlterColumnsResult, @@ -3290,6 +3292,12 @@ class Table(ABC): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> "RefreshColumnResult": """ Fill the rows of a computed column that hold no value yet. @@ -3365,6 +3373,9 @@ class Table(ABC): error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + Workflow version 1 servers default to skip with a 5% failure ceiling + and publish successful output before reporting a threshold failure. + Older deployments retain their existing defaults. max_failed_fraction: float, optional Under a skip policy, fail the job once more than this share of rows (0 to 1) has failed. LanceDB Enterprise only. @@ -3382,6 +3393,23 @@ class Table(ABC): max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. + retry_errors: bool, default False + Select current failed rows on the server. Cannot be combined with + ``where``. Requires Enterprise workflow version 1 or later. + retry_job_id: str, optional + Restrict a failed-row retry to errors recorded by this job. + retry_error_type: str, optional + Restrict a failed-row retry to this exception class. + include_quarantined: bool, default False + Explicitly release and include quarantined rows in a failed-row retry. + function_version: str, optional + Atomically rebind this column's Function to the specified immutable + version. Requires Enterprise workflow version 1 or later. + recompute: {"failed", "all", "none"}, optional + Which rows to recompute during an upgrade. Requires + ``function_version``; the default is ``all``. ``failed`` selects + current failures, and ``none`` preserves existing values. Quarantined + rows stay excluded unless explicitly included in a failed-row retry. Returns ------- @@ -3412,6 +3440,12 @@ class Table(ABC): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> Job[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job @@ -3486,6 +3520,9 @@ class Table(ABC): error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + Workflow version 1 servers default to skip with a 5% failure ceiling + and publish successful output before reporting a threshold failure. + Older deployments retain their existing defaults. max_failed_fraction: float, optional Under a skip policy, fail the job once more than this share of rows (0 to 1) has failed. LanceDB Enterprise only. @@ -3503,6 +3540,23 @@ class Table(ABC): max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. + retry_errors: bool, default False + Select current failed rows on the server. Cannot be combined with + ``where``. Requires Enterprise workflow version 1 or later. + retry_job_id: str, optional + Restrict a failed-row retry to errors recorded by this job. + retry_error_type: str, optional + Restrict a failed-row retry to this exception class. + include_quarantined: bool, default False + Explicitly release and include quarantined rows in a failed-row retry. + function_version: str, optional + Atomically rebind this column's Function to the specified immutable + version. Requires Enterprise workflow version 1 or later. + recompute: {"failed", "all", "none"}, optional + Which rows to recompute during an upgrade. Requires + ``function_version``; the default is ``all``. ``failed`` selects + current failures, and ``none`` preserves existing values. Quarantined + rows stay excluded unless explicitly included in a failed-row retry. Returns ------- @@ -3525,22 +3579,104 @@ class Table(ABC): 'finished' """ + def retry_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + **options: Any, + ) -> Job[RefreshColumnJobResult]: + """Start a job for exactly the current failed rows. + + Stable row identities survive compaction. Set ``function_version`` to + upgrade and retry failures atomically. ``include_quarantined=True`` + explicitly releases quarantined rows before retrying them. + + >>> job = table.retry_failed("sharpness") # doctest: +SKIP + >>> result = job.wait() # doctest: +SKIP + """ + return self.refresh_column_async( + column, + retry_errors=True, + retry_error_type=error_type, + retry_job_id=job_id, + include_quarantined=include_quarantined, + function_version=function_version, + recompute="failed" if function_version is not None else None, + **options, + ) + + def upgrade_column( + self, + column: str, + *, + version: str, + recompute: Literal["failed", "all", "none"] = "all", + **options: Any, + ) -> Job[RefreshColumnJobResult]: + """Upgrade a Function binding while keeping its columns available. + + ``failed`` recomputes current failures, ``all`` recomputes all live rows, + and ``none`` preserves existing values. New and changed rows use the new + version; ``function_provenance`` identifies each value's producing version. + """ + return self.refresh_column_async( + column, function_version=version, recompute=recompute, **options + ) + + def quarantine_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + after_attempts: Optional[int] = None, + quarantined: bool = True, + ) -> int: + """Quarantine current failures, or release them with ``quarantined=False``. + + Normal and automatic refreshes skip quarantined rows. ``after_attempts`` + restricts the selection to rows with at least that many failed calls. + Returns the number of selected rows. LanceDB Enterprise only. + """ + raise NotImplementedError("Function quarantine requires LanceDB Enterprise") + + def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> FunctionProvenance: + """Read each returned row's producing Function version and job. + + ``version`` selects a table snapshot. Check ``truncated`` before treating + the returned records as a complete snapshot. LanceDB Enterprise only. + """ + raise NotImplementedError("Function provenance requires LanceDB Enterprise") + @abstractmethod def function_errors( self, job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, + history: bool = False, ) -> "FunctionErrors": """ The per-row errors Function refreshes recorded on this table. - A refresh running under a skip policy records each row it skipped - with the input that failed and the error. This lists those records, - newest job first, plus a summary for any fragment whose per-row - detail was capped. LanceDB Enterprise only; reading errors - needs read access to the table, since a message carries the value - that failed. + A refresh running under a skip policy records each row it skipped. + On servers advertising workflow version 1 or later, the default lists + current unresolved failures, deduplicated by row and Function column, + with attempt counts and first/last failure times. ``history=True`` + returns retained observations, including repaired failures. Older servers + keep their legacy listing behavior and reject explicit history requests. + LanceDB Enterprise only; reading errors needs table read access because + messages can include the input that failed. Parameters ---------- @@ -3550,6 +3686,10 @@ class Table(ABC): Only errors on this column. limit: int, optional At most this many records (server default 10000, cap 100000). + history: bool, default False + 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. Returns ------- @@ -5706,6 +5846,12 @@ class LanceTable(Table): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> "RefreshColumnResult": """Fill a computed column's unfilled rows and recompute those whose inputs changed. See @@ -5730,6 +5876,12 @@ class LanceTable(Table): init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ) ) @@ -5754,6 +5906,12 @@ class LanceTable(Table): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> Job[RefreshColumnJobResult]: """Fill a computed column's unfilled rows and recompute those whose inputs changed, returning a handle to the refresh job. See @@ -5780,6 +5938,12 @@ class LanceTable(Table): init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ) ) ) @@ -5789,11 +5953,44 @@ class LanceTable(Table): job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, + history: bool = False, ) -> "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) + self._table.function_errors( + job_id=job_id, column=column, limit=limit, history=history + ) + ).as_sync(self) + + def quarantine_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + after_attempts: Optional[int] = None, + quarantined: bool = True, + ) -> int: + return LOOP.run( + self._table.quarantine_failed( + column, + error_type=error_type, + job_id=job_id, + after_attempts=after_attempts, + quarantined=quarantined, + ) + ) + + def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> FunctionProvenance: + return LOOP.run( + self._table.function_provenance(column, limit=limit, version=version) ) def column_statuses( @@ -8221,6 +8418,12 @@ class AsyncTable: init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> RefreshColumnResult: """ Fill the rows of a computed column that hold no value yet. @@ -8296,6 +8499,9 @@ class AsyncTable: error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + Workflow version 1 servers default to skip with a 5% failure ceiling + and publish successful output before reporting a threshold failure. + Older deployments retain their existing defaults. max_failed_fraction: float, optional Under a skip policy, fail the job once more than this share of rows (0 to 1) has failed. LanceDB Enterprise only. @@ -8313,6 +8519,23 @@ class AsyncTable: max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. + retry_errors: bool, default False + Select current failed rows on the server. Cannot be combined with + ``where``. Requires Enterprise workflow version 1 or later. + retry_job_id: str, optional + Restrict a failed-row retry to errors recorded by this job. + retry_error_type: str, optional + Restrict a failed-row retry to this exception class. + include_quarantined: bool, default False + Explicitly release and include quarantined rows in a failed-row retry. + function_version: str, optional + Atomically rebind this column's Function to the specified immutable + version. Requires Enterprise workflow version 1 or later. + recompute: {"failed", "all", "none"}, optional + Which rows to recompute during an upgrade. Requires + ``function_version``; the default is ``all``. ``failed`` selects + current failures, and ``none`` preserves existing values. Quarantined + rows stay excluded unless explicitly included in a failed-row retry. Returns ------- @@ -8340,6 +8563,77 @@ class AsyncTable: init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, + ) + + async def retry_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + **options: Any, + ) -> AsyncJob[RefreshColumnJobResult]: + """Start an exact failed-row retry; see ``Table.retry_failed``.""" + return await self.refresh_column_async( + column, + retry_errors=True, + retry_error_type=error_type, + retry_job_id=job_id, + include_quarantined=include_quarantined, + function_version=function_version, + recompute="failed" if function_version is not None else None, + **options, + ) + + async def upgrade_column( + self, + column: str, + *, + version: str, + recompute: Literal["failed", "all", "none"] = "all", + **options: Any, + ) -> AsyncJob[RefreshColumnJobResult]: + """Upgrade the Function and choose which rows to recompute.""" + return await self.refresh_column_async( + column, function_version=version, recompute=recompute, **options + ) + + async def quarantine_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + after_attempts: Optional[int] = None, + quarantined: bool = True, + ) -> int: + """Quarantine current failures or release them for later refreshes.""" + return await self._inner.quarantine_function_errors( + column, + quarantined=quarantined, + error_type=error_type, + job_id=job_id, + after_attempts=after_attempts, + ) + + async def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> FunctionProvenance: + """Read per-row producing versions at a table snapshot.""" + return FunctionProvenance.from_json( + await self._inner.function_provenance(column, limit=limit, version=version) ) async def function_errors( @@ -8347,16 +8641,19 @@ class AsyncTable: job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, - ) -> "FunctionErrors": + history: bool = False, + ) -> "AsyncFunctionErrors": """ The per-row errors Function refreshes recorded on this table. - A refresh running under a skip policy records each row it skipped - with the input that failed and the error. This lists those records, - newest job first, plus a summary for any fragment whose per-row - detail was capped. LanceDB Enterprise only; reading errors - needs read access to the table, since a message carries the value - that failed. + A refresh running under a skip policy records each row it skipped. + On servers advertising workflow version 1 or later, the default lists + current unresolved failures, deduplicated by row and Function column, + with attempt counts and first/last failure times. ``history=True`` + returns retained observations, including repaired failures. Older servers + keep their legacy listing behavior and reject explicit history requests. + LanceDB Enterprise only; reading errors needs table read access because + messages can include the input that failed. Parameters ---------- @@ -8366,10 +8663,14 @@ class AsyncTable: Only errors on this column. limit: int, optional At most this many records (server default 10000, cap 100000). + history: bool, default False + 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. Returns ------- - FunctionErrors + AsyncFunctionErrors ``records``, ``fragments`` and ``truncated``, the last saying whether the listing stopped at its limit. @@ -8427,9 +8728,10 @@ class AsyncTable: >>> if errors.truncated: # doctest: +SKIP ... print("listing stopped at the limit") """ - return await self._inner.function_errors( - job_id=job_id, column=column, limit=limit + raw = await self._inner.function_errors( + job_id=job_id, column=column, limit=limit, history=history ) + return AsyncFunctionErrors(raw, self, history=history) async def column_statuses( self, column: Optional[str] = None @@ -8478,6 +8780,12 @@ class AsyncTable: init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> AsyncJob[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job @@ -8552,6 +8860,9 @@ class AsyncTable: error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + Workflow version 1 servers default to skip with a 5% failure ceiling + and publish successful output before reporting a threshold failure. + Older deployments retain their existing defaults. max_failed_fraction: float, optional Under a skip policy, fail the job once more than this share of rows (0 to 1) has failed. LanceDB Enterprise only. @@ -8569,6 +8880,23 @@ class AsyncTable: max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. + retry_errors: bool, default False + Select current failed rows on the server. Cannot be combined with + ``where``. Requires Enterprise workflow version 1 or later. + retry_job_id: str, optional + Restrict a failed-row retry to errors recorded by this job. + retry_error_type: str, optional + Restrict a failed-row retry to this exception class. + include_quarantined: bool, default False + Explicitly release and include quarantined rows in a failed-row retry. + function_version: str, optional + Atomically rebind this column's Function to the specified immutable + version. Requires Enterprise workflow version 1 or later. + recompute: {"failed", "all", "none"}, optional + Which rows to recompute during an upgrade. Requires + ``function_version``; the default is ``all``. ``failed`` selects + current failures, and ``none`` preserves existing values. Quarantined + rows stay excluded unless explicitly included in a failed-row retry. Returns ------- @@ -8613,6 +8941,12 @@ class AsyncTable: init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ), RefreshColumnJobResult.from_json, ) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 587e2d587..2cacc4716 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -21,6 +21,7 @@ import threading import time from urllib.parse import parse_qs, urlparse from unittest.mock import MagicMock, patch +from types import SimpleNamespace import uuid import warnings from packaging.version import Version @@ -2382,7 +2383,7 @@ async def test_remote_refresh_async_returns_typed_terminal_result( result = job.wait(timeout=timedelta(seconds=30)) assert isinstance(result, lancedb.RefreshColumnResult) - assert result.model_dump() == terminal_result + assert result.model_dump(exclude_defaults=True) == terminal_result assert result.rows_filled == 12 assert result.version == 8 @@ -7845,3 +7846,211 @@ def test_remote_fts_and_rejects_legacy_server(): with query_test_table(handler, vector_columns={}) as table: with pytest.raises(NotImplementedError, match="server version 0.3.0"): table.search("gripper closed", query_type="fts", operator="AND").to_list() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("async_table", [False, True]) +async def test_function_failure_workflow_uses_exact_retry_and_upgrade_apis(async_table): + received = [] + result = { + "rows_assigned": 1000, + "rows_failed": 100, + "rows_remaining": 0, + "source_version": 7, + "published_version": 8, + "error_groups": [ + { + "column": "derived", + "error_type": "RowTimeoutError", + "error_message": "timeout", + "rows_failed": 100, + } + ], + "error_groups_truncated": False, + } + + def handler(request): + length = int(request.headers.get("Content-Length", 0)) + body = json.loads(request.rfile.read(length)) if length else {} + received.append((request.path, body)) + status = 200 + if request.path == "/v1/table/test/describe/": + response = {"version": 8, "schema": {"fields": []}} + elif request.path == "/v1/table/test/backfill_column": + status = 202 + response = {"job_id": "refresh-1"} + elif request.path == "/v1/jobs/describe": + response = { + "job_id": "refresh-1", + "job_type": "function_refresh", + "job_state": "DONE", + "result": result, + } + elif request.path == "/v1/table/test/errors/quarantine": + response = {"rows_affected": 100} + elif request.path == "/v1/table/test/function_provenance": + response = { + "records": [ + { + "column": "derived", + "job_id": "refresh-1", + "function_name": "check", + "function_version": "2", + "row_id": 42, + "source_version": 7, + "published_version": 8, + } + ], + "truncated": False, + } + elif request.path == "/v1/table/test/errors": + response = { + "records": [], + "fragments": [], + "truncated": False, + "workflow_version": 1, + } + else: + status = 404 + response = {} + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + retry_options = dict( + error_type="ValueError", + job_id="first", + include_quarantined=True, + function_version="2", + max_failed_fraction=1.0, + ) + if async_table: + async with mock_lancedb_connection_async(handler) as db: + table = await db.open_table("test") + job = await table.retry_failed("derived", **retry_options) + terminal = await job.wait() + await table.upgrade_column("derived", version="3", recompute="none") + affected = await table.quarantine_failed("derived", after_attempts=3) + provenance = await table.function_provenance("derived") + errors = await table.function_errors(column="derived", history=True) + else: + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + terminal = table.retry_failed("derived", **retry_options).wait() + table.upgrade_column("derived", version="3", recompute="none") + affected = table.quarantine_failed("derived", after_attempts=3) + provenance = table.function_provenance("derived") + errors = table.function_errors(column="derived", history=True) + + refreshes = [body for path, body in received if path.endswith("backfill_column")] + assert refreshes == [ + { + "column": "derived", + "retry_errors": True, + "retry_job_id": "first", + "retry_error_type": "ValueError", + "include_quarantined": True, + "function_version": "2", + "recompute": "failed", + "max_failed_fraction": 1.0, + }, + {"column": "derived", "function_version": "3", "recompute": "none"}, + ] + assert terminal.rows_assigned == 1000 + assert terminal.error_groups[0].rows_failed == 100 + assert affected == 100 + assert provenance.records[0].function_version == "2" + assert provenance.records[0].row_id == 42 + assert errors.summary() == [] + assert ("/v1/table/test/errors", {"column": "derived", "history": True}) in received + + +def test_function_error_rows_returns_all_inputs_and_preserves_multiple_column_errors( + tmp_path, +): + db = lancedb.connect(tmp_path) + table = db.create_table("inputs", [{"id": index} for index in range(16)]) + inputs = table.search().select(["id", "_rowid", "_rowaddr"]).limit(16).to_arrow() + records = [ + SimpleNamespace( + column="first", + row_id=row_id, + row_address=999999, + row_offset=0, + input=None, + error_type="ValueError", + error_message="corrupt", + attempts=3, + function_version="1", + job_id="first", + first_seen_at_millis=100, + last_seen_at_millis=200, + quarantined=False, + ) + for row_id in inputs.column("_rowid").to_pylist() + ] + duplicate = copy.copy(records[0]) + duplicate.column = "second" + records.append(duplicate) + errors = lancedb.FunctionErrors( + SimpleNamespace( + records=records, fragments=[], truncated=False, workflow_version=1 + ), + table, + ) + rows = errors.rows(columns=["id"]) + assert rows.num_rows == 17 + assert sorted(set(rows.column("id").to_pylist())) == list(range(16)) + assert rows.column("__function_error").type.field("column").name == "column" + assert [group.rows_failed for group in errors.summary()] == [16, 1] + legacy = copy.copy(records[0]) + legacy.row_id = None + legacy.row_address = inputs.column("_rowaddr")[0].as_py() + legacy_errors = lancedb.FunctionErrors( + SimpleNamespace( + records=[legacy], fragments=[], truncated=False, workflow_version=1 + ), + table, + ) + assert legacy_errors.rows(columns=["id"]).column("id").to_pylist() == [0] + + incomplete = lancedb.FunctionErrors( + SimpleNamespace( + records=records, fragments=[], truncated=True, workflow_version=1 + ), + table, + ) + with pytest.raises(ValueError, match="incomplete"): + incomplete.rows() + + +def test_exact_function_retries_fail_before_writing_to_older_servers(): + writes = [] + + def handler(request): + length = int(request.headers.get("Content-Length", 0)) + body = request.rfile.read(length) if length else b"" + if request.path == "/v1/table/test/describe/": + response = {"version": 1, "schema": {"fields": []}} + elif request.path == "/v1/table/test/errors": + response = {"records": [], "fragments": [], "truncated": False} + else: + writes.append((request.path, body)) + response = {} + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + with pytest.raises(NotImplementedError, match="server does not support"): + table.retry_failed("derived") + with pytest.raises(NotImplementedError, match="server does not support"): + table.upgrade_column("derived", version="2", recompute="failed") + with pytest.raises(NotImplementedError, match="server does not support"): + table.function_errors(history=True) + with pytest.raises(NotImplementedError, match="server does not support"): + table.function_errors().summary() + assert writes == [] diff --git a/python/src/table.rs b/python/src/table.rs index 25a99e5db..3bc23ec95 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -48,6 +48,12 @@ mod scannable; /// Keyword arguments shared by `refresh_column` and `refresh_column_async`. struct RefreshColumnArgs { + retry_errors: bool, + retry_job_id: Option, + retry_error_type: Option, + include_quarantined: bool, + function_version: Option, + recompute: Option, where_clause: Option, batch_size: Option, max_concurrency: Option, @@ -259,6 +265,12 @@ fn parse_planning_workers( fn refresh_column_options(args: RefreshColumnArgs) -> PyResult { let RefreshColumnArgs { + retry_errors, + retry_job_id, + retry_error_type, + include_quarantined, + function_version, + recompute, where_clause, batch_size, max_concurrency, @@ -278,6 +290,17 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult for RefreshColumnResult { #[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] #[derive(Clone, Debug)] pub struct FunctionErrorRecord { + pub first_seen_at_millis: Option, + pub last_seen_at_millis: Option, + pub quarantined: bool, + pub input: Option, pub attempts: Option, pub job_id: String, pub fragment_id: u64, @@ -915,6 +942,10 @@ impl FunctionErrorRecord { impl From for FunctionErrorRecord { fn from(record: lancedb::function::FunctionErrorRecord) -> Self { Self { + first_seen_at_millis: record.first_seen_at_millis, + last_seen_at_millis: record.last_seen_at_millis, + quarantined: record.quarantined, + input: record.input.map(|value| value.to_string()), attempts: record.attempts, job_id: record.job_id, fragment_id: record.fragment_id, @@ -968,6 +999,8 @@ impl From for FunctionErrorFragment { #[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] #[derive(Clone, Debug)] pub struct FunctionErrors { + pub workflow_version: Option, + pub error_groups_json: String, pub records: Vec, pub fragments: Vec, pub truncated: bool, @@ -988,6 +1021,9 @@ impl FunctionErrors { impl From for FunctionErrors { fn from(errors: lancedb::function::FunctionErrors) -> Self { Self { + workflow_version: errors.workflow_version, + error_groups_json: serde_json::to_string(&errors.error_groups) + .expect("serializable Function error groups"), records: errors.records.into_iter().map(Into::into).collect(), fragments: errors.fragments.into_iter().map(Into::into).collect(), truncated: errors.truncated, @@ -2599,7 +2635,7 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column<'py>( self_: PyRef<'py, Self>, @@ -2621,8 +2657,20 @@ impl Table { init_timeout_seconds: Option, num_workers: Option, max_executor_processes_per_worker: Option, + retry_errors: bool, + retry_job_id: Option, + retry_error_type: Option, + include_quarantined: bool, + function_version: Option, + recompute: Option, ) -> PyResult> { let options = refresh_column_options(RefreshColumnArgs { + retry_errors, + retry_job_id, + retry_error_type, + include_quarantined, + function_version, + recompute, where_clause: r#where, batch_size, max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, @@ -2651,7 +2699,7 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column_async<'py>( self_: PyRef<'py, Self>, @@ -2673,8 +2721,20 @@ impl Table { init_timeout_seconds: Option, num_workers: Option, max_executor_processes_per_worker: Option, + retry_errors: bool, + retry_job_id: Option, + retry_error_type: Option, + include_quarantined: bool, + function_version: Option, + recompute: Option, ) -> PyResult> { let options = refresh_column_options(RefreshColumnArgs { + retry_errors, + retry_job_id, + retry_error_type, + include_quarantined, + function_version, + recompute, where_clause: r#where, batch_size, max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, @@ -2703,18 +2763,20 @@ impl Table { }) } - #[pyo3(signature = (job_id=None, column=None, limit=None))] + #[pyo3(signature = (job_id=None, column=None, limit=None, history=false))] pub fn function_errors( self_: PyRef<'_, Self>, job_id: Option, column: Option, limit: Option, + history: bool, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); let request = lancedb::function::FunctionErrorsRequest { job_id, column, limit, + history, }; future_into_py(self_.py(), async move { let errors = inner.function_errors(request).await.infer_error()?; @@ -2722,6 +2784,53 @@ impl Table { }) } + #[pyo3(signature = (column, *, quarantined=true, job_id=None, error_type=None, after_attempts=None))] + pub fn quarantine_function_errors( + self_: PyRef<'_, Self>, + column: String, + quarantined: bool, + job_id: Option, + error_type: Option, + after_attempts: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + inner + .quarantine_function_errors( + &column, + lancedb::function::FunctionQuarantineOptions { + quarantined, + job_id, + error_type, + after_attempts, + }, + ) + .await + .infer_error() + }) + } + + #[pyo3(signature = (column, *, limit=None, version=None))] + pub fn function_provenance( + self_: PyRef<'_, Self>, + column: String, + limit: Option, + version: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let result = inner + .function_provenance( + &column, + lancedb::function::FunctionProvenanceOptions { limit, version }, + ) + .await + .infer_error()?; + serde_json::to_string(&result) + .map_err(|error| PyRuntimeError::new_err(error.to_string())) + }) + } + #[pyo3(signature = (column=None))] pub fn column_statuses( self_: PyRef<'_, Self>, diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 4e7157c37..e4fff29c5 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -1308,6 +1308,12 @@ pub struct FunctionRefreshPlan { /// Enterprise decodes the same value from the durable job's terminal payload. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RefreshColumnResult { + /// Grouped row failures, when the server reports them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub error_groups: Vec, + /// Whether the grouped counts omit any failures. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub error_groups_truncated: bool, /// Rows assigned a value by this refresh. pub rows_assigned: u64, /// Rows whose computation failed. @@ -1330,6 +1336,8 @@ pub struct RefreshColumnResult { /// covers every refresh of every column. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct FunctionErrorsRequest { + /// Include retained historical errors, including repaired rows. + pub history: bool, /// Only errors recorded by this job. pub job_id: Option, /// Only errors on this column. @@ -1340,6 +1348,11 @@ pub struct FunctionErrorsRequest { } impl FunctionErrorsRequest { + /// Include retained historical records instead of current failures. + pub fn history(mut self, history: bool) -> Self { + self.history = history; + self + } /// A request with no filter. pub fn new() -> Self { Self::default() @@ -1369,6 +1382,18 @@ impl FunctionErrorsRequest { /// read access to the table. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionErrorRecord { + /// Earliest retained failure time for this current failure. + #[serde(default)] + pub first_seen_at_millis: Option, + /// Most recent failure time. + #[serde(default)] + pub last_seen_at_millis: Option, + /// Whether normal refreshes skip this row until explicitly retried. + #[serde(default)] + pub quarantined: bool, + /// Source identities for a materialized-view Function invocation. + #[serde(default)] + pub input: Option, /// Number of user-code calls for this failed invocation, when recorded. #[serde(default, skip_serializing_if = "Option::is_none")] pub attempts: Option, @@ -1429,6 +1454,12 @@ pub struct FunctionErrorFragment { /// A table's per-row Function errors; see [`crate::Table::function_errors`]. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionErrors { + /// Version of the server's current-failure, retry, upgrade, and quarantine contract. + #[serde(default)] + pub workflow_version: Option, + /// Grouped causes for the returned records. Counts are bounded by the listing. + #[serde(default)] + pub error_groups: Vec, /// The recorded rows, newest job first. pub records: Vec, /// Fragments whose detail was capped. @@ -1439,6 +1470,79 @@ pub struct FunctionErrors { pub truncated: bool, } +/// Which existing rows to recompute when upgrading a Function column. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FunctionRecompute { + /// Recompute exactly the current failures. + Failed, + /// Recompute all live rows. + All, + /// Preserve existing values; new and changed rows use the new Function. + None, +} + +/// One cause in a Function failure listing or refresh result. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionErrorGroup { + pub column: String, + pub error_type: String, + pub error_message: String, + pub rows_failed: u64, +} + +/// Selection and state for explicitly quarantining or releasing failed rows. +#[derive(Debug, Clone, Serialize)] +pub struct FunctionQuarantineOptions { + pub quarantined: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub job_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub error_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub after_attempts: Option, +} + +impl Default for FunctionQuarantineOptions { + fn default() -> Self { + Self { + quarantined: true, + job_id: None, + error_type: None, + after_attempts: None, + } + } +} + +/// Which snapshot and how much producing-version metadata to read. +#[derive(Debug, Clone, Default, Serialize)] +pub struct FunctionProvenanceOptions { + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// The Function and job that produced one stored value. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FunctionValueProvenance { + pub job_id: String, + pub column: String, + pub function_name: String, + pub function_version: String, + pub row_id: Option, + pub row_address: Option, + pub source_version: u64, + pub published_version: u64, +} + +/// A bounded set of per-row producing-version records. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FunctionProvenance { + pub records: Vec, + pub truncated: bool, +} + impl RefreshColumnResult { /// Deprecated compatibility alias for `rows_assigned`. pub fn rows_filled(&self) -> u64 { @@ -1465,6 +1569,8 @@ mod refresh_result_tests { source_version: 7, published_version: Some(8), plan, + error_groups: Vec::new(), + error_groups_truncated: false, } } diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index f89be7e69..ad53f8722 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -969,6 +969,33 @@ impl RemoteTable { } } + async fn require_function_failure_workflow(&self) -> Result<()> { + let mut body = serde_json::json!({"limit": 1}); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/errors", self.identifier)) + .json(&body); + let (request_id, response) = self.send(request, true).await?; + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let value: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: error.into(), + request_id, + status_code: None, + })?; + if value + .get("workflow_version") + .and_then(serde_json::Value::as_u64) + .is_some_and(|version| version >= 1) + { + Ok(()) + } else { + Err(Error::NotSupported { message: "The server does not support the Function row-failure workflow; upgrade the server before retrying, upgrading, or quarantining rows".into() }) + } + } + async fn describe(&self) -> Result { self.describe_read_snapshot(self.snapshot_read_state().await) .await @@ -4322,6 +4349,9 @@ impl BaseTable for RemoteTable { ) -> Result> { options.validate()?; self.check_mutable().await?; + if options.retry_errors == Some(true) || options.function_version.is_some() { + self.require_function_failure_workflow().await?; + } let mut body = serde_json::to_value(&options).map_err(|e| Error::Runtime { message: format!("failed to serialize refresh options: {e}"), })?; @@ -4363,7 +4393,13 @@ impl BaseTable for RemoteTable { &self, request: &crate::function::FunctionErrorsRequest, ) -> Result { + if request.history { + self.require_function_failure_workflow().await?; + } let mut body = serde_json::json!({}); + if request.history { + body["history"] = serde_json::json!(true); + } if let Some(job_id) = &request.job_id { body["job_id"] = serde_json::json!(job_id); } @@ -4388,6 +4424,70 @@ impl BaseTable for RemoteTable { }) } + async fn quarantine_function_errors( + &self, + column: &str, + options: &crate::function::FunctionQuarantineOptions, + ) -> Result { + self.require_function_failure_workflow().await?; + self.check_mutable().await?; + if options.after_attempts == Some(0) { + return Err(Error::InvalidInput { + message: "after_attempts must be at least 1".into(), + }); + } + let mut body = serde_json::json!({"column": column, "quarantined": options.quarantined, + "job_id": options.job_id, "error_type": options.error_type, "after_attempts": options.after_attempts}); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/errors/quarantine", self.identifier)) + .json(&body); + let (request_id, response) = self.send(request, false).await?; + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let value: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: error.into(), + request_id: request_id.clone(), + status_code: None, + })?; + value + .get("rows_affected") + .and_then(serde_json::Value::as_u64) + .ok_or_else(|| Error::Http { + source: "Function quarantine response has no rows_affected".into(), + request_id, + status_code: None, + }) + } + + async fn function_provenance( + &self, + column: &str, + options: &crate::function::FunctionProvenanceOptions, + ) -> Result { + self.require_function_failure_workflow().await?; + let mut body = serde_json::json!({"column": column, "limit": options.limit, + "version": match options.version { Some(version) => version, None => self.version().await? }}); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!( + "/v1/table/{}/function_provenance", + self.identifier + )) + .json(&body); + let (request_id, response) = self.send(request, true).await?; + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + serde_json::from_str(&body).map_err(|error| Error::Http { + source: error.into(), + request_id, + status_code: None, + }) + } + async fn function_column_statuses( &self, column: Option<&str>, @@ -12925,6 +13025,10 @@ mod tests { assert_eq!( errors.records, [FunctionErrorRecord { + first_seen_at_millis: None, + last_seen_at_millis: None, + quarantined: false, + input: None, attempts: Some(3), job_id: "j-7".into(), fragment_id: 3, diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 00505220b..f247a386f 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -980,6 +980,28 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { .append_to("per-row Function errors are recorded only in LanceDB Enterprise"), }) } + /// Change the quarantine state of current failed rows. + async fn quarantine_function_errors( + &self, + _column: &str, + _options: &crate::function::FunctionQuarantineOptions, + ) -> Result { + Err(Error::NotSupported { + message: "Function quarantine requires LanceDB Enterprise".into(), + }) + } + + /// Read per-row producing Function versions from LanceDB Enterprise. + async fn function_provenance( + &self, + _column: &str, + _options: &crate::function::FunctionProvenanceOptions, + ) -> Result { + Err(Error::NotSupported { + message: "Function provenance requires LanceDB Enterprise".into(), + }) + } + /// Exact four-way freshness status for Function-backed output columns. /// /// `column` filters to one user-visible output; `None` returns every @@ -2285,6 +2307,30 @@ impl Table { /// refreshes ignore the batch-size and GPU options, and reject resource /// budgets, publication thresholds, and other Enterprise-only options. /// + /// Native failed-row retry and upgrades require Enterprise workflow version + /// 1 or later. The SDK checks the server capability before submitting them. + /// An upgrade targets an existing immutable version of the same Function. + /// + /// ``` + /// # use lancedb::{Table, table::RefreshColumnOptions}; + /// use lancedb::function::FunctionRecompute; + /// # async fn retry_and_upgrade(table: &Table) -> lancedb::Result<()> { + /// let retry = table.refresh_column_async_with_options( + /// "embedding", + /// RefreshColumnOptions::default() + /// .retry_errors(true) + /// .retry_error_type("ValueError"), + /// ).await?; + /// retry.wait().await?; + /// let upgrade = table.refresh_column_async_with_options( + /// "embedding", + /// RefreshColumnOptions::default().upgrade("2", FunctionRecompute::Failed), + /// ).await?; + /// upgrade.wait().await?; + /// # Ok(()) + /// # } + /// ``` + /// /// ``` /// # use lancedb::{Table, table::RefreshColumnOptions}; /// # async fn refresh(table: &Table) -> Result<(), Box> { @@ -2388,6 +2434,9 @@ impl Table { /// A record carries a stable `row_id` when the refresh source used stable /// row IDs. Prefer it over the physical `row_address` for retries: /// compaction and rewrite can change the address. + /// With Enterprise workflow version 1, the default lists current failures; + /// [`FunctionErrorsRequest::history`] selects retained historical attempts. + /// Earlier servers retain their existing default behavior. /// /// LanceDB Enterprise only, and the caller needs read access /// to the table, since a message carries the value that failed. @@ -2413,6 +2462,62 @@ impl Table { self.inner.function_errors(&request).await } + /// Quarantine current failures, or release them with `quarantined=false`. + /// Normal and automatic Function refreshes skip quarantined rows. + /// Requires Enterprise workflow version 1 or later. + /// + /// ``` + /// # use lancedb::Table; + /// use lancedb::function::FunctionQuarantineOptions; + /// # async fn quarantine(table: &Table) -> lancedb::Result<()> { + /// let count = table.quarantine_function_errors( + /// "embedding", + /// FunctionQuarantineOptions { + /// after_attempts: Some(3), + /// ..Default::default() + /// }, + /// ).await?; + /// println!("quarantined {count} rows"); + /// # Ok(()) + /// # } + /// ``` + pub async fn quarantine_function_errors( + &self, + column: &str, + options: crate::function::FunctionQuarantineOptions, + ) -> Result { + self.inner + .quarantine_function_errors(column, &options) + .await + } + + /// Read the producing Function version and job for each returned row. + /// Inspect `truncated` before treating this as a complete snapshot. + /// Requires Enterprise workflow version 1 or later. + /// + /// ``` + /// # use lancedb::Table; + /// use lancedb::function::FunctionProvenanceOptions; + /// # async fn provenance(table: &Table) -> lancedb::Result<()> { + /// let values = table.function_provenance( + /// "embedding", FunctionProvenanceOptions::default(), + /// ).await?; + /// if !values.truncated { + /// for value in values.records { + /// println!("{:?}: {}", value.row_id, value.function_version); + /// } + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn function_provenance( + &self, + column: &str, + options: crate::function::FunctionProvenanceOptions, + ) -> Result { + self.inner.function_provenance(column, &options).await + } + /// Change a column's name, data type, or nullability. /// /// Each alteration must specify at least one of `rename`, `data_type`, or diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index f6bab98f5..78530497f 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -212,6 +212,24 @@ impl FunctionRefreshPlanningConfig { #[derive(Debug, Clone, Default, Serialize)] #[non_exhaustive] pub struct RefreshColumnOptions { + /// Select exactly the current failed rows. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_errors: Option, + /// Restrict retry selection to this job. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_job_id: Option, + /// Restrict retry selection to this exception class. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_error_type: Option, + /// Explicitly release and retry quarantined rows. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub include_quarantined: Option, + /// Upgrade the bound Function to this exact version. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub function_version: Option, + /// Rows recomputed by a Function upgrade. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub recompute: Option, /// Only refresh the rows matching this SQL filter. Enterprise only. #[serde(rename = "where", skip_serializing_if = "Option::is_none")] pub where_clause: Option, @@ -290,6 +308,40 @@ pub struct RefreshColumnOptions { } impl RefreshColumnOptions { + /// Retry only current failures, using the server's row identities. + pub fn retry_errors(mut self, enabled: bool) -> Self { + self.retry_errors = Some(enabled); + self + } + + /// Restrict a failed-row retry to one recorded job. + pub fn retry_job_id(mut self, job_id: impl Into) -> Self { + self.retry_job_id = Some(job_id.into()); + self + } + + /// Restrict a failed-row retry to one exception class. + pub fn retry_error_type(mut self, error_type: impl Into) -> Self { + self.retry_error_type = Some(error_type.into()); + self + } + + /// Release quarantine when explicitly retrying failures. + pub fn include_quarantined(mut self, include: bool) -> Self { + self.include_quarantined = Some(include); + self + } + + /// Change the Function version and select the upgrade's recomputation policy. + pub fn upgrade( + mut self, + version: impl Into, + recompute: crate::function::FunctionRecompute, + ) -> Self { + self.function_version = Some(version.into()); + self.recompute = Some(recompute); + self + } /// Only refresh the rows matching `filter`. pub fn where_clause(mut self, filter: impl Into) -> Self { self.where_clause = Some(filter.into()); @@ -399,6 +451,12 @@ impl RefreshColumnOptions { /// The first set option a LanceDB Embedded refresh cannot honor, if any. pub fn enterprise_only_option(&self) -> Option<&'static str> { [ + ("retry_errors", self.retry_errors.is_some()), + ("retry_job_id", self.retry_job_id.is_some()), + ("retry_error_type", self.retry_error_type.is_some()), + ("include_quarantined", self.include_quarantined.is_some()), + ("function_version", self.function_version.is_some()), + ("recompute", self.recompute.is_some()), ("where", self.where_clause.is_some()), ("retry_policy", self.retry_policy.is_some()), ("error_policy", self.error_policy.is_some()), @@ -426,6 +484,31 @@ impl RefreshColumnOptions { /// Validate client-side constraints before any request is sent. pub fn validate(&self) -> Result<()> { + let retry = self.retry_errors == Some(true); + if (retry || self.function_version.is_some()) && self.where_clause.is_some() { + return Err(Error::InvalidInput { + message: "retry_errors and Function upgrades cannot be combined with where".into(), + }); + } + if !retry + && (self.retry_job_id.is_some() + || self.retry_error_type.is_some() + || self.include_quarantined == Some(true)) + { + return Err(Error::InvalidInput { + message: "retry filters require retry_errors=true".into(), + }); + } + if self + .function_version + .as_ref() + .is_some_and(|version| version.is_empty()) + || (self.recompute.is_some() && self.function_version.is_none()) + { + return Err(Error::InvalidInput { + message: "recompute requires a nonempty function_version".into(), + }); + } if self .where_clause .as_deref() @@ -780,6 +863,8 @@ pub(crate) async fn execute_refresh_column_async( let execution = execute_refresh_column_with_source(&table, &column).await?; table.bump_freshness(); Ok(crate::function::RefreshColumnResult { + error_groups: Vec::new(), + error_groups_truncated: false, rows_assigned: execution.result.rows_filled, rows_failed: 0, rows_remaining: 0,