Files
lancedb/docs/web/management/function-failures.mdx
Xuanwo 4d9fd358f8 feat(nodejs): expose Function failure recovery APIs (#5209)
TypeScript callers can now inspect and recover Function row failures
through the native workflow. `functionErrors()` groups returned failures
and can show retained attempt history. `functionErrorRows()` looks up
current failed inputs using row IDs and physical row addresses
represented as `bigint`. Older deployments can continue to use the
existing error listing.

`retryFailed()` selects the exact failed rows on the server, with
optional error type and job filters. `upgradeColumn()` binds an existing
immutable Function version and can recompute failed rows, all eligible
rows, or no rows. Callers can quarantine and release failures,
explicitly include quarantined rows in a retry, and use
`functionProvenance()` to see which Function version produced a recorded
value.

The native operations reuse the existing Rust workflow v1 capability
checks. The Function failures guide includes TypeScript examples for
inspecting, retrying, upgrading, and quarantining failures.
2026-11-25 23:14:04 +08:00

366 lines
14 KiB
Plaintext

---
title: "Handle Function failures"
sidebarTitle: "Function Failures"
description: "Keep usable outputs, inspect row errors, retry by stable identity and isolate inputs that need attention."
icon: triangle-exclamation
tag: "Early access"
availability:
embedded: unavailable
enterprise: available
---
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.
The native workflow below needs a recent SDK and a matching Enterprise server.
The recipes that follow it remain available for older deployments.
## Native workflow: server contract version 1 {#native}
This section uses the native recovery APIs in Python SDK 0.42.0b19 or later and
in Rust and TypeScript SDKs that expose them. It requires an Enterprise
deployment advertising `workflow_version >= 1` in its Function error response.
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:
<CodeGroup>
```python 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.
```
```typescript TypeScript
const errors = await table.functionErrors({ column: "embedding" });
if (!errors.truncated && errors.fragments.length === 0) {
console.log(errors.errorGroups);
}
const inputs = await table.functionErrorRows({ column: "embedding", columns: ["text"] });
for (const { input, error } of inputs) {
console.log(input.text, error.rowId, error.errorType);
}
const history = await table.functionErrors({ column: "embedding", history: true });
console.log(history.records);
```
</CodeGroup>
The default listing deduplicates failures by row and Function column, retaining
attempt counts and first/last failure times. In Python, `summary()` and `rows()`
require a complete listing. In TypeScript, `errorGroups` counts the returned
records and `functionErrorRows()` requires a complete current listing. Narrow a
truncated request before using its counts as totals. Read historical attempts
through the returned records.
Stable row IDs survive compaction. TypeScript exposes row IDs and physical
addresses as `bigint`. 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:
<CodeGroup>
```python Python
retry_job = table.retry_failed("embedding", error_type="ValueError")
retry_job.wait()
```
```typescript TypeScript
const retryJob = await table.retryFailed("embedding", { errorType: "ValueError" });
const { rowsAssigned, rowsFailed } = await retryJob.wait();
console.log(rowsAssigned, rowsFailed);
```
</CodeGroup>
Upgrade the existing Function binding and choose which values to recompute:
<CodeGroup>
```python 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)
```
```typescript TypeScript
const upgradeJob = await table.upgradeColumn("embedding", { version: "2", recompute: "failed" });
await upgradeJob.wait();
const provenance = await table.functionProvenance("embedding");
if (!provenance.truncated) {
console.log(provenance.records);
}
```
</CodeGroup>
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:
<CodeGroup>
```python Python
table.quarantine_failed("embedding", after_attempts=3)
retry_job = table.retry_failed("embedding", include_quarantined=True)
retry_job.wait()
```
```typescript TypeScript
await table.quarantineFailed("embedding", { afterAttempts: 3 });
const retryJob = await table.retryFailed("embedding", { includeQuarantined: true });
await retryJob.wait();
```
</CodeGroup>
Ordinary and automatic refreshes exclude quarantined rows, including during
an `"all"` upgrade. Explicit inclusion releases quarantine before the retry.
To release rows for a later refresh, set `quarantined=False` in Python or
`quarantined: false` in TypeScript when calling the quarantine method.
Async Python tables expose the same operations with `await`, including
`rows()` on the `AsyncFunctionErrors` listing.
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.
## Resume a failed refresh job {#resume-refresh}
Job recovery requires a Python or Rust SDK that exposes `resume_refresh` and
an Enterprise deployment that supports `POST /v1/table/{id}/resume_refresh`.
The `workflow_version` reported by `function_errors` covers row-error
operations. Check your server release for job recovery support separately.
Open the original table on the branch where the refresh failed. Pass the
failed job ID to get a handle for the successor attempt and wait for its result.
```python
resumed = table.resume_refresh(failed_job_id)
result = resumed.wait()
```
```rust
async fn resume(table: &lancedb::Table, failed_job_id: &str) -> lancedb::Result<()> {
let resumed = table.resume_refresh(failed_job_id).await?;
let result = resumed.wait().await?;
println!("Assigned {} rows", result.rows_assigned);
Ok(())
}
```
The server reuses confirmed outputs. If it reports that an external call may
already have run, check the external result before starting another refresh.
For a Function with external effects, set `max_job_attempts=1` when submitting
the refresh until you have verified replay safety on your deployment. A limit
of `1` counts the initial attempt and disables automatic job retries.
## 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}
On these deployments, the default `fail` stops the job on a row error. `skip`
retains a failed row's existing output, leaves an unassigned output unassigned
and records errors, subject to the refresh's failure limits:
```python
job = table.refresh_column_async(
"embedding",
error_policy="skip",
max_failed_rows=100,
max_failed_fraction=0.1,
)
result = job.wait()
print(result.rows_assigned, result.rows_failed, result.rows_remaining)
```
Choose limits for your workload; these example limits stop work when more
than 100 rows or more than 10% fail. `skip` does not make initialization,
infrastructure or publication failures successful. If `wait()` raises,
[refresh the job record](/basics/jobs#snapshots), inspect `job.failure()`, and
inspect any recorded row errors. A failed/cancelled job can have committed
some output, but retention of every successful call is not guaranteed.
External effects are not rolled back and can be repeated during recovery.
## Inspect and group recorded errors {#inspect}
Scope diagnostics to the job you are investigating:
```python
from collections import Counter
errors = table.function_errors(job_id=job.id(), column="embedding", limit=10000)
groups = Counter((r.error_type, r.error_message) for r in errors.records)
for cause, count in groups.most_common():
print(count, cause)
for fragment in errors.fragments:
print(fragment.fragment_id, fragment.rows_skipped, fragment.rows_recorded)
print("listing truncated:", errors.truncated)
```
Each record includes the Function name/version, table version, error type and
message, creation time, and available row identities. `attempts` and traceback
details depend on the server/image version. This client-side grouping counts
only returned detail records. `truncated=True` or fragment summaries with
more skipped than recorded rows mean it is incomplete; do not label it a full
error census. See [`SHOW ERRORS`](/sql/ddl/job#errors) for SQL and its limits.
Records are historical observations, not a deduplicated list of currently
failed rows. Reading errors without `job_id` can include older attempts that
have since succeeded. A null output can mean unfilled, skipped, or a computed
nullable field; output nullness alone is not a current-error test.
## Retry exactly identified rows {#retry}
On tables with stable row IDs, supporting server/SDK versions return
`record.row_id` from the refresh's pinned source version. Keep that table and
branch identity with the records. Compaction can move physical addresses, so
do not derive a row ID from fragment numbers or offsets.
The following deliberately refuses incomplete or unidentified error sets.
Review historical records against the current inputs before using them as a
retry selection. Keep this selection small enough for a SQL predicate.
```python
if errors.truncated or any(f.rows_skipped > f.rows_recorded for f in errors.fragments):
raise RuntimeError("Inspect a narrower job/error set before selecting retries")
if any(r.row_id is None for r in errors.records):
raise RuntimeError("This workflow requires stable row IDs in every error record")
row_ids = sorted({int(r.row_id) for r in errors.records})
if row_ids:
predicate = "_rowid IN (" + ", ".join(map(str, row_ids)) + ")"
retry_job = table.refresh_column_async("embedding", where=predicate)
retry_job.wait()
```
This recomputes every selected live row with the existing binding. It can
repeat a row already repaired since the error was recorded. Inspect the retry
job and its errors afterward; an older record need not disappear. On tables
without stable row IDs, resolve errors to application keys at the recorded
snapshot before retrying. Do not substitute `_rowaddr` after a rewrite.
Python `where=` requires a supporting SDK such as `0.42.0b9`, not stable
`0.41.0`, plus a matching server.
## Repair with a newer Function {#new-version}
Registering a new version does not change an existing column's immutable
binding. To evaluate a fix while retaining old outputs, register the corrected
callable and declare a separate output column. For example, with a corrected
`embed_fixed` callable already defined and a `text` input column:
```python
from lancedb import col
fixed = db.create_function(embed_fixed)
table.add_columns(
{"embedding_repaired": fixed(text=col("text"))},
auto_refresh_enabled=False,
)
if row_ids:
repair_job = table.refresh_column_async("embedding_repaired", where=predicate)
repair_job.wait()
```
Only the reviewed failed-row selection is populated in the new column; other
rows remain unfilled. Compare those outputs before deciding how readers
should use them. This does not promise an in-place upgrade/retry operation or
per-row producing-version lookup for a column containing mixed executions.
Error records' Function versions describe failures, not the provenance of
every successful row.
## Quarantine inputs for review {#quarantine}
Use an application-owned table of source table/branch, recorded table version,
stable row ID or business key, Function version, cause and review disposition.
Keep Blob payloads in the source table; a quarantine entry can refer to their
source identity. Choose an ordinary table name such as `function_quarantine`,
and explicitly exclude its reviewed IDs in subsequent input selections.
Quarantine is an application workflow here: there is no implied built-in
quarantine lifecycle, automatic current-error clearing or exactly-once retry.
Do not delete source rows merely to hide an error. For very large failure sets,
bounded error listings cannot select every row; use a smaller reviewed scope
or wait for a deployment with the required complete selection support.
Native retry policies, full current-error summaries, in-place version upgrades
and materialized-view row-error handling have separate server/SDK prerequisites.
Do not apply `REFRESH COLUMN` options to a materialized view and assume the
same policy; consult the [MV refresh reference](/sql/dml/refresh-materialized-view)
for your deployment's accepted options.
## Continue {#next}
- [Function lifecycle and failures](/management/function#failures)
- [Conditional and list-element refresh](/feature-engineering/refresh-column#partial)
- [Job results and events](/basics/jobs#snapshots)