diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index a1618c47b..afd2b897f 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -952,41 +952,81 @@ that version; a latest handle retains normal read-freshness behavior. *** +### functionErrorRows() + +```ts +functionErrorRows(options?): Promise +``` + +Read current failing inputs, one result per error record. +Requires a complete LanceDB Enterprise workflow version 1 listing with +row identities. Throws if a failed row is no longer addressable in the +table's read snapshot. For materialized views, see the source identities +on each error record returned by [Table#functionErrors](Table.md#functionerrors). + +#### Parameters + +* **options?**: [`FunctionErrorRowsOptions`](../interfaces/FunctionErrorRowsOptions.md) + +#### Returns + +`Promise`<[`FunctionFailedRow`](../interfaces/FunctionFailedRow.md)[]> + +*** + ### functionErrors() ```ts abstract functionErrors(options?): Promise ``` -The per-row errors Function refreshes recorded on this table. +List the per-row errors recorded by Function refreshes 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. +On LanceDB Enterprise with workflow version 1 or later, the default +lists current failures. Set `history: true` to include retained attempts +for repaired rows. Older deployments keep their existing default listing. +Reading errors requires table read access because messages can include the +input that failed. `errorGroups` describes the returned records. #### Parameters * **options?**: [`FunctionErrorsOptions`](../interfaces/FunctionErrorsOptions.md) - Optional filters: `jobId`, - `column`, and `limit` (server default 10000, cap 100000). #### Returns `Promise`<[`FunctionErrors`](../interfaces/FunctionErrors.md)> -The records, the capped fragments, -and whether the listing stopped at its limit. - #### Example ```ts -const { records, truncated } = await table.functionErrors({ column: "embedding" }); +const errors = await table.functionErrors({ column: "embedding" }); +console.log(errors.records, errors.errorGroups); ``` *** +### functionProvenance() + +```ts +functionProvenance(_column, _options?): Promise +``` + +Read the producing Function version and job for each returned value. +Check `truncated` before treating the result as a complete listing. +Requires LanceDB Enterprise Function failure workflow version 1 or later. + +#### Parameters + +* **\_column**: `string` + +* **\_options?**: [`FunctionProvenanceOptions`](../interfaces/FunctionProvenanceOptions.md) + +#### Returns + +`Promise`<[`FunctionProvenance`](../interfaces/FunctionProvenance.md)> + +*** + ### getRTESpec() ```ts @@ -1350,6 +1390,28 @@ Prewarm an index in the table. *** +### quarantineFailed() + +```ts +quarantineFailed(_column, _options?): Promise +``` + +Quarantine current failures and return the number of affected rows. +Set `quarantined: false` to release them for future refreshes. +Requires LanceDB Enterprise Function failure workflow version 1 or later. + +#### Parameters + +* **\_column**: `string` + +* **\_options?**: [`FunctionQuarantineOptions`](../interfaces/FunctionQuarantineOptions.md) + +#### Returns + +`Promise`<`number`> + +*** + ### query() ```ts @@ -1560,6 +1622,28 @@ out state and the read_consistency_interval, if any, will apply. *** +### retryFailed() + +```ts +retryFailed(_column, _options?): Promise> +``` + +Start a job to retry exactly the current failures of one Function column. +Filters apply on the server. Quarantined rows are excluded by default. +Requires LanceDB Enterprise Function failure workflow version 1 or later. + +#### Parameters + +* **\_column**: `string` + +* **\_options?**: [`RetryFailedOptions`](../interfaces/RetryFailedOptions.md) + +#### Returns + +`Promise`<[`Job`](Job.md)<[`RefreshColumnJobResult`](../interfaces/RefreshColumnJobResult.md)>> + +*** + ### schema() ```ts @@ -1932,6 +2016,28 @@ await table.updateTableOverrides({ *** +### upgradeColumn() + +```ts +upgradeColumn(_column, _options): Promise> +``` + +Start an upgrade to an existing immutable Function version and choose +which rows to recompute. New and changed inputs use the new version. +Requires LanceDB Enterprise Function failure workflow version 1 or later. + +#### Parameters + +* **\_column**: `string` + +* **\_options**: [`UpgradeColumnOptions`](../interfaces/UpgradeColumnOptions.md) + +#### Returns + +`Promise`<[`Job`](Job.md)<[`RefreshColumnJobResult`](../interfaces/RefreshColumnJobResult.md)>> + +*** + ### vectorSearch() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 79ebf0f13..33fbe1176 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -106,15 +106,22 @@ - [FunctionColumnStatus](interfaces/FunctionColumnStatus.md) - [FunctionColumnVersionStatus](interfaces/FunctionColumnVersionStatus.md) - [FunctionErrorFragment](interfaces/FunctionErrorFragment.md) +- [FunctionErrorGroup](interfaces/FunctionErrorGroup.md) - [FunctionErrorRecord](interfaces/FunctionErrorRecord.md) +- [FunctionErrorRowsOptions](interfaces/FunctionErrorRowsOptions.md) - [FunctionErrors](interfaces/FunctionErrors.md) - [FunctionErrorsOptions](interfaces/FunctionErrorsOptions.md) +- [FunctionFailedRow](interfaces/FunctionFailedRow.md) - [FunctionProfile](interfaces/FunctionProfile.md) - [FunctionProfileOptions](interfaces/FunctionProfileOptions.md) - [FunctionProfileWaitOptions](interfaces/FunctionProfileWaitOptions.md) +- [FunctionProvenance](interfaces/FunctionProvenance.md) +- [FunctionProvenanceOptions](interfaces/FunctionProvenanceOptions.md) +- [FunctionQuarantineOptions](interfaces/FunctionQuarantineOptions.md) - [FunctionRefreshPlanningConfig](interfaces/FunctionRefreshPlanningConfig.md) - [FunctionRefreshPodResources](interfaces/FunctionRefreshPodResources.md) - [FunctionRetryPolicy](interfaces/FunctionRetryPolicy.md) +- [FunctionValueProvenance](interfaces/FunctionValueProvenance.md) - [HnswPqOptions](interfaces/HnswPqOptions.md) - [HnswSqOptions](interfaces/HnswSqOptions.md) - [IndexConfig](interfaces/IndexConfig.md) @@ -145,6 +152,7 @@ - [RTEStats](interfaces/RTEStats.md) - [RTEWriteSpec](interfaces/RTEWriteSpec.md) - [RTreeOptions](interfaces/RTreeOptions.md) +- [RefreshColumnJobResult](interfaces/RefreshColumnJobResult.md) - [RefreshColumnOptions](interfaces/RefreshColumnOptions.md) - [RefreshColumnResult](interfaces/RefreshColumnResult.md) - [RefreshMaterializedViewResult](interfaces/RefreshMaterializedViewResult.md) @@ -152,6 +160,7 @@ - [RenameTableOptions](interfaces/RenameTableOptions.md) - [RestNamespaceConfig](interfaces/RestNamespaceConfig.md) - [RetryConfig](interfaces/RetryConfig.md) +- [RetryFailedOptions](interfaces/RetryFailedOptions.md) - [ScannableOptions](interfaces/ScannableOptions.md) - [SessionLogout](interfaces/SessionLogout.md) - [SessionStatus](interfaces/SessionStatus.md) @@ -174,6 +183,7 @@ - [UpdateFieldMetadataResult](interfaces/UpdateFieldMetadataResult.md) - [UpdateOptions](interfaces/UpdateOptions.md) - [UpdateResult](interfaces/UpdateResult.md) +- [UpgradeColumnOptions](interfaces/UpgradeColumnOptions.md) - [Version](interfaces/Version.md) - [ViewDescription](interfaces/ViewDescription.md) - [WriteExecutionOptions](interfaces/WriteExecutionOptions.md) @@ -199,6 +209,7 @@ - [FieldLike](type-aliases/FieldLike.md) - [FunctionProfileKind](type-aliases/FunctionProfileKind.md) - [FunctionProfileStatus](type-aliases/FunctionProfileStatus.md) +- [FunctionRecompute](type-aliases/FunctionRecompute.md) - [IntoSql](type-aliases/IntoSql.md) - [IntoVector](type-aliases/IntoVector.md) - [JobProgressCallback](type-aliases/JobProgressCallback.md) diff --git a/docs/src/js/interfaces/FunctionErrorGroup.md b/docs/src/js/interfaces/FunctionErrorGroup.md new file mode 100644 index 000000000..cb804b07b --- /dev/null +++ b/docs/src/js/interfaces/FunctionErrorGroup.md @@ -0,0 +1,41 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionErrorGroup + +# Interface: FunctionErrorGroup + +One cause among the returned Function errors. + +## Properties + +### column + +```ts +column: string; +``` + +*** + +### errorMessage + +```ts +errorMessage: string; +``` + +*** + +### errorType + +```ts +errorType: string; +``` + +*** + +### rowsFailed + +```ts +rowsFailed: bigint; +``` diff --git a/docs/src/js/interfaces/FunctionErrorRecord.md b/docs/src/js/interfaces/FunctionErrorRecord.md index 16198e70e..a95547b06 100644 --- a/docs/src/js/interfaces/FunctionErrorRecord.md +++ b/docs/src/js/interfaces/FunctionErrorRecord.md @@ -10,6 +10,16 @@ One row a Function refresh skipped, as the server recorded it. ## Properties +### attempts? + +```ts +optional attempts: number; +``` + +Number of failed invocation attempts, when recorded. + +*** + ### column ```ts @@ -42,6 +52,16 @@ errorType: string; *** +### firstSeenAtMillis? + +```ts +optional firstSeenAtMillis: number; +``` + +First failure time for this row, when recorded. + +*** + ### fragmentId ```ts @@ -66,6 +86,16 @@ functionVersion: string; *** +### input? + +```ts +optional input: unknown; +``` + +Source identities for a materialized-view Function invocation. + +*** + ### jobId ```ts @@ -74,6 +104,46 @@ jobId: string; *** +### lastSeenAtMillis? + +```ts +optional lastSeenAtMillis: number; +``` + +Latest failure time for this row, when recorded. + +*** + +### quarantined? + +```ts +optional quarantined: boolean; +``` + +Whether the failure is quarantined. Absent on older listings. + +*** + +### rowAddress? + +```ts +optional rowAddress: bigint; +``` + +Physical row address at the recorded version. A rewrite can change it. + +*** + +### rowId? + +```ts +optional rowId: bigint; +``` + +Stable row identity when recorded. It survives compaction and rewrite. + +*** + ### rowOffset? ```ts diff --git a/docs/src/js/interfaces/FunctionErrorRowsOptions.md b/docs/src/js/interfaces/FunctionErrorRowsOptions.md new file mode 100644 index 000000000..da2cdd03c --- /dev/null +++ b/docs/src/js/interfaces/FunctionErrorRowsOptions.md @@ -0,0 +1,65 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionErrorRowsOptions + +# Interface: FunctionErrorRowsOptions + +Filters and projection for current failing inputs. + +## Extends + +- `Pick`<[`FunctionErrorsOptions`](FunctionErrorsOptions.md), `"column"` \| `"jobId"` \| `"limit"`> + +## Properties + +### column? + +```ts +optional column: string; +``` + +Only errors on this column. + +#### Inherited from + +`Pick.column` + +*** + +### columns? + +```ts +optional columns: string[]; +``` + +Source columns to return. Defaults to all source columns. + +*** + +### jobId? + +```ts +optional jobId: string; +``` + +Only errors recorded by this job. + +#### Inherited from + +`Pick.jobId` + +*** + +### limit? + +```ts +optional limit: number; +``` + +At most this many records (server default 10000, cap 100000). + +#### Inherited from + +`Pick.limit` diff --git a/docs/src/js/interfaces/FunctionErrors.md b/docs/src/js/interfaces/FunctionErrors.md index 17f2beefa..2aa19c193 100644 --- a/docs/src/js/interfaces/FunctionErrors.md +++ b/docs/src/js/interfaces/FunctionErrors.md @@ -10,6 +10,17 @@ A table's per-row Function errors. ## Properties +### errorGroups? + +```ts +optional errorGroups: FunctionErrorGroup[]; +``` + +Grouped causes over the returned records, if the server supports the workflow. +Counts can be incomplete. Check `truncated` and `fragments` before using them as totals. + +*** + ### fragments ```ts @@ -47,3 +58,13 @@ truncated: boolean; ``` Whether the listing stopped at its limit. + +*** + +### workflowVersion? + +```ts +optional workflowVersion: number; +``` + +Version of the Enterprise row-failure workflow, if advertised by the server. diff --git a/docs/src/js/interfaces/FunctionErrorsOptions.md b/docs/src/js/interfaces/FunctionErrorsOptions.md index ec8b9b036..1a4f44dd8 100644 --- a/docs/src/js/interfaces/FunctionErrorsOptions.md +++ b/docs/src/js/interfaces/FunctionErrorsOptions.md @@ -20,6 +20,16 @@ Only errors on this column. *** +### history? + +```ts +optional history: boolean; +``` + +Include retained historical attempts, including repaired rows. Requires workflow version 1 or later. + +*** + ### jobId? ```ts diff --git a/docs/src/js/interfaces/FunctionFailedRow.md b/docs/src/js/interfaces/FunctionFailedRow.md new file mode 100644 index 000000000..21a5019c5 --- /dev/null +++ b/docs/src/js/interfaces/FunctionFailedRow.md @@ -0,0 +1,29 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionFailedRow + +# Interface: FunctionFailedRow + +A failed Function-column row and its source data at the table's read snapshot. + +## Properties + +### error + +```ts +error: FunctionErrorRecord; +``` + +The failure for this row and Function column. + +*** + +### input + +```ts +input: Record; +``` + +Values of the requested source columns. diff --git a/docs/src/js/interfaces/FunctionProvenance.md b/docs/src/js/interfaces/FunctionProvenance.md new file mode 100644 index 000000000..98eb66f34 --- /dev/null +++ b/docs/src/js/interfaces/FunctionProvenance.md @@ -0,0 +1,27 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionProvenance + +# Interface: FunctionProvenance + +A bounded producing-version listing for a table snapshot. + +## Properties + +### records + +```ts +records: FunctionValueProvenance[]; +``` + +*** + +### truncated + +```ts +truncated: boolean; +``` + +Whether the listing stopped at its limit. diff --git a/docs/src/js/interfaces/FunctionProvenanceOptions.md b/docs/src/js/interfaces/FunctionProvenanceOptions.md new file mode 100644 index 000000000..01aacd614 --- /dev/null +++ b/docs/src/js/interfaces/FunctionProvenanceOptions.md @@ -0,0 +1,29 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionProvenanceOptions + +# Interface: FunctionProvenanceOptions + +Snapshot and record limit for a producing-version listing. + +## Properties + +### limit? + +```ts +optional limit: number; +``` + +Maximum records to return (server default 10000, cap 100000). + +*** + +### version? + +```ts +optional version: number | bigint; +``` + +An exact table version. Defaults to the table handle's read version. diff --git a/docs/src/js/interfaces/FunctionQuarantineOptions.md b/docs/src/js/interfaces/FunctionQuarantineOptions.md new file mode 100644 index 000000000..e8c5e3679 --- /dev/null +++ b/docs/src/js/interfaces/FunctionQuarantineOptions.md @@ -0,0 +1,49 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionQuarantineOptions + +# Interface: FunctionQuarantineOptions + +Select current failures to quarantine or release. + +## Properties + +### afterAttempts? + +```ts +optional afterAttempts: number; +``` + +Only failures with at least this many attempts. Defaults to 1. + +*** + +### errorType? + +```ts +optional errorType: string; +``` + +Only failures with this exception class. + +*** + +### jobId? + +```ts +optional jobId: string; +``` + +Only failures recorded by this job. + +*** + +### quarantined? + +```ts +optional quarantined: boolean; +``` + +Quarantine by default. Set false to release failures for later refreshes. diff --git a/docs/src/js/interfaces/FunctionValueProvenance.md b/docs/src/js/interfaces/FunctionValueProvenance.md new file mode 100644 index 000000000..56c0974c4 --- /dev/null +++ b/docs/src/js/interfaces/FunctionValueProvenance.md @@ -0,0 +1,73 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionValueProvenance + +# Interface: FunctionValueProvenance + +The Function and job that produced one stored value. + +## Properties + +### column + +```ts +column: string; +``` + +*** + +### functionName + +```ts +functionName: string; +``` + +*** + +### functionVersion + +```ts +functionVersion: string; +``` + +*** + +### jobId + +```ts +jobId: string; +``` + +*** + +### publishedVersion + +```ts +publishedVersion: bigint; +``` + +*** + +### rowAddress? + +```ts +optional rowAddress: bigint; +``` + +*** + +### rowId? + +```ts +optional rowId: bigint; +``` + +*** + +### sourceVersion + +```ts +sourceVersion: bigint; +``` diff --git a/docs/src/js/interfaces/RefreshColumnJobResult.md b/docs/src/js/interfaces/RefreshColumnJobResult.md new file mode 100644 index 000000000..1d5f7fe87 --- /dev/null +++ b/docs/src/js/interfaces/RefreshColumnJobResult.md @@ -0,0 +1,79 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / RefreshColumnJobResult + +# Interface: RefreshColumnJobResult + +The terminal outcome of a Function retry or upgrade job. + +## Properties + +### errorGroups + +```ts +errorGroups: FunctionErrorGroup[]; +``` + +Grouped causes reported by the completed job. + +*** + +### errorGroupsTruncated + +```ts +errorGroupsTruncated: boolean; +``` + +Whether the reported cause counts omit any failures. + +*** + +### publishedVersion? + +```ts +optional publishedVersion: bigint; +``` + +The table version made visible by the job, if it published one. + +*** + +### rowsAssigned + +```ts +rowsAssigned: bigint; +``` + +Logical rows successfully assigned a value. + +*** + +### rowsFailed + +```ts +rowsFailed: bigint; +``` + +Logical rows whose computation failed. + +*** + +### rowsRemaining + +```ts +rowsRemaining: bigint; +``` + +Logical rows still needing a value, excluding rows counted in `rowsFailed`. + +*** + +### sourceVersion + +```ts +sourceVersion: bigint; +``` + +The exact table version read by the job. diff --git a/docs/src/js/interfaces/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md index 4a5b256f7..3c22ada7f 100644 --- a/docs/src/js/interfaces/RefreshColumnOptions.md +++ b/docs/src/js/interfaces/RefreshColumnOptions.md @@ -28,8 +28,8 @@ Maximum rows per Function call; must be greater than zero. optional errorPolicy: string; ``` -`"fail"` (default) stops on a row error; `"skip"` writes null and -records the error, subject to the failure limits. +`"fail"` stops on a row error; `"skip"` records it and continues, +subject to the failure limits. The default is server-dependent. *** diff --git a/docs/src/js/interfaces/RetryFailedOptions.md b/docs/src/js/interfaces/RetryFailedOptions.md new file mode 100644 index 000000000..d13534cb3 --- /dev/null +++ b/docs/src/js/interfaces/RetryFailedOptions.md @@ -0,0 +1,312 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / RetryFailedOptions + +# Interface: RetryFailedOptions + +Options for retrying exactly the current failures of one Function column. + +## Extends + +- `Omit`<[`RefreshColumnOptions`](RefreshColumnOptions.md), `"where"`> + +## Properties + +### batchSize? + +```ts +optional batchSize: number; +``` + +Maximum rows per Function call; must be greater than zero. + +#### Inherited from + +`Omit.batchSize` + +*** + +### errorPolicy? + +```ts +optional errorPolicy: string; +``` + +`"fail"` stops on a row error; `"skip"` records it and continues, +subject to the failure limits. The default is server-dependent. + +#### Inherited from + +`Omit.errorPolicy` + +*** + +### errorType? + +```ts +optional errorType: string; +``` + +Only retry failures with this exception class. + +*** + +### functionVersion? + +```ts +optional functionVersion: string; +``` + +Upgrade to this immutable Function version while retrying failures. + +*** + +### gpuClass? + +```ts +optional gpuClass: string; +``` + +GPU class for Function workers. + +#### Inherited from + +`Omit.gpuClass` + +*** + +### gpuCount? + +```ts +optional gpuCount: number; +``` + +Positive GPU count allocated to each Function worker. + +#### Inherited from + +`Omit.gpuCount` + +*** + +### includeQuarantined? + +```ts +optional includeQuarantined: boolean; +``` + +Explicitly release and retry matching quarantined failures. + +*** + +### initTimeoutSeconds? + +```ts +optional initTimeoutSeconds: number; +``` + +Deadline for Function initialization, in seconds. + +#### Inherited from + +`Omit.initTimeoutSeconds` + +*** + +### jobId? + +```ts +optional jobId: string; +``` + +Only retry current failures recorded by this job. + +*** + +### maxConcurrency? + +```ts +optional maxConcurrency: number; +``` + +Override the registered Function's maximum concurrent user-code calls +for this logical execution. + +#### Inherited from + +`Omit.maxConcurrency` + +*** + +### maxExecutorProcessesPerWorker? + +```ts +optional maxExecutorProcessesPerWorker: number; +``` + +Cap on executor processes per Function worker. + +#### Inherited from + +`Omit.maxExecutorProcessesPerWorker` + +*** + +### maxFailedFraction? + +```ts +optional maxFailedFraction: number; +``` + +Under a skip policy, fail the job once more than this share of rows +(0 to 1) has failed. + +#### Inherited from + +`Omit.maxFailedFraction` + +*** + +### maxFailedRows? + +```ts +optional maxFailedRows: number; +``` + +Under a skip policy, fail the job once more than this many rows have +failed. + +#### Inherited from + +`Omit.maxFailedRows` + +*** + +### numWorkers? + +```ts +optional numWorkers: number; +``` + +Worker count for an expression column; Function columns reject it. + +#### Inherited from + +`Omit.numWorkers` + +*** + +### planningWorkers? + +```ts +optional planningWorkers: FunctionRefreshPlanningConfig; +``` + +Resources and sizing for the refresh planning fleet. + +#### Inherited from + +`Omit.planningWorkers` + +*** + +### publicationIntervalRows? + +```ts +optional publicationIntervalRows: number; +``` + +Row-count threshold for publishing completed Function split ranges. +Must be a positive safe integer. Omit for whole-fragment publication. +Actual publications can be larger; remaining rows publish at completion. +Requires LanceDB Enterprise with non-Blob Function outputs. + +#### Inherited from + +`Omit.publicationIntervalRows` + +*** + +### retryPolicy? + +```ts +optional retryPolicy: FunctionRetryPolicy; +``` + +Override retries of failed user-code calls for this refresh. + +#### Inherited from + +`Omit.retryPolicy` + +*** + +### rowTimeoutSeconds? + +```ts +optional rowTimeoutSeconds: number; +``` + +Deadline for one Function call, in seconds. + +#### Inherited from + +`Omit.rowTimeoutSeconds` + +*** + +### supervisorResources? + +```ts +optional supervisorResources: FunctionRefreshPodResources; +``` + +CPU, memory, and ephemeral-storage limits for the refresh supervisor. + +#### Inherited from + +`Omit.supervisorResources` + +*** + +### totalCpuMillis? + +```ts +optional totalCpuMillis: number; +``` + +Override the total CPU budget in millicores for this refresh. + +#### Inherited from + +`Omit.totalCpuMillis` + +*** + +### totalGpuCount? + +```ts +optional totalGpuCount: number; +``` + +Nonnegative total GPU budget for Function workers. + +#### Inherited from + +`Omit.totalGpuCount` + +*** + +### totalMemoryBytes? + +```ts +optional totalMemoryBytes: number; +``` + +Override the total memory budget in bytes for this refresh. + +#### Inherited from + +`Omit.totalMemoryBytes` diff --git a/docs/src/js/interfaces/UpgradeColumnOptions.md b/docs/src/js/interfaces/UpgradeColumnOptions.md new file mode 100644 index 000000000..9f937b116 --- /dev/null +++ b/docs/src/js/interfaces/UpgradeColumnOptions.md @@ -0,0 +1,292 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / UpgradeColumnOptions + +# Interface: UpgradeColumnOptions + +Options for assigning a new immutable Function version to a column. + +## Extends + +- `Omit`<[`RefreshColumnOptions`](RefreshColumnOptions.md), `"where"`> + +## Properties + +### batchSize? + +```ts +optional batchSize: number; +``` + +Maximum rows per Function call; must be greater than zero. + +#### Inherited from + +`Omit.batchSize` + +*** + +### errorPolicy? + +```ts +optional errorPolicy: string; +``` + +`"fail"` stops on a row error; `"skip"` records it and continues, +subject to the failure limits. The default is server-dependent. + +#### Inherited from + +`Omit.errorPolicy` + +*** + +### gpuClass? + +```ts +optional gpuClass: string; +``` + +GPU class for Function workers. + +#### Inherited from + +`Omit.gpuClass` + +*** + +### gpuCount? + +```ts +optional gpuCount: number; +``` + +Positive GPU count allocated to each Function worker. + +#### Inherited from + +`Omit.gpuCount` + +*** + +### initTimeoutSeconds? + +```ts +optional initTimeoutSeconds: number; +``` + +Deadline for Function initialization, in seconds. + +#### Inherited from + +`Omit.initTimeoutSeconds` + +*** + +### maxConcurrency? + +```ts +optional maxConcurrency: number; +``` + +Override the registered Function's maximum concurrent user-code calls +for this logical execution. + +#### Inherited from + +`Omit.maxConcurrency` + +*** + +### maxExecutorProcessesPerWorker? + +```ts +optional maxExecutorProcessesPerWorker: number; +``` + +Cap on executor processes per Function worker. + +#### Inherited from + +`Omit.maxExecutorProcessesPerWorker` + +*** + +### maxFailedFraction? + +```ts +optional maxFailedFraction: number; +``` + +Under a skip policy, fail the job once more than this share of rows +(0 to 1) has failed. + +#### Inherited from + +`Omit.maxFailedFraction` + +*** + +### maxFailedRows? + +```ts +optional maxFailedRows: number; +``` + +Under a skip policy, fail the job once more than this many rows have +failed. + +#### Inherited from + +`Omit.maxFailedRows` + +*** + +### numWorkers? + +```ts +optional numWorkers: number; +``` + +Worker count for an expression column; Function columns reject it. + +#### Inherited from + +`Omit.numWorkers` + +*** + +### planningWorkers? + +```ts +optional planningWorkers: FunctionRefreshPlanningConfig; +``` + +Resources and sizing for the refresh planning fleet. + +#### Inherited from + +`Omit.planningWorkers` + +*** + +### publicationIntervalRows? + +```ts +optional publicationIntervalRows: number; +``` + +Row-count threshold for publishing completed Function split ranges. +Must be a positive safe integer. Omit for whole-fragment publication. +Actual publications can be larger; remaining rows publish at completion. +Requires LanceDB Enterprise with non-Blob Function outputs. + +#### Inherited from + +`Omit.publicationIntervalRows` + +*** + +### recompute? + +```ts +optional recompute: FunctionRecompute; +``` + +Defaults to `"all"`. Quarantined failures are excluded. + +*** + +### retryPolicy? + +```ts +optional retryPolicy: FunctionRetryPolicy; +``` + +Override retries of failed user-code calls for this refresh. + +#### Inherited from + +`Omit.retryPolicy` + +*** + +### rowTimeoutSeconds? + +```ts +optional rowTimeoutSeconds: number; +``` + +Deadline for one Function call, in seconds. + +#### Inherited from + +`Omit.rowTimeoutSeconds` + +*** + +### supervisorResources? + +```ts +optional supervisorResources: FunctionRefreshPodResources; +``` + +CPU, memory, and ephemeral-storage limits for the refresh supervisor. + +#### Inherited from + +`Omit.supervisorResources` + +*** + +### totalCpuMillis? + +```ts +optional totalCpuMillis: number; +``` + +Override the total CPU budget in millicores for this refresh. + +#### Inherited from + +`Omit.totalCpuMillis` + +*** + +### totalGpuCount? + +```ts +optional totalGpuCount: number; +``` + +Nonnegative total GPU budget for Function workers. + +#### Inherited from + +`Omit.totalGpuCount` + +*** + +### totalMemoryBytes? + +```ts +optional totalMemoryBytes: number; +``` + +Override the total memory budget in bytes for this refresh. + +#### Inherited from + +`Omit.totalMemoryBytes` + +*** + +### version + +```ts +version: string; +``` + +An existing immutable version of the bound Function. diff --git a/docs/src/js/type-aliases/FunctionRecompute.md b/docs/src/js/type-aliases/FunctionRecompute.md new file mode 100644 index 000000000..1957ad801 --- /dev/null +++ b/docs/src/js/type-aliases/FunctionRecompute.md @@ -0,0 +1,15 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionRecompute + +# Type Alias: FunctionRecompute + +```ts +type FunctionRecompute: "failed" | "all" | "none"; +``` + +Which existing values to recompute during a Function version upgrade. +`"failed"` selects current failures. `"all"` refreshes every eligible live +row. `"none"` preserves existing values and only changes the binding. diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx index 793563414..ed002d856 100644 --- a/docs/web/management/function-failures.mdx +++ b/docs/web/management/function-failures.mdx @@ -16,10 +16,11 @@ The recipes that follow it remain available for older deployments. ## Native workflow: server contract version 1 {#native} -This section requires Python SDK 0.42.0b19 or later and an Enterprise +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 +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 @@ -30,7 +31,9 @@ failures remain job failures. External effects can repeat during recovery. Read current unresolved failures, group their causes and inspect their inputs: -```python + + +```python Python errors = table.function_errors(column="embedding") print(errors.summary()) inputs = errors.rows(columns=["text"]) @@ -40,23 +43,54 @@ 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); +``` + + + 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. +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: -```python + + +```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); +``` + + + Upgrade the existing Function binding and choose which values to recompute: -```python + + +```python Python upgrade_job = table.upgrade_column("embedding", version="2", recompute="failed") upgrade_job.wait() provenance = table.function_provenance("embedding") @@ -64,6 +98,17 @@ 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); +} +``` + + + 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 @@ -74,18 +119,28 @@ 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 + + +```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(); +``` + + + 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. +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: diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 35e1d608c..8844afcf2 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -3,6 +3,7 @@ import * as http from "http"; import { RequestListener } from "http"; +import { tableFromArrays } from "apache-arrow"; import packageJson = require("../package.json"); import { ClientAuthMethod, @@ -854,15 +855,349 @@ describe("remote connection", () => { ]); expect(errors.records[0].rowOffset).toBe(9); expect(errors.fragments[0].rowsSkipped).toBe(500); - await table.functionErrors(); + expect(errors.workflowVersion).toBeUndefined(); + expect(errors.errorGroups).toBeUndefined(); + await expect( + table.functionErrorRows({ columns: ["text"] }), + ).rejects.toThrow("Function row-failure workflow"); + await table.functionErrors({ history: false }); await expect(table.functionErrors({ limit: -1 })).rejects.toThrow( "limit must be a non-negative integer", ); + for (const operation of [ + () => table.functionErrors({ history: true }), + () => table.retryFailed("embedding"), + () => table.upgradeColumn("embedding", { version: "2" }), + () => table.quarantineFailed("embedding"), + () => table.quarantineFailed("embedding", { quarantined: false }), + () => table.functionProvenance("embedding"), + ]) { + await expect(operation()).rejects.toThrow( + "Function row-failure workflow", + ); + } }, ); expect(bodies).toEqual([ JSON.parse('{"job_id": "j-7", "column": "embedding", "limit": 2}'), {}, + {}, + ...Array.from({ length: 6 }, () => ({ limit: 1 })), + ]); + }); + + it("reads Function failure history and joins current inputs by exact row identity", async () => { + const stableId = 9_007_199_254_740_993n; + const physicalAddress = 9_007_203_549_708_297n; + const currentRows = tableFromArrays({ + text: ["physical failure", "moved stable row", "unrelated row"], + ["_rowid"]: new BigUint64Array([ + physicalAddress, + stableId, + stableId - 1n, + ]), + ["_rowaddr"]: new BigUint64Array([physicalAddress, 14n, 10n]), + }); + const records = `[ + {"job_id":"j-7", "fragment_id":0, "row_offset":10, + "row_id":${stableId}, "row_address":10, "column":"embedding", + "function":"embed", "function_version":"2", "table_version":11, + "error_type":"ValueError", "error_message":"bad input", + "created_at_millis":1700000000001, "first_seen_at_millis":1700000000000, + "last_seen_at_millis":1700000000001, "attempts":3, "quarantined":true}, + {"job_id":"j-7", "fragment_id":2097153, "row_offset":9, + "row_address":${physicalAddress}, "column":"embedding", + "function":"embed", "function_version":"2", "table_version":11, + "error_type":"ValueError", "error_message":"bad input", "created_at_millis":1700000000001}, + {"job_id":"j-8", "fragment_id":0, "row_offset":10, + "row_id":${stableId}, "row_address":10, "column":"score", + "function":"score", "function_version":"1", "table_version":11, + "error_type":"TypeError", "error_message":"bad input", "created_at_millis":1700000000001} + ]`; + const groups = `[ + {"column":"embedding", "error_type":"ValueError", "error_message":"bad input", "rows_failed":2}, + {"column":"score", "error_type":"TypeError", "error_message":"bad input", "rows_failed":1} + ]`; + const errorRequests: unknown[] = []; + const queryRequests: unknown[] = []; + await withMockDatabase( + (req, res) => { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + if (req.url === "/v1/table/docs/describe/") { + res.writeHead(200).end('{"version":12,"schema":{"fields":[]}}'); + } else if (req.url === "/v1/table/docs/errors") { + const request = JSON.parse(body); + errorRequests.push(request); + const empty = request.column === "empty"; + const truncated = request.limit === 2; + res.writeHead(200).end(`{ + "workflow_version":1, "records":${empty ? "[]" : records}, + "fragments":[], "truncated":${truncated}, + "error_groups":${empty ? "[]" : groups} + }`); + } else if (req.url === "/v1/table/docs/query/") { + const query = JSON.parse(body); + queryRequests.push(query); + const rows = + queryRequests.length === 1 + ? currentRows.slice(0, 2) + : currentRows.slice(0, 1); + res + .writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + }) + .end(Buffer.from(tableToIPC(rows, "stream"))); + } else { + res.writeHead(404).end(); + } + }); + }, + async (db) => { + const table = await db.openTable("docs"); + const errors = await table.functionErrors(); + expect(errors.workflowVersion).toBe(1); + expect(errors.records[0]).toMatchObject({ + rowId: stableId, + rowAddress: 10n, + attempts: 3, + firstSeenAtMillis: 1_700_000_000_000, + lastSeenAtMillis: 1_700_000_000_001, + quarantined: true, + }); + expect(errors.records[1].rowAddress).toBe(physicalAddress); + expect(errors.errorGroups).toEqual([ + { + column: "embedding", + errorType: "ValueError", + errorMessage: "bad input", + rowsFailed: 2n, + }, + { + column: "score", + errorType: "TypeError", + errorMessage: "bad input", + rowsFailed: 1n, + }, + ]); + const rows = await table.functionErrorRows({ columns: ["text"] }); + expect(rows.map(({ input, error }) => [input, error.column])).toEqual([ + [{ text: "moved stable row" }, "embedding"], + [{ text: "physical failure" }, "embedding"], + [{ text: "moved stable row" }, "score"], + ]); + await expect( + table.functionErrorRows({ columns: ["text"] }), + ).rejects.toThrow("no longer addressable"); + const history = await table.functionErrors({ + history: true, + jobId: "j-7", + }); + expect(history.records[0].rowId).toBe(stableId); + await expect( + table.functionErrorRows({ columns: ["text"], limit: 2 }), + ).rejects.toThrow("Function errors are incomplete"); + await expect( + table.functionErrorRows({ column: "empty" }), + ).resolves.toEqual([]); + }, + ); + expect(errorRequests).toEqual([ + {}, + {}, + {}, + { limit: 1 }, + { history: true, ["job_id"]: "j-7" }, + { limit: 2 }, + { column: "empty" }, + ]); + expect(queryRequests).toHaveLength(2); + for (const request of queryRequests) { + expect(request).toMatchObject({ + columns: ["text", "_rowid", "_rowaddr"], + filter: `_rowid IN (${stableId}) OR _rowaddr IN (${physicalAddress})`, + k: 2, + }); + } + }); + + it("forwards exact Function recovery requests and preserves async job results", async () => { + const requests: [string, unknown][] = []; + const stableId = 9_007_199_254_740_993n; + await withMockDatabase( + (req, res) => { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + const path = req.url ?? ""; + const request = body ? JSON.parse(body) : {}; + requests.push([path, request]); + if (path === "/v1/table/docs/describe/") { + res.writeHead(200).end('{"version":8,"schema":{"fields":[]}}'); + } else if (path === "/v1/table/docs/errors") { + res + .writeHead(200) + .end( + '{"workflow_version":1,"records":[],"fragments":[],"truncated":false}', + ); + } else if (path === "/v1/table/docs/backfill_column") { + res.writeHead(202).end('{"job_id":"refresh-1"}'); + } else if (path === "/v1/jobs/describe") { + res.writeHead(200).end(`{ + "job_id":"refresh-1", "job_type":"function_refresh", "job_state":"DONE", + "result":{"rows_assigned":19, "rows_failed":1, "rows_remaining":0, + "source_version":7, "published_version":8, "error_groups_truncated":true, + "error_groups":[{"column":"embedding", "error_type":"ValueError", + "error_message":"bad input", "rows_failed":1}]} + }`); + } else if (path === "/v1/table/docs/errors/quarantine") { + res.writeHead(200).end('{"rows_affected":2}'); + } else if (path === "/v1/table/docs/function_provenance") { + res.writeHead(200).end(`{"truncated":true,"records":[{ + "column":"embedding", "job_id":"refresh-1", "function_name":"embed", + "function_version":"2", "row_id":${stableId}, "row_address":null, + "source_version":7, "published_version":8 + }]}`); + } else { + res.writeHead(404).end(); + } + }); + }, + async (db) => { + const table = await db.openTable("docs"); + const job = await table.retryFailed("embedding", { + errorType: "ValueError", + jobId: "first", + includeQuarantined: true, + functionVersion: "2", + maxFailedFraction: 1, + }); + expect(job.id).toBe("refresh-1"); + expect(await job.wait()).toEqual({ + rowsAssigned: 19n, + rowsFailed: 1n, + rowsRemaining: 0n, + sourceVersion: 7n, + publishedVersion: 8n, + errorGroupsTruncated: true, + errorGroups: [ + { + column: "embedding", + errorType: "ValueError", + errorMessage: "bad input", + rowsFailed: 1n, + }, + ], + }); + await table.retryFailed("embedding"); + await table.upgradeColumn("embedding", { + version: "3", + recompute: "failed", + }); + await table.upgradeColumn("embedding", { version: "4" }); + await table.upgradeColumn("embedding", { + version: "5", + recompute: "none", + }); + await expect( + table.quarantineFailed("embedding", { + jobId: "first", + afterAttempts: 3, + errorType: "ValueError", + }), + ).resolves.toBe(2); + await expect( + table.quarantineFailed("embedding", { quarantined: false }), + ).resolves.toBe(2); + const provenance = await table.functionProvenance("embedding", { + version: 8n, + limit: 1, + }); + expect(provenance.truncated).toBe(true); + expect(provenance.records[0]).toMatchObject({ + jobId: "refresh-1", + functionName: "embed", + functionVersion: "2", + rowId: stableId, + sourceVersion: 7n, + publishedVersion: 8n, + }); + await expect( + table.upgradeColumn("embedding", { version: "" }), + ).rejects.toThrow("nonempty function_version"); + await expect( + table.quarantineFailed("embedding", { afterAttempts: 2 ** 32 + 1 }), + ).rejects.toThrow("afterAttempts"); + await expect( + table.functionProvenance("embedding", { version: -(2n ** 64n) }), + ).rejects.toThrow("positive lossless u64 bigint"); + const ordinary = await table.refreshColumnAsync("embedding"); + await expect(ordinary.wait()).resolves.toBeUndefined(); + }, + ); + const probe = ["/v1/table/docs/errors", { limit: 1 }]; + expect(requests).toEqual([ + ["/v1/table/docs/describe/", {}], + probe, + [ + "/v1/table/docs/backfill_column", + JSON.parse(`{ + "column":"embedding", "retry_errors":true, "retry_job_id":"first", + "retry_error_type":"ValueError", "include_quarantined":true, + "function_version":"2", "recompute":"failed", "max_failed_fraction":1 + }`), + ], + ["/v1/jobs/describe", { ["job_id"]: "refresh-1" }], + probe, + [ + "/v1/table/docs/backfill_column", + { column: "embedding", ["retry_errors"]: true }, + ], + ...[ + ["3", "failed"], + ["4", "all"], + ["5", "none"], + ].flatMap(([version, recompute]) => [ + probe, + [ + "/v1/table/docs/backfill_column", + { column: "embedding", ["function_version"]: version, recompute }, + ], + ]), + probe, + [ + "/v1/table/docs/errors/quarantine", + { + column: "embedding", + quarantined: true, + ["job_id"]: "first", + ["after_attempts"]: 3, + ["error_type"]: "ValueError", + }, + ], + probe, + [ + "/v1/table/docs/errors/quarantine", + { + column: "embedding", + quarantined: false, + ["job_id"]: null, + ["after_attempts"]: null, + ["error_type"]: null, + }, + ], + probe, + [ + "/v1/table/docs/function_provenance", + { column: "embedding", version: 8, limit: 1 }, + ], + ["/v1/table/docs/backfill_column", { column: "embedding" }], + ["/v1/jobs/describe", { ["job_id"]: "refresh-1" }], ]); }); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index afd0e1741..0971d66f9 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -6474,18 +6474,35 @@ describe("durable compaction validation", () => { }); describe("Enterprise table overrides", () => { - it("keeps override methods optional for existing custom Table subclasses", async () => { - // Declare the old Table surface; only the new methods must be inherited. - // Keeping these override methods abstract must fail type checking here. + it("keeps added operations optional for existing custom Table subclasses", async () => { + // Declare the old Table surface; the new methods must be inherited. // biome-ignore lint/correctness/noUnusedVariables: declaration merging supplies the legacy members interface LegacyTable extends Omit< Table, - "getTableOverrides" | "updateTableOverrides" | "resetTableOverrides" + | "getTableOverrides" + | "updateTableOverrides" + | "resetTableOverrides" + | "functionErrors" + | "functionErrorRows" + | "retryFailed" + | "upgradeColumn" + | "quarantineFailed" + | "functionProvenance" > {} - class LegacyTable extends Table {} + class LegacyTable extends Table { + async functionErrors() { + return { records: [], fragments: [], truncated: false }; + } + } const table = new LegacyTable(); + await expect(table.functionErrorRows()).rejects.toThrow( + "Function row-failure workflow", + ); + await expect(table.retryFailed("embedding")).rejects.toThrow( + "retryFailed is not supported on this table type", + ); await expect(table.delta(1)).rejects.toThrow( "table.delta is only supported on LanceDB Embedded tables", ); diff --git a/nodejs/lancedb/function_recovery.ts b/nodejs/lancedb/function_recovery.ts new file mode 100644 index 000000000..54bf86600 --- /dev/null +++ b/nodejs/lancedb/function_recovery.ts @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import type { + FunctionErrorGroup, + FunctionErrorRecord, + FunctionErrors, + FunctionErrorsOptions, + RefreshColumnOptions, +} from "./native"; +import type { Table } from "./table"; + +/** Options for retrying exactly the current failures of one Function column. */ +export interface RetryFailedOptions + extends Omit { + /** Only retry failures with this exception class. */ + errorType?: string; + /** Only retry current failures recorded by this job. */ + jobId?: string; + /** Explicitly release and retry matching quarantined failures. */ + includeQuarantined?: boolean; + /** Upgrade to this immutable Function version while retrying failures. */ + functionVersion?: string; +} + +/** + * Which existing values to recompute during a Function version upgrade. + * `"failed"` selects current failures. `"all"` refreshes every eligible live + * row. `"none"` preserves existing values and only changes the binding. + */ +export type FunctionRecompute = "failed" | "all" | "none"; + +/** Options for assigning a new immutable Function version to a column. */ +export interface UpgradeColumnOptions + extends Omit { + /** An existing immutable version of the bound Function. */ + version: string; + /** Defaults to `"all"`. Quarantined failures are excluded. */ + recompute?: FunctionRecompute; +} + +/** The terminal outcome of a Function retry or upgrade job. */ +export interface RefreshColumnJobResult { + /** Logical rows successfully assigned a value. */ + rowsAssigned: bigint; + /** Logical rows whose computation failed. */ + rowsFailed: bigint; + /** Logical rows still needing a value, excluding rows counted in `rowsFailed`. */ + rowsRemaining: bigint; + /** The exact table version read by the job. */ + sourceVersion: bigint; + /** The table version made visible by the job, if it published one. */ + publishedVersion?: bigint; + /** Grouped causes reported by the completed job. */ + errorGroups: FunctionErrorGroup[]; + /** Whether the reported cause counts omit any failures. */ + errorGroupsTruncated: boolean; +} + +/** @internal */ +export function decodeRefreshColumnJobResult( + value: unknown, +): RefreshColumnJobResult { + // The Rust typed job validates the terminal result and preserves u64 values. + const result = value as { + ["rows_assigned"]: number | bigint; + ["rows_failed"]: number | bigint; + ["rows_remaining"]: number | bigint; + ["source_version"]: number | bigint; + ["published_version"]?: number | bigint; + ["error_groups"]?: { + column: string; + ["error_type"]: string; + ["error_message"]: string; + ["rows_failed"]: number | bigint; + }[]; + ["error_groups_truncated"]?: boolean; + }; + return { + rowsAssigned: BigInt(result.rows_assigned), + rowsFailed: BigInt(result.rows_failed), + rowsRemaining: BigInt(result.rows_remaining), + sourceVersion: BigInt(result.source_version), + publishedVersion: + result.published_version === undefined + ? undefined + : BigInt(result.published_version), + errorGroups: (result.error_groups ?? []).map((group) => ({ + column: group.column, + errorType: group.error_type, + errorMessage: group.error_message, + rowsFailed: BigInt(group.rows_failed), + })), + errorGroupsTruncated: result.error_groups_truncated ?? false, + }; +} + +/** A failed Function-column row and its source data at the table's read snapshot. */ +export interface FunctionFailedRow { + /** Values of the requested source columns. */ + input: Record; + /** The failure for this row and Function column. */ + error: FunctionErrorRecord; +} + +/** Filters and projection for current failing inputs. */ +export interface FunctionErrorRowsOptions + extends Pick { + /** Source columns to return. Defaults to all source columns. */ + columns?: string[]; +} + +/** @internal */ +export async function readFailedRows( + table: Table, + errors: FunctionErrors, + columns?: string[], +): Promise { + if ((errors.workflowVersion ?? 0) < 1) { + throw new Error( + "The server does not support the Function row-failure workflow", + ); + } + if ( + errors.truncated || + errors.fragments.length > 0 || + errors.records.some( + (record) => record.rowOffset == null && record.input == null, + ) + ) { + throw new Error( + "Function errors are incomplete; narrow the request or raise limit", + ); + } + const { records } = errors; + if (records.length === 0) return []; + + const stableIds = new Set(); + const addresses = new Set(); + const keys = records.map((record) => { + if (record.input != null) { + throw new Error( + "Inspect the input source identities for a materialized-view Function error", + ); + } + if (typeof record.rowId === "bigint") { + stableIds.add(record.rowId); + return `_rowid:${record.rowId}`; + } + if (typeof record.rowAddress === "bigint") { + addresses.add(record.rowAddress); + return `_rowaddr:${record.rowAddress}`; + } + throw new Error("This Function error has no source row identity"); + }); + const identities = ( + [ + ["_rowid", stableIds], + ["_rowaddr", addresses], + ] as const + ).filter(([, values]) => values.size > 0); + const identityColumns = identities.map(([column]) => column); + const selected = + columns ?? (await table.schema()).fields.map((field) => field.name); + const projection = [...new Set([...selected, ...identityColumns])]; + const filter = identities + .map(([column, values]) => `${column} IN (${[...values].join(",")})`) + .join(" OR "); + const source = await table + .query() + .select(projection) + .where(filter) + .limit(stableIds.size + addresses.size) + .toArrow(); + const selectedNames = new Set(selected); + const inputColumns = source.schema.fields + .map((field) => field.name) + .filter( + (name) => + (name !== "_rowid" && name !== "_rowaddr") || selectedNames.has(name), + ); + const byIdentity = new Map>(); + for (const row of source) { + if (row === null) continue; + const input = Object.fromEntries( + inputColumns.map((name) => [name, row[name]]), + ); + for (const column of identityColumns) { + const identity: unknown = row[column]; + if (typeof identity === "bigint") { + byIdentity.set(`${column}:${identity}`, input); + } + } + } + return records.map((error, index) => { + const input = byIdentity.get(keys[index]); + if (input === undefined) { + throw new Error( + "Some failed inputs are no longer addressable in this snapshot; refresh the error listing", + ); + } + return { input, error }; + }); +} diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index e8a015c59..88f1bd921 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -63,8 +63,13 @@ export { RefreshColumnResult, FunctionErrors, FunctionErrorsOptions, + FunctionErrorGroup, FunctionErrorRecord, FunctionErrorFragment, + FunctionProvenance, + FunctionProvenanceOptions, + FunctionQuarantineOptions, + FunctionValueProvenance, RefreshMaterializedViewResult, AlterColumnsResult, UpdateFieldMetadataResult, @@ -111,6 +116,15 @@ export { RenameTableOptions, } from "./connection"; +export type { + FunctionErrorRowsOptions, + FunctionFailedRow, + FunctionRecompute, + RefreshColumnJobResult, + RetryFailedOptions, + UpgradeColumnOptions, +} from "./function_recovery"; + export { JobFailureInfo, JobInfo, Session } from "./native.js"; export { diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 6645e0205..a599bac2b 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -41,6 +41,15 @@ import { runWithSignal, } from "./blob"; import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; +import { + type FunctionErrorRowsOptions, + type FunctionFailedRow, + type RefreshColumnJobResult, + type RetryFailedOptions, + type UpgradeColumnOptions, + decodeRefreshColumnJobResult, + readFailedRows, +} from "./function_recovery"; import { IndexOptions } from "./indices"; import { Job } from "./job"; import { validateNonNegativeInteger } from "./materialized_view"; @@ -55,6 +64,9 @@ import { DropColumnsResult, FunctionErrors, FunctionErrorsOptions, + FunctionProvenance, + FunctionProvenanceOptions, + FunctionQuarantineOptions, IndexConfig, IndexStatistics, JobFailureInfo, @@ -1001,26 +1013,87 @@ export abstract class Table { ): Promise; /** - * The per-row errors Function refreshes recorded on this table. + * List the per-row errors recorded by Function refreshes on this table. + * + * On LanceDB Enterprise with workflow version 1 or later, the default + * lists current failures. Set `history: true` to include retained attempts + * for repaired rows. Older deployments keep their existing default listing. + * Reading errors requires table read access because messages can include the + * input that failed. `errorGroups` describes the returned records. * - * 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. - * @param {FunctionErrorsOptions} options Optional filters: `jobId`, - * `column`, and `limit` (server default 10000, cap 100000). - * @returns {Promise} The records, the capped fragments, - * and whether the listing stopped at its limit. * @example * ```ts - * const { records, truncated } = await table.functionErrors({ column: "embedding" }); + * const errors = await table.functionErrors({ column: "embedding" }); + * console.log(errors.records, errors.errorGroups); * ``` */ abstract functionErrors( options?: FunctionErrorsOptions, ): Promise; + /** + * Read current failing inputs, one result per error record. + * Requires a complete LanceDB Enterprise workflow version 1 listing with + * row identities. Throws if a failed row is no longer addressable in the + * table's read snapshot. For materialized views, see the source identities + * on each error record returned by {@link Table#functionErrors}. + */ + async functionErrorRows( + options?: FunctionErrorRowsOptions, + ): Promise { + const { columns, column, jobId, limit } = options ?? {}; + const errors = await this.functionErrors({ column, jobId, limit }); + return readFailedRows(this, errors, columns); + } + + /** + * Start a job to retry exactly the current failures of one Function column. + * Filters apply on the server. Quarantined rows are excluded by default. + * Requires LanceDB Enterprise Function failure workflow version 1 or later. + */ + async retryFailed( + _column: string, + _options?: RetryFailedOptions, + ): Promise> { + throw new Error("retryFailed is not supported on this table type"); + } + + /** + * Start an upgrade to an existing immutable Function version and choose + * which rows to recompute. New and changed inputs use the new version. + * Requires LanceDB Enterprise Function failure workflow version 1 or later. + */ + async upgradeColumn( + _column: string, + _options: UpgradeColumnOptions, + ): Promise> { + throw new Error("upgradeColumn is not supported on this table type"); + } + + /** + * Quarantine current failures and return the number of affected rows. + * Set `quarantined: false` to release them for future refreshes. + * Requires LanceDB Enterprise Function failure workflow version 1 or later. + */ + async quarantineFailed( + _column: string, + _options?: FunctionQuarantineOptions, + ): Promise { + throw new Error("quarantineFailed is not supported on this table type"); + } + + /** + * Read the producing Function version and job for each returned value. + * Check `truncated` before treating the result as a complete listing. + * Requires LanceDB Enterprise Function failure workflow version 1 or later. + */ + async functionProvenance( + _column: string, + _options?: FunctionProvenanceOptions, + ): Promise { + throw new Error("functionProvenance is not supported on this table type"); + } + /** * Return exact freshness status for Function-backed output columns. * @@ -2012,7 +2085,56 @@ export class LocalTable extends Table { options?: FunctionErrorsOptions, ): Promise { validateNonNegativeInteger(options?.limit, "limit"); - return await this.inner.functionErrors(options); + return this.inner.functionErrors(options); + } + + override async retryFailed( + column: string, + options?: RetryFailedOptions, + ): Promise> { + const { + errorType, + jobId, + includeQuarantined, + functionVersion, + ...refresh + } = options ?? {}; + const job = await this.inner.refreshColumnAsync(column, refresh, { + retryErrors: true, + retryErrorType: errorType, + retryJobId: jobId, + includeQuarantined, + functionVersion, + recompute: functionVersion === undefined ? undefined : "failed", + }); + return new Job(job, decodeRefreshColumnJobResult); + } + + override async upgradeColumn( + column: string, + options: UpgradeColumnOptions, + ): Promise> { + const { version, recompute = "all", ...refresh } = options; + const job = await this.inner.refreshColumnAsync(column, refresh, { + functionVersion: version, + recompute, + }); + return new Job(job, decodeRefreshColumnJobResult); + } + + override async quarantineFailed( + column: string, + options?: FunctionQuarantineOptions, + ): Promise { + return this.inner.quarantineFunctionErrors(column, options); + } + + override async functionProvenance( + column: string, + options?: FunctionProvenanceOptions, + ): Promise { + validateNonNegativeInteger(options?.limit, "limit"); + return this.inner.functionProvenance(column, options); } async functionColumnStatuses( diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 1370278b0..098b7ce0b 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -685,14 +685,24 @@ impl Table { &self, column: String, options: Option, + recovery: Option, ) -> napi::Result { - let options = options.unwrap_or_default().try_into()?; + let mut options: lancedb::table::RefreshColumnOptions = + options.unwrap_or_default().try_into()?; + let typed_result = recovery.is_some(); + if let Some(recovery) = recovery { + recovery.apply(&mut options)?; + } let job = self .inner_ref()? .refresh_column_async_with_options(column, options) .await .default_error()?; - Ok(crate::job::Job::new(job)) + Ok(if typed_result { + crate::job::Job::new_typed(job) + } else { + crate::job::Job::new(job) + }) } #[napi(catch_unwind)] @@ -701,18 +711,11 @@ impl Table { options: Option, ) -> napi::Result { let options = options.unwrap_or_default(); - let limit = options - .limit - .map(|limit| { - usize::try_from(limit) - .map_err(|_| napi::Error::from_reason("limit must be a non-negative integer")) - }) - .transpose()?; let request = lancedb::function::FunctionErrorsRequest { - history: false, + history: options.history.unwrap_or_default(), job_id: options.job_id, column: options.column, - limit, + limit: function_listing_limit(options.limit)?, page_token: options.page_token, }; let errors = self @@ -723,6 +726,62 @@ impl Table { Ok(errors.into()) } + #[napi(catch_unwind)] + pub async fn quarantine_function_errors( + &self, + column: String, + options: Option, + ) -> napi::Result { + let options = options.unwrap_or_default(); + let options = lancedb::function::FunctionQuarantineOptions { + quarantined: options.quarantined.unwrap_or(true), + job_id: options.job_id, + error_type: options.error_type, + after_attempts: positive_u32(options.after_attempts, "afterAttempts")?, + }; + let affected = self + .inner_ref()? + .quarantine_function_errors(&column, options) + .await + .default_error()?; + Ok(affected as f64) + } + + #[napi(catch_unwind)] + pub async fn function_provenance( + &self, + column: String, + options: Option, + ) -> napi::Result { + let options = options.unwrap_or_default(); + let version = match options.version { + None => None, + Some(Either::A(number)) => Some(positive_safe_integer(number, "version")?), + Some(Either::B(bigint)) => { + let (negative, value, lossless) = bigint.get_u64(); + if negative || !lossless || value == 0 { + return Err(napi::Error::from_reason( + "version must be a positive lossless u64 bigint", + )); + } + Some(value) + } + }; + let options = lancedb::function::FunctionProvenanceOptions { + version, + limit: function_listing_limit(options.limit)?, + }; + let provenance = self + .inner_ref()? + .function_provenance(&column, options) + .await + .default_error()?; + Ok(FunctionProvenance { + records: provenance.records.into_iter().map(Into::into).collect(), + truncated: provenance.truncated, + }) + } + #[napi(catch_unwind)] pub async fn function_column_statuses( &self, @@ -1946,10 +2005,78 @@ pub struct FunctionErrorsOptions { pub column: Option, /// At most this many records (server default 10000, cap 100000). pub limit: Option, + /// Include retained historical attempts, including repaired rows. Requires workflow version 1 or later. + pub history: Option, /// Empty starts retained history, including repaired rows, for an exact jobId; otherwise continue that page. pub page_token: Option, } +fn function_listing_limit(limit: Option) -> napi::Result> { + limit + .map(|limit| { + usize::try_from(limit) + .map_err(|_| napi::Error::from_reason("limit must be a non-negative integer")) + }) + .transpose() +} + +/// Select current failures to quarantine or release. +#[napi(object)] +#[derive(Default)] +pub struct FunctionQuarantineOptions { + /// Quarantine by default. Set false to release failures for later refreshes. + pub quarantined: Option, + /// Only failures recorded by this job. + pub job_id: Option, + /// Only failures with this exception class. + pub error_type: Option, + /// Only failures with at least this many attempts. Defaults to 1. + pub after_attempts: Option, +} + +/// Snapshot and record limit for a producing-version listing. +#[napi(object)] +#[derive(Default)] +pub struct FunctionProvenanceOptions { + /// An exact table version. Defaults to the table handle's read version. + pub version: Option>, + /// Maximum records to return (server default 10000, cap 100000). + pub limit: Option, +} + +#[napi(object)] +pub struct FunctionRecoveryOptions { + pub retry_errors: Option, + pub retry_job_id: Option, + pub retry_error_type: Option, + pub include_quarantined: Option, + pub function_version: Option, + pub recompute: Option, +} + +impl FunctionRecoveryOptions { + fn apply(self, options: &mut lancedb::table::RefreshColumnOptions) -> napi::Result<()> { + use lancedb::function::FunctionRecompute; + options.retry_errors = self.retry_errors; + options.retry_job_id = self.retry_job_id; + options.retry_error_type = self.retry_error_type; + options.include_quarantined = self.include_quarantined; + options.function_version = self.function_version; + options.recompute = match self.recompute.as_deref() { + None => None, + Some("failed") => Some(FunctionRecompute::Failed), + Some("all") => Some(FunctionRecompute::All), + Some("none") => Some(FunctionRecompute::None), + Some(_) => { + return Err(napi::Error::from_reason( + "recompute must be 'failed', 'all', or 'none'", + )); + } + }; + Ok(()) + } +} + /// CPU, memory, and ephemeral-storage limits for one Function refresh /// control-plane pod. #[napi(object)] @@ -2063,8 +2190,8 @@ pub struct RefreshColumnOptions { pub total_gpu_count: Option, /// Override retries of failed user-code calls for this refresh. pub retry_policy: Option, - /// `"fail"` (default) stops on a row error; `"skip"` writes null and - /// records the error, subject to the failure limits. + /// `"fail"` stops on a row error; `"skip"` records it and continues, + /// subject to the failure limits. The default is server-dependent. pub error_policy: Option, /// Under a skip policy, fail the job once more than this share of rows /// (0 to 1) has failed. @@ -2234,35 +2361,113 @@ pub struct FunctionErrorRecord { /// The row's offset within the fragment; absent when the fragment's /// detail was capped. pub row_offset: Option, + /// Stable row identity when recorded. It survives compaction and rewrite. + pub row_id: Option, + /// Physical row address at the recorded version. A rewrite can change it. + pub row_address: Option, pub column: String, pub function: String, pub function_version: String, pub table_version: i64, pub error_type: String, pub error_message: String, + /// Number of failed invocation attempts, when recorded. + pub attempts: Option, /// User-code traceback, possibly truncated by the server. pub traceback: Option, pub created_at_millis: i64, + /// First failure time for this row, when recorded. + pub first_seen_at_millis: Option, + /// Latest failure time for this row, when recorded. + pub last_seen_at_millis: Option, + /// Whether the failure is quarantined. Absent on older listings. + pub quarantined: Option, + /// Source identities for a materialized-view Function invocation. + #[napi(ts_type = "unknown")] + pub input: Option, } -impl From for FunctionErrorRecord { - fn from(record: lancedb::function::FunctionErrorRecord) -> Self { +impl FunctionErrorRecord { + fn from_record(record: lancedb::function::FunctionErrorRecord, has_workflow: bool) -> Self { Self { job_id: record.job_id, fragment_id: record.fragment_id as i64, row_offset: record.row_offset.map(i64::from), + row_id: record.row_id.map(BigInt::from), + row_address: record.row_address.map(BigInt::from), column: record.column, function: record.function, function_version: record.function_version, table_version: record.table_version as i64, error_type: record.error_type, error_message: record.error_message, + attempts: record.attempts, traceback: record.traceback, created_at_millis: record.created_at_millis, + first_seen_at_millis: record.first_seen_at_millis, + last_seen_at_millis: record.last_seen_at_millis, + quarantined: has_workflow.then_some(record.quarantined), + input: record.input, } } } +/// One cause among the returned Function errors. +#[napi(object)] +pub struct FunctionErrorGroup { + pub column: String, + pub error_type: String, + pub error_message: String, + pub rows_failed: BigInt, +} + +impl From for FunctionErrorGroup { + fn from(group: lancedb::function::FunctionErrorGroup) -> Self { + Self { + column: group.column, + error_type: group.error_type, + error_message: group.error_message, + rows_failed: BigInt::from(group.rows_failed), + } + } +} + +/// The Function and job that produced one stored value. +#[napi(object)] +pub struct FunctionValueProvenance { + pub column: String, + pub job_id: String, + pub function_name: String, + pub function_version: String, + pub row_id: Option, + pub row_address: Option, + pub source_version: BigInt, + pub published_version: BigInt, +} + +impl From for FunctionValueProvenance { + fn from(record: lancedb::function::FunctionValueProvenance) -> Self { + Self { + column: record.column, + job_id: record.job_id, + function_name: record.function_name, + function_version: record.function_version, + row_id: record.row_id.map(BigInt::from), + row_address: record.row_address.map(BigInt::from), + source_version: BigInt::from(record.source_version), + published_version: BigInt::from(record.published_version), + } + } +} + +/// A bounded producing-version listing for a table snapshot. +#[napi(object)] +pub struct FunctionProvenance { + pub records: Vec, + /// Whether the listing stopped at its limit. + pub truncated: bool, +} + /// A fragment whose per-row error detail was capped: `rowsSkipped` rows /// failed, of which only `rowsRecorded` have a record of their own. #[napi(object)] @@ -2287,8 +2492,12 @@ impl From for FunctionErrorFragment { /// A table's per-row Function errors. #[napi(object)] -#[derive(Clone, Debug)] pub struct FunctionErrors { + /// Version of the Enterprise row-failure workflow, if advertised by the server. + pub workflow_version: Option, + /// Grouped causes over the returned records, if the server supports the workflow. + /// Counts can be incomplete. Check `truncated` and `fragments` before using them as totals. + pub error_groups: Option>, /// The recorded rows, newest job first. pub records: Vec, /// Fragments whose detail was capped. @@ -2411,8 +2620,16 @@ impl From for FunctionColumnStatus { impl From for FunctionErrors { fn from(errors: lancedb::function::FunctionErrors) -> Self { + let has_workflow = errors.workflow_version.is_some_and(|version| version >= 1); Self { - records: errors.records.into_iter().map(Into::into).collect(), + workflow_version: errors.workflow_version, + error_groups: has_workflow + .then(|| errors.error_groups.into_iter().map(Into::into).collect()), + records: errors + .records + .into_iter() + .map(|record| FunctionErrorRecord::from_record(record, has_workflow)) + .collect(), fragments: errors.fragments.into_iter().map(Into::into).collect(), truncated: errors.truncated, page_token: errors.page_token,