diff --git a/docs/src/js/classes/Job.md b/docs/src/js/classes/Job.md index 43d532cdd..01f4a1f50 100644 --- a/docs/src/js/classes/Job.md +++ b/docs/src/js/classes/Job.md @@ -26,6 +26,20 @@ extra round trip on every call: ## Accessors +### attempt + +```ts +get attempt(): null | number +``` + +One-based attempt ordinal. Worker replacement does not increment it. + +#### Returns + +`null` \| `number` + +*** + ### creationMs ```ts @@ -40,6 +54,20 @@ When the job was created, in milliseconds since the epoch. *** +### executionEpoch + +```ts +get executionEpoch(): null | number +``` + +Most recent execution's fencing token, when reported. + +#### Returns + +`null` \| `number` + +*** + ### failure ```ts @@ -73,6 +101,23 @@ durable resume tokens. *** +### jobId + +```ts +get jobId(): null | string +``` + +Identity of the selected attempt last observed by this handle. +For operation handles, `refresh()` or `status()` can select a different +attempt while `id` stays unchanged. Save this value after refreshing and +use it throughout paged diagnostics. Local IDs cannot be reopened on a server. + +#### Returns + +`null` \| `string` + +*** + ### jobType ```ts @@ -88,6 +133,34 @@ server-reported job type. Null for in-process handles. *** +### lifecycleState + +```ts +get lifecycleState(): null | JobState +``` + +Detailed state last observed; unknown values never establish success. + +#### Returns + +`null` \| [`JobState`](../type-aliases/JobState.md) + +*** + +### operationId + +```ts +get operationId(): null | string +``` + +Root of the explicit retry lineage, when reported. + +#### Returns + +`null` \| `string` + +*** + ### result ```ts @@ -104,6 +177,34 @@ instead. *** +### retryOf + +```ts +get retryOf(): null | string +``` + +Immediate predecessor attempt, when reported. + +#### Returns + +`null` \| `string` + +*** + +### sourceTableVersion + +```ts +get sourceTableVersion(): null | number +``` + +Source snapshot pinned for this attempt, when reported. + +#### Returns + +`null` \| `number` + +*** + ### spec ```ts @@ -175,6 +276,24 @@ per fragment. `filter` is a SQL-like expression over the `state`, *** +### history() + +```ts +history(options?): AsyncGenerator, any, unknown> +``` + +Walk retained history one page at a time using the server's continuation. + +#### Parameters + +* **options?**: [`JobEventsOptions`](../interfaces/JobEventsOptions.md) + +#### Returns + +`AsyncGenerator`<`Table`<`any`>, `any`, `unknown`> + +*** + ### progress() ```ts @@ -208,6 +327,20 @@ its full record, then cache it for the getters above. *** +### retry() + +```ts +retry(): Promise> +``` + +Select this exact attempt's pinned successor. Requires backend support. + +#### Returns + +`Promise`<[`Job`](Job.md)<`T`>> + +*** + ### status() ```ts @@ -226,6 +359,20 @@ terminal failure state. Also refreshes the getters above. *** +### statusTyped() + +```ts +statusTyped(): Promise +``` + +Refresh and return the detailed lifecycle state. + +#### Returns + +`Promise`<[`JobState`](../type-aliases/JobState.md)> + +*** + ### toString() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 2b4498615..1769c6c1f 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -194,6 +194,7 @@ - [IntoSql](type-aliases/IntoSql.md) - [IntoVector](type-aliases/IntoVector.md) - [JobProgressCallback](type-aliases/JobProgressCallback.md) +- [JobState](type-aliases/JobState.md) - [MaterializedViewSelect](type-aliases/MaterializedViewSelect.md) - [MultiVector](type-aliases/MultiVector.md) - [QueryParameterValue](type-aliases/QueryParameterValue.md) diff --git a/docs/src/js/interfaces/CherryPickResult.md b/docs/src/js/interfaces/CherryPickResult.md index fdec8eedd..a5f416629 100644 --- a/docs/src/js/interfaces/CherryPickResult.md +++ b/docs/src/js/interfaces/CherryPickResult.md @@ -38,8 +38,8 @@ preview: CherryPickPreview; ```ts status: - | "ready" | "failed" + | "ready" | "notImplemented" | "cherryPicked" | "unknown"; diff --git a/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md index 3a203026c..eb95c8004 100644 --- a/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md +++ b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md @@ -22,11 +22,11 @@ optional activeJobId: string; ```ts optional blockedReason: + | "cancelled" | "table_has_mem_wal" | "inputs_not_settled" | "dependency_in_flight" | "table_capacity" - | "cancelled" | "preparation_backoff" | "failure_threshold_reached" | "binding_revision_missing"; @@ -86,8 +86,8 @@ optional nextRunAtReason: string; ```ts state: - | "running" | "queued" + | "running" | "disabled" | "ready" | "up_to_date" diff --git a/docs/src/js/interfaces/FunctionErrors.md b/docs/src/js/interfaces/FunctionErrors.md index bee0a80d8..17f2beefa 100644 --- a/docs/src/js/interfaces/FunctionErrors.md +++ b/docs/src/js/interfaces/FunctionErrors.md @@ -20,6 +20,16 @@ Fragments whose detail was capped. *** +### pageToken? + +```ts +optional pageToken: string; +``` + +Continue the same job/filter. Absent for complete pages and older servers. + +*** + ### records ```ts diff --git a/docs/src/js/interfaces/FunctionErrorsOptions.md b/docs/src/js/interfaces/FunctionErrorsOptions.md index af0e71cfe..ec8b9b036 100644 --- a/docs/src/js/interfaces/FunctionErrorsOptions.md +++ b/docs/src/js/interfaces/FunctionErrorsOptions.md @@ -37,3 +37,13 @@ optional limit: number; ``` At most this many records (server default 10000, cap 100000). + +*** + +### pageToken? + +```ts +optional pageToken: string; +``` + +Empty starts retained history, including repaired rows, for an exact jobId; otherwise continue that page. diff --git a/docs/src/js/interfaces/JobEventsOptions.md b/docs/src/js/interfaces/JobEventsOptions.md index 24831f4f1..c03573ddf 100644 --- a/docs/src/js/interfaces/JobEventsOptions.md +++ b/docs/src/js/interfaces/JobEventsOptions.md @@ -27,3 +27,13 @@ optional limit: number; ``` Maximum event rows to return, up to the server maximum of 10,000. + +*** + +### pageToken? + +```ts +optional pageToken: string; +``` + +Opaque continuation from the preceding page's schema metadata. diff --git a/docs/src/js/type-aliases/JobState.md b/docs/src/js/type-aliases/JobState.md new file mode 100644 index 000000000..dfc70b5f3 --- /dev/null +++ b/docs/src/js/type-aliases/JobState.md @@ -0,0 +1,21 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / JobState + +# Type Alias: JobState + +```ts +type JobState: + | "created" + | "queued" + | "in_progress" + | "succeeded" + | "failed" + | "canceled" + | "timed_out" + | string & object; +``` + +Detailed lifecycle state. Unrecognized future values remain strings. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index f315910ed..fdcb0d483 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -452,6 +452,53 @@ identifiers. `fn.image` has a concise representation; `describe()` exposes Pytho and CUDA requirements without inspecting Pydantic internals. Platforms, base image and size are `None` until the service reports them. The full image descriptor and canonical JSON remain available. +Jobs retain an attempt identity through `job_id()`, and explicit server retries +report `operation_id()`, `attempt()`, and `retry_of()` when the server supports +them. +`lifecycle_state()` and `status_typed()` expose detailed `JobState` values while +the existing string `status()` remains available. Unknown future states retain +their value and never imply success. `source_table_version()` identifies the +attempt's pinned input snapshot when reported. + +```python +from datetime import timedelta +from lancedb import JobState + +job = db.open_job(job_id) +state = job.status_typed() +if state is JobState.SUCCEEDED: + print(job.operation_id(), job.attempt(), job.source_table_version()) +job.wait(timeout=timedelta(seconds=5)) +for page in job.history(limit=1000): + print(page) +``` + +A wait timeout leaves execution running and the handle reusable. Cancellation +can be refused when publication has already acquired its commit claim; inspect +the job again to learn that attempt's outcome. LanceDB Embedded handles have a +stable identity for their lifetime and share typed lifecycle and wait semantics; +their IDs cannot be reopened after a process restart. Event history, durable +retries, and per-row Function errors require a backend that records them. + +Explicit retries name the exact failed attempt and preserve its resolved +Function version and source snapshot. Repeating `job.retry()` selects the same +successor; call `retry()` on that successor to request another attempt. Safely +retryable states and publication outcomes are validated by the backend. + +```python +retry = failed_job.retry() +retry.refresh() +attempt_job_id = retry.job_id() +token = "" +while token is not None: + errors = table.function_errors(job_id=attempt_job_id, limit=1000, page_token=token) + print(errors.records, errors.fragments) + token = errors.page_token +``` + +An empty error page can still carry a continuation. Keep the table, branch, +job, and column filters unchanged while paging. Diagnose a terminal attempt for +its complete retained row errors; an executing attempt is a partial observation. A `@function` definition is also a local callable. Call a decorated function directly with row inputs, or call a decorated class with its initialization fields @@ -698,6 +745,8 @@ with BlobReader(read_range, len(payload)) as reader: ::: lancedb.job.Job +::: lancedb.job.JobState + ::: lancedb.job.AsyncJob ::: lancedb.job.JobInfo diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index f7390b69c..69801dc10 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -314,6 +314,184 @@ history. Draft for the Functions release. Add this section before "Embedded and Enterprise execution": +### Typed states and attempt identity + +The existing identity and string status APIs keep their behavior. For a detailed +state, use Python's `status_typed()`, TypeScript's `statusTyped()`, or Rust's +`status_typed()`. Known states are `created`, `queued`, `in_progress`, +`succeeded`, `failed`, `canceled`, and `timed_out`. Unknown future states retain +their original value and never establish success. + +The detail getters report the last observation. Call `status()` or `refresh()` +to populate registry metadata. A handle that follows recovery can select a +different attempt during either call while the existing handle ID stays +unchanged. Save Python's `job_id()` (`jobId` in TypeScript) after refreshing +and use that saved value throughout an exact-attempt diagnostic read; +refreshing again may select a later attempt. + +| Python method | Meaning | +| --- | --- | +| `job_id()` | Identity of one attempt. Embedded identities last for the handle's lifetime and cannot be reopened. | +| `operation_id()` | Root of the explicit retry lineage, when reported. | +| `attempt()` | One-based attempt ordinal. Worker replacement does not increment it. | +| `retry_of()` | Immediate predecessor attempt, when reported. | +| `lifecycle_state()` | Detailed cached lifecycle state, including unknown future values. | +| `source_table_version()` | Source snapshot pinned for the attempt, when reported. | +| `execution_epoch()` | Execution fencing token, when reported. | + +Python data access uses synchronous methods on both handle types. +TypeScript exposes the same values as camel-case properties. Older servers +may omit lineage and pin metadata; a missing value is unknown. + +### Retry an exact attempt + +`retry()` requires a backend that supports exact-attempt retry. It selects a +successor for an unsuccessful attempt, preserving resolved Function inputs, +result decoding, and the submitting table's read freshness. Repeated requests +for the same predecessor select the same successor. Retry the successor's ID +to request another attempt. These guarantees require the supporting server +protocol; Embedded handles without a replayable operation specification refuse +durable retry. + + +```python Python +from lancedb import JobState + +job = db.open_job(job_id) +if job.status_typed() in (JobState.FAILED, JobState.TIMED_OUT): + successor = job.retry() + result = successor.wait() +``` + +```typescript TypeScript +const state = await job.statusTyped(); +if (state === "failed" || state === "timed_out") { + const successor = await job.retry(); + await successor.wait(); +} +``` + +```rust Rust +use lancedb::JobState; + +if matches!( + job.status_typed().await?, + JobState::Failed | JobState::TimedOut +) { + let successor = job.retry().await?; + let result = successor.wait().await?; +} +``` + + +A wait timeout stops waiting without cancelling execution. Keep the handle +and wait again; a timeout alone is not a reason to retry the operation. +TypeScript and Rust also support wait deadlines: + + +```python Python +from datetime import timedelta + +result = job.wait(timeout=timedelta(minutes=10)) +``` + +```typescript TypeScript +await job.wait({ timeoutMs: 10 * 60 * 1000, onProgress: console.log }); +``` + +```rust Rust +use std::time::Duration; + +job.wait_with_options( + lancedb::job::JobWaitOptions::new().timeout(Duration::from_secs(10 * 60)), +).await?; +``` + + +### Retained history and row-error pages + +`events()` returns one retained event page. Pass its opaque continuation to +the next call (`page_token` in Python/Rust, `pageToken` in TypeScript). +`history()` follows those continuations, including empty pages. Python and +TypeScript yield pages; Rust collects the retained batches. Event history +requires a registry-backed handle and a supporting server. + + +```python Python +for page in job.history(limit=1000): + print(page.to_pylist()) +``` + +```typescript TypeScript +for await (const page of job.history({ limit: 1000 })) { + console.log(page.toArray()); +} +``` + +```rust Rust +use lancedb::job::JobEventsRequest; + +for batch in job.history(JobEventsRequest::default().limit(1000)).await? { + println!("{batch:?}"); +} +``` + + +For retained row diagnostics, including repaired rows, opt into paging with an exact `job_id` and an empty +`page_token`. Continue until the response omits its token, keeping the table, +branch, job, and column filters unchanged. Records and capped-fragment +summaries share the page budget. An empty page can still have a continuation. +Explicit paging requires a supporting server; a server that truncates without +returning a cursor is rejected rather than treated as complete. + + +```python Python +job.refresh() +attempt_job_id = job.job_id() +token = "" +while token is not None: + errors = tbl.function_errors(job_id=attempt_job_id, limit=1000, page_token=token) + print(errors.records, errors.fragments) + token = errors.page_token +``` + +```typescript TypeScript +await job.refresh(); +const jobId = job.jobId; +if (jobId === null) throw new Error("A registry attempt ID is required"); +let pageToken: string | undefined = ""; +while (pageToken !== undefined) { + const page = await tbl.functionErrors({ jobId, limit: 1000, pageToken }); + console.log(page.records, page.fragments); + pageToken = page.pageToken ?? undefined; +} +``` + +```rust Rust +use lancedb::function::FunctionErrorsRequest; + +job.refresh().await?; +let job_id = job.job_id().expect("a registry-backed job"); +let mut token = Some(String::new()); +while let Some(current) = token { + let page = table + .function_errors( + FunctionErrorsRequest::new() + .job_id(job_id.clone()) + .limit(1000) + .page_token(current), + ) + .await?; + println!("{:?} {:?}", page.records, page.fragments); + token = page.page_token; +} +``` + + +Pages from an executing attempt are partial observations. Page a terminal +attempt for its complete retained diagnostics; retained diagnostics are not a +ledger of every attempted row. + ### Progress snapshots and observers Enterprise registry handles expose a structured progress snapshot. This @@ -325,7 +503,8 @@ observations; it does not start another polling loop. It is a synchronous observer and is not awaited. If it throws, `wait()` logs the error and continues waiting; callback exceptions do not reject `wait()`. -```python + +```python Python def show_progress(progress): print( progress.get("state"), @@ -342,7 +521,7 @@ if snapshot is not None: result = job.wait(progress=show_progress) ``` -```typescript +```typescript TypeScript const showProgress = (progress: lancedb.JobProgress) => { console.log( progress.state, @@ -361,7 +540,7 @@ if (snapshot !== null) { await job.wait(showProgress); ``` -```rust +```rust Rust let job = table.refresh_column_async("embedding").await?; if let Some(progress) = job.progress().await? { println!( @@ -384,6 +563,7 @@ let result = job }) .await?; ``` + Job-type-specific counters are optional. A missing `rows_computed`, `rows_planned`, or `rows_remaining` field means the server did not report that diff --git a/docs/web/maintenance/cleanup.mdx b/docs/web/maintenance/cleanup.mdx index 8575acba0..07dd432c3 100644 --- a/docs/web/maintenance/cleanup.mdx +++ b/docs/web/maintenance/cleanup.mdx @@ -102,16 +102,16 @@ These restrictions apply to every retention value, including zero. from datetime import timedelta job = table.cleanup_async(min_age_seconds=604800) -print(job.id) # Save this durable ID. +print(job.id()) # Save this durable ID. result = job.wait(timeout=timedelta(minutes=10), progress=print) print(result.old_versions, result.bytes_removed) -reopened = db.open_job(job.id) +reopened = db.open_job(job.id()) ``` ```python Python async icon="python" job = await table.cleanup_async(min_age_seconds=604800) result = await job.wait() -reopened = await db.open_job(job.id) +reopened = await db.open_job(job.id()) ``` ```typescript TypeScript icon="js" diff --git a/nodejs/__test__/job.test.ts b/nodejs/__test__/job.test.ts new file mode 100644 index 000000000..31049f820 --- /dev/null +++ b/nodejs/__test__/job.test.ts @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { Job } from "../lancedb/job"; +import type { Job as NativeJob } from "../lancedb/native"; + +describe("Job attempt contract", () => { + test("preserves lineage and unknown detailed states", async () => { + const inner = { + jobId: "attempt-2", + operationId: "attempt-1", + attempt: 2, + retryOf: "attempt-1", + lifecycleState: "future_publication_state", + sourceTableVersion: 7, + executionEpoch: 3, + status: jest.fn().mockResolvedValue("future_publication_state"), + } as unknown as NativeJob; + const job = new Job(inner); + expect(job.jobId).toBe("attempt-2"); + expect(job.operationId).toBe("attempt-1"); + expect(job.attempt).toBe(2); + expect(job.retryOf).toBe("attempt-1"); + expect(await job.statusTyped()).toBe("future_publication_state"); + expect(job.sourceTableVersion).toBe(7); + expect(job.executionEpoch).toBe(3); + }); + + test("passes wait deadlines through without cancelling execution", async () => { + const wait = jest.fn().mockRejectedValue(new Error("Timeout error")); + const cancel = jest.fn(); + const job = new Job({ wait, cancel } as unknown as NativeJob); + await expect(job.wait({ timeoutMs: 1 })).rejects.toThrow("Timeout"); + expect(wait).toHaveBeenCalledWith(undefined, 1); + expect(cancel).not.toHaveBeenCalled(); + }); + test("retry retains the typed result decoder", async () => { + const successor = { + waitResult: jest.fn().mockResolvedValue({ value: 7 }), + } as unknown as NativeJob; + const inner = { + retry: jest.fn().mockResolvedValue(successor), + } as unknown as NativeJob; + const job = new Job(inner, (value) => (value as { value: number }).value); + const retry = await job.retry(); + expect(await retry.wait()).toBe(7); + }); +}); diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 1576ded54..a77795a56 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -2398,6 +2398,8 @@ describe("remote connection jobs surface", () => { expect(job.result).toBeNull(); expect(job.failure?.message).toEqual("worker died"); expect(await job.progress()).toEqual({ + // biome-ignore lint/style/useNamingConvention: server wire format + job_id: "job-1", // biome-ignore lint/style/useNamingConvention: server wire format job_type: "create_index", state: "failed", diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 2e52732e6..cbdfe2c18 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -2,21 +2,21 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors import { - Connection, + type Connection, LocalConnection, cleanseStorageOptions, } from "./connection"; import { - ConnectNamespaceOptions, - ConnectionOptions, + type ConnectNamespaceOptions, + type ConnectionOptions, Connection as LanceDbConnection, JsHeaderProvider as NativeJsHeaderProvider, - Session, + type Session, tokenize as nativeTokenize, } from "./native.js"; -import { HeaderProvider } from "./header"; +import type { HeaderProvider } from "./header"; import type { BaseTokenizer } from "./indices"; import type { FtsToken } from "./table"; @@ -118,7 +118,12 @@ export { Job, JobEventsOptions, } from "./job"; -export type { JobProgress, JobProgressCallback, JobWaitOptions } from "./job"; +export type { + JobProgress, + JobProgressCallback, + JobState, + JobWaitOptions, +} from "./job"; export { AutoQuery, diff --git a/nodejs/lancedb/job.ts b/nodejs/lancedb/job.ts index aa8e9dc10..c9d9beddd 100644 --- a/nodejs/lancedb/job.ts +++ b/nodejs/lancedb/job.ts @@ -4,7 +4,7 @@ import { Table as ArrowTable, tableFromIPC } from "apache-arrow"; import { decodeCleanupResult } from "./cleanup"; import { decodeCompactionResult } from "./compaction"; -import { JobFailureInfo, Job as NativeJob } from "./native"; +import type { JobFailureInfo, Job as NativeJob } from "./native"; import { decodePrewarmDataResult } from "./prewarm"; /** Which of a job's events {@link Job.events} returns. */ @@ -13,6 +13,8 @@ export interface JobEventsOptions { limit?: number; /** SQL-like filter over the event columns. */ filter?: string; + /** Opaque continuation from the preceding page's schema metadata. */ + pageToken?: string; } /** @@ -93,6 +95,16 @@ export interface JobWaitOptions { /** Observe progress using the same poller that waits for completion. */ onProgress?: JobProgressCallback; } +/** Detailed lifecycle state. Unrecognized future values remain strings. */ +export type JobState = + | "created" + | "queued" + | "in_progress" + | "succeeded" + | "failed" + | "canceled" + | "timed_out" + | (string & {}); /** * A handle to an operation that may still be running. @@ -141,6 +153,56 @@ export class Job { return this.inner.id ?? null; } + /** + * Identity of the selected attempt last observed by this handle. + * For operation handles, `refresh()` or `status()` can select a different + * attempt while `id` stays unchanged. Save this value after refreshing and + * use it throughout paged diagnostics. Local IDs cannot be reopened on a server. + */ + get jobId(): string | null { + return this.inner.jobId ?? null; + } + + /** Root of the explicit retry lineage, when reported. */ + get operationId(): string | null { + return this.inner.operationId ?? null; + } + + /** One-based attempt ordinal. Worker replacement does not increment it. */ + get attempt(): number | null { + return this.inner.attempt ?? null; + } + + /** Immediate predecessor attempt, when reported. */ + get retryOf(): string | null { + return this.inner.retryOf ?? null; + } + + /** Detailed state last observed; unknown values never establish success. */ + get lifecycleState(): JobState | null { + return this.inner.lifecycleState ?? null; + } + + /** Source snapshot pinned for this attempt, when reported. */ + get sourceTableVersion(): number | null { + return this.inner.sourceTableVersion ?? null; + } + + /** Most recent execution's fencing token, when reported. */ + get executionEpoch(): number | null { + return this.inner.executionEpoch ?? null; + } + + /** Refresh and return the detailed lifecycle state. */ + async statusTyped(): Promise { + const state = await this.status(); + if (this.lifecycleState !== null) return this.lifecycleState; + if (state === "running") return "in_progress"; + if (state === "finished") return "succeeded"; + if (state === "cancelled") return "canceled"; + return state; + } + /** The last observed lifecycle state, without contacting the backend. */ get state(): string | null { return this.inner.state ?? null; @@ -277,6 +339,11 @@ export class Job { return this.inner.cancel(); } + /** Select this exact attempt's pinned successor. Requires backend support. */ + async retry(): Promise> { + return new Job(await this.inner.retry(), this.resultDecoder); + } + /** * Ask the backend for this job's current state, and for a server-side job * its full record, then cache it for the getters above. @@ -300,13 +367,33 @@ export class Job { * `updated_by`, `emitted_from`, `emitted_by`, and `claim_entity` columns. */ async events(options?: JobEventsOptions): Promise { - const buf = await this.inner.events(options?.limit, options?.filter); + const buf = await this.inner.events( + options?.limit, + options?.filter, + options?.pageToken, + ); if (buf.length === 0) { return new ArrowTable(); } return tableFromIPC(buf); } + /** Walk retained history one page at a time using the server's continuation. */ + async *history(options?: JobEventsOptions): AsyncGenerator { + let pageToken = options?.pageToken; + for (;;) { + const page = await this.events({ ...options, pageToken }); + yield page; + const next = page.schema.metadata.get( + "lancedb.job_coordinator.page_token", + ); + if (next === undefined) return; + if (next === pageToken) + throw new Error("Job history repeated its page token"); + pageToken = next; + } + } + private lastProgress: JobProgress | null = null; private enrichProgress(progress: Record): JobProgress { diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 15e95caad..cd7c6a469 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -52,6 +52,45 @@ impl Job { self.inner.id().map(str::to_string) } + #[napi(getter)] + pub fn job_id(&self) -> Option { + self.inner.job_id() + } + + #[napi(getter)] + pub fn operation_id(&self) -> Option { + self.inner.operation_id() + } + + #[napi(getter)] + pub fn attempt(&self) -> Option { + self.inner.attempt() + } + + #[napi(getter)] + pub fn retry_of(&self) -> Option { + self.inner.retry_of() + } + + #[napi(getter)] + pub fn lifecycle_state(&self) -> Option { + self.inner + .lifecycle_state() + .map(|state| state.as_str().to_string()) + } + + #[napi(getter)] + pub fn source_table_version(&self) -> Option { + self.inner + .source_table_version() + .map(|version| version as f64) + } + + #[napi(getter)] + pub fn execution_epoch(&self) -> Option { + self.inner.execution_epoch() + } + /// The operation's current lifecycle state: "running", "finished", /// "failed", or "cancelled". /// @@ -137,6 +176,13 @@ impl Job { self.inner.cancel().await.default_error() } + #[napi(catch_unwind)] + pub async fn retry(&self) -> napi::Result { + Ok(Self { + inner: Arc::new(self.inner.retry().await.default_error()?), + }) + } + /// Ask the backend for this job's current state, and for a server-side job /// its full record, then cache it for the getters below. /// @@ -190,10 +236,19 @@ impl Job { /// This job's recorded lifecycle events, as an Arrow IPC stream buffer. /// The TypeScript wrapper turns it into an Arrow table. #[napi(catch_unwind)] - pub async fn events(&self, limit: Option, filter: Option) -> napi::Result { + pub async fn events( + &self, + limit: Option, + filter: Option, + page_token: Option, + ) -> napi::Result { let batches = self .inner - .events(JobEventsRequest { limit, filter }) + .events(JobEventsRequest { + limit, + filter, + page_token, + }) .await .default_error()?; batches_to_ipc_buffer(&batches) diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 5457d727a..3075a7696 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -661,6 +661,7 @@ impl Table { job_id: options.job_id, column: options.column, limit, + page_token: options.page_token, }; let errors = self .inner_ref()? @@ -1845,6 +1846,8 @@ pub struct FunctionErrorsOptions { pub column: Option, /// At most this many records (server default 10000, cap 100000). pub limit: Option, + /// Empty starts retained history, including repaired rows, for an exact jobId; otherwise continue that page. + pub page_token: Option, } /// Aggregate worker resources for one Enterprise Function refresh. @@ -2204,6 +2207,8 @@ pub struct FunctionErrors { pub fragments: Vec, /// Whether the listing stopped at its limit. pub truncated: bool, + /// Continue the same job/filter. Absent for complete pages and older servers. + pub page_token: Option, } /// One exact immutable Function revision attached to a table output. @@ -2322,6 +2327,7 @@ impl From for FunctionErrors { records: errors.records.into_iter().map(Into::into).collect(), fragments: errors.fragments.into_iter().map(Into::into).collect(), truncated: errors.truncated, + page_token: errors.page_token, } } } diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index c845815f2..e368c985d 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -40,7 +40,7 @@ from .remote.db import RemoteDBConnection from .expr import Expr, col, lit, func from .schema import BasePath, blob, blob_uri_array, vector from ._blob_reader import BlobReader as BlobReader -from .job import AsyncJob, Job +from .job import AsyncJob, Job, JobState from .sql import AsyncQuery as AsyncSqlQuery from .sql import Query as SqlQuery from .sql import QueryDescription @@ -701,6 +701,7 @@ __all__ = [ "vector", "DBConnection", "Job", + "JobState", "QueryDescription", "SqlQuery", "LanceDBConnection", diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 7af833c79..a930728d7 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -439,6 +439,20 @@ class BlobFile: def read_up_to(self, length: int) -> bytes: ... class Job: + @property + def job_id(self) -> Optional[str]: ... + @property + def operation_id(self) -> Optional[str]: ... + @property + def attempt(self) -> Optional[int]: ... + @property + def retry_of(self) -> Optional[str]: ... + @property + def lifecycle_state(self) -> Optional[str]: ... + @property + def source_table_version(self) -> Optional[int]: ... + @property + def execution_epoch(self) -> Optional[int]: ... @property def id(self) -> Optional[str]: ... @property @@ -453,6 +467,7 @@ class Job: progress: Optional[Callable[[dict[str, Any]], None]] = None, ) -> Optional[str]: ... async def cancel(self) -> None: ... + async def retry(self) -> Job: ... async def refresh(self) -> None: ... async def timeline(self) -> str: ... async def stack(self, worker_id: str) -> str: ... @@ -462,6 +477,7 @@ class Job: *, limit: Optional[int] = None, filter: Optional[str] = None, + page_token: Optional[str] = None, ) -> pa.Table: ... class JobInfo: @@ -526,6 +542,18 @@ class JobFailureInfo: def sql_job_id(self) -> Optional[str]: ... class JobDescription: + @property + def operation_id(self) -> Optional[str]: ... + @property + def attempt(self) -> Optional[int]: ... + @property + def retry_of(self) -> Optional[str]: ... + @property + def lifecycle_state(self) -> Optional[str]: ... + @property + def source_table_version(self) -> Optional[int]: ... + @property + def execution_epoch(self) -> Optional[int]: ... @property def job_id(self) -> str: ... @property @@ -766,6 +794,7 @@ class Table: column: Optional[str] = None, limit: Optional[int] = None, history: bool = False, + page_token: Optional[str] = None, ) -> FunctionErrors: ... async def quarantine_function_errors( self, @@ -1250,6 +1279,7 @@ class FunctionErrorRecord: input: Optional[str] attempts: Optional[int] job_id: str + attempt_job_id: Optional[str] fragment_id: int row_offset: Optional[int] row_id: Optional[int] @@ -1273,6 +1303,8 @@ class FunctionErrorFragment: class FunctionErrors: workflow_version: Optional[int] error_groups_json: str + @property + def page_token(self) -> Optional[str]: ... records: list[FunctionErrorRecord] fragments: list[FunctionErrorFragment] truncated: bool diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 18403c75d..ab8c66b22 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1176,6 +1176,7 @@ class _FunctionErrors: self.records = raw.records self.fragments = raw.fragments self.truncated = raw.truncated + self.page_token = getattr(raw, "page_token", None) def __repr__(self) -> str: return repr(self._raw) diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index b3a6e527f..7ea2151b6 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -10,9 +10,20 @@ import reprlib import time from contextlib import suppress from datetime import timedelta +from enum import Enum from os import PathLike from pathlib import Path -from typing import Any, Callable, Generic, Optional, TypeVar, cast +from typing import ( + Any, + AsyncIterator, + Callable, + Generic, + Iterator, + Optional, + TypeVar, + cast, +) +from uuid import uuid4 import pyarrow as pa @@ -34,9 +45,49 @@ __all__ = [ "JobDescription", "JobFailureInfo", "JobInfo", + "JobState", ] +class JobState(str, Enum): + """Detailed lifecycle of one attempt, retaining unknown future values.""" + + CREATED = "created" + QUEUED = "queued" + IN_PROGRESS = "in_progress" + SUCCEEDED = "succeeded" + FAILED = "failed" + CANCELED = "canceled" + TIMED_OUT = "timed_out" + + @classmethod + def _missing_(cls, value): + if not isinstance(value, str): + return None + aliases = { + "running": cls.IN_PROGRESS, + "finished": cls.SUCCEEDED, + "cancelled": cls.CANCELED, + } + if value in aliases: + return aliases[value] + member = str.__new__(cls, value) + member._name_ = None + member._value_ = value + return member + + @property + def is_terminal(self) -> bool: + return self in (self.SUCCEEDED, self.FAILED, self.CANCELED, self.TIMED_OUT) + + @property + def is_success(self) -> bool: + return self == self.SUCCEEDED + + def __str__(self) -> str: + return self.value + + def _timeout_message( job_id: Optional[str], timeout: timedelta, job_type: Optional[str] ) -> str: @@ -45,7 +96,7 @@ def _timeout_message( if job_id is None: return ( f"operation still running after {seconds} {unit}; " - "it continues on the server" + "keep this handle to continue waiting" ) if job_type == "query": return ( @@ -231,6 +282,7 @@ class AsyncJob(Generic[T]): self._result_decoder = result_decoder self._last_progress_snapshot = None self._created_at = time.monotonic() + self._local_job_id = str(uuid4()) if inner is None else None def _enrich_progress(self, snapshot): enriched = _with_progress_eta(self._last_progress_snapshot, snapshot) @@ -263,6 +315,54 @@ class AsyncJob(Generic[T]): return "finished" return await self._inner.status() + def job_id(self) -> Optional[str]: + """Identity of the selected attempt last observed by this handle. + + For operation handles, ``refresh()`` or ``status()`` can select a + different attempt while ``id()`` stays unchanged. Save this value after + refreshing and use it throughout paged diagnostics. Embedded IDs cannot + be reopened on a server. + """ + return ( + getattr(self._inner, "job_id", self.id()) + if self._inner is not None + else self._local_job_id + ) + + def operation_id(self) -> Optional[str]: + """Root of the explicit retry lineage, when known.""" + return ( + getattr(self._inner, "operation_id", None) + if self._inner is not None + else self._local_job_id + ) + + def attempt(self) -> Optional[int]: + """One-based attempt ordinal; worker replacement does not increment it.""" + return getattr(self._inner, "attempt", None) if self._inner is not None else 1 + + def retry_of(self) -> Optional[str]: + """Immediate predecessor attempt, when supplied by the backend.""" + return getattr(self._inner, "retry_of", None) + + def lifecycle_state(self) -> Optional[JobState]: + """Detailed state last observed; unknown values never imply success.""" + raw = getattr(self._inner, "lifecycle_state", None) or self.state() + return JobState(raw) if raw is not None else None + + async def status_typed(self) -> JobState: + """Refresh and return the detailed, forward-compatible lifecycle state.""" + state = await self.status() + return self.lifecycle_state() or JobState(state) + + def source_table_version(self) -> Optional[int]: + """Source snapshot pinned for this attempt, when reported.""" + return getattr(self._inner, "source_table_version", None) + + def execution_epoch(self) -> Optional[int]: + """Most recent execution's fencing token, when reported.""" + return getattr(self._inner, "execution_epoch", None) + async def progress(self) -> Optional[dict[str, Any]]: """Fetch a structured progress snapshot. @@ -446,6 +546,18 @@ class AsyncJob(Generic[T]): return await self._inner.cancel() + async def retry(self) -> "AsyncJob[T]": + """Select a successor for this exact failed attempt using pinned inputs. + + Repeated requests select the same successor even after it finishes. + Requires a supporting server and a safely retryable Function job. + In-process operations do not retain a replayable specification and + raise ``NotImplementedError``. + """ + if self._inner is None: + raise NotImplementedError("retry requires a registry-backed job") + return AsyncJob(await self._inner.retry(), self._result_decoder) + async def refresh(self) -> None: """Ask the backend for this job's current state, and for a server-side job its full record, then cache it for the read methods below. @@ -644,6 +756,7 @@ class AsyncJob(Generic[T]): *, limit: Optional[int] = None, filter: Optional[str] = None, + page_token: Optional[str] = None, ) -> "pa.Table": """This job's recorded lifecycle events. @@ -675,7 +788,29 @@ class AsyncJob(Generic[T]): "jobs", ) ) - return await self._inner.events(limit=limit, filter=filter) + if page_token is None: + return await self._inner.events(limit=limit, filter=filter) + return await self._inner.events( + limit=limit, filter=filter, page_token=page_token + ) + + async def history( + self, *, limit: Optional[int] = None, filter: Optional[str] = None + ) -> AsyncIterator["pa.Table"]: + """Walk retained history in pages, following opaque server continuations.""" + token = None + while True: + page = await self.events(limit=limit, filter=filter, page_token=token) + yield page + next_token = (page.schema.metadata or {}).get( + b"lancedb.job_coordinator.page_token" + ) + if next_token is None: + return + next_token = next_token.decode() + if next_token == token: + raise RuntimeError("job history repeated its page token") + token = next_token def __repr__(self) -> str: return _job_repr("AsyncJob", self) @@ -738,7 +873,62 @@ class Job(Generic[T]): """ def __init__(self, inner: Optional[AsyncJob[T]]): - self._inner = inner + self._inner = inner if inner is not None else AsyncJob(None) + + def job_id(self) -> Optional[str]: + """Selected attempt ID; refresh can change it while ``id()`` stays fixed. + + Save the value after refreshing for paged diagnostics. + See [AsyncJob.job_id()][lancedb.job.AsyncJob.job_id]. + """ + return self._inner.job_id() + + def operation_id(self) -> Optional[str]: + """Root retry identity. + + See [AsyncJob.operation_id()][lancedb.job.AsyncJob.operation_id]. + """ + return self._inner.operation_id() + + def attempt(self) -> Optional[int]: + """One-based attempt ordinal. + + See [AsyncJob.attempt()][lancedb.job.AsyncJob.attempt]. + """ + return self._inner.attempt() + + def retry_of(self) -> Optional[str]: + """Immediate predecessor. + + See [AsyncJob.retry_of()][lancedb.job.AsyncJob.retry_of]. + """ + return self._inner.retry_of() + + def lifecycle_state(self) -> Optional[JobState]: + """Detailed state last observed. + + See [AsyncJob.lifecycle_state()][lancedb.job.AsyncJob.lifecycle_state]. + """ + return self._inner.lifecycle_state() + + def status_typed(self) -> JobState: + """Refresh the detailed lifecycle state. See :meth:`AsyncJob.status_typed`.""" + return LOOP.run(self._inner.status_typed()) + + def source_table_version(self) -> Optional[int]: + """Pinned source snapshot. + + See the async handle's + [source_table_version()][lancedb.job.AsyncJob.source_table_version]. + """ + return self._inner.source_table_version() + + def execution_epoch(self) -> Optional[int]: + """Execution fencing token. + + See [AsyncJob.execution_epoch()][lancedb.job.AsyncJob.execution_epoch]. + """ + return self._inner.execution_epoch() def id(self) -> Optional[str]: """Return the operation's opaque server ID without a backend call. @@ -800,6 +990,10 @@ class Job(Generic[T]): return LOOP.run(self._inner.cancel()) + def retry(self) -> "Job[T]": + """Select this attempt's pinned successor. See :meth:`AsyncJob.retry`.""" + return Job(LOOP.run(self._inner.retry())) + def refresh(self) -> None: """Ask the backend for this job's current state and record. @@ -954,6 +1148,7 @@ class Job(Generic[T]): *, limit: Optional[int] = None, filter: Optional[str] = None, + page_token: Optional[str] = None, ) -> "pa.Table": """This job's recorded lifecycle events. @@ -966,7 +1161,20 @@ class Job(Generic[T]): "jobs", ) ) - return LOOP.run(self._inner.events(limit=limit, filter=filter)) + return LOOP.run( + self._inner.events(limit=limit, filter=filter, page_token=page_token) + ) + + def history( + self, *, limit: Optional[int] = None, filter: Optional[str] = None + ) -> Iterator["pa.Table"]: + """Walk retained history in pages. See :meth:`AsyncJob.history`.""" + pages = self._inner.history(limit=limit, filter=filter) + try: + while (page := LOOP.run(anext(pages, None))) is not None: + yield page + finally: + LOOP.run(pages.aclose()) def __repr__(self) -> str: return _job_repr("Job", self) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 4fe2c3175..b96a3c80e 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1334,10 +1334,15 @@ class RemoteTable(Table): column: Optional[str] = None, limit: Optional[int] = None, history: bool = False, + page_token: Optional[str] = None, ): return LOOP.run( self._table.function_errors( - job_id=job_id, column=column, limit=limit, history=history + job_id=job_id, + column=column, + limit=limit, + history=history, + page_token=page_token, ) ).as_sync(self) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 73e8d58a7..71688a56e 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -3272,7 +3272,7 @@ class Table(ABC): The server does not enforce coordination. Cancellation cannot undo deletion or prove storage I/O stopped. Preview is available without deletion. - Save ``job.id`` to reopen with ``db.open_job(id)``. Waiting returns + Save ``job.id()`` to reopen with ``db.open_job(id)``. Waiting returns [CleanupResult][lancedb.cleanup.CleanupResult]; timeout leaves work running. Unknown totals after retry/recovery remain None. Auxiliary sweeps are best effort and excluded from the version-deletion counts. @@ -3952,6 +3952,7 @@ class Table(ABC): column: Optional[str] = None, limit: Optional[int] = None, history: bool = False, + page_token: Optional[str] = None, ) -> "FunctionErrors": """ The per-row errors Function refreshes recorded on this table. @@ -3977,6 +3978,10 @@ class Table(ABC): Include retained historical errors instead of current failures. Requires Enterprise workflow version 1 or later. Historical records cannot be used with the current-input ``rows()`` helper. + page_token: str, optional + Empty starts retained history, including repaired rows, for an exact + job_id. Continue with the response's + page_token until it is None, keeping all filters unchanged. Returns ------- @@ -6621,12 +6626,17 @@ class LanceTable(Table): column: Optional[str] = None, limit: Optional[int] = None, history: bool = False, + page_token: Optional[str] = None, ) -> "FunctionErrors": """The per-row errors Function refreshes recorded on this table. See [`Table.function_errors`][lancedb.table.Table.function_errors].""" return LOOP.run( self._table.function_errors( - job_id=job_id, column=column, limit=limit, history=history + job_id=job_id, + column=column, + limit=limit, + history=history, + page_token=page_token, ) ).as_sync(self) @@ -9435,6 +9445,7 @@ class AsyncTable: column: Optional[str] = None, limit: Optional[int] = None, history: bool = False, + page_token: Optional[str] = None, ) -> "AsyncFunctionErrors": """ The per-row errors Function refreshes recorded on this table. @@ -9460,6 +9471,10 @@ class AsyncTable: Include retained historical errors instead of current failures. Requires Enterprise workflow version 1 or later. Historical records cannot be used with the current-input ``rows()`` helper. + page_token: str, optional + Empty starts retained history, including repaired rows, for an exact + job_id. Continue with the response's + page_token until it is None, keeping all filters unchanged. Returns ------- @@ -9522,9 +9537,13 @@ class AsyncTable: ... print("listing stopped at the limit") """ raw = await self._inner.function_errors( - job_id=job_id, column=column, limit=limit, history=history + job_id=job_id, + column=column, + limit=limit, + history=history, + page_token=page_token, ) - return AsyncFunctionErrors(raw, self, history=history) + return AsyncFunctionErrors(raw, self, history=history or page_token is not None) async def column_statuses( self, column: Optional[str] = None diff --git a/python/python/tests/test_cleanup.py b/python/python/tests/test_cleanup.py index 4d7c285dd..944594b21 100644 --- a/python/python/tests/test_cleanup.py +++ b/python/python/tests/test_cleanup.py @@ -114,7 +114,7 @@ async def test_cleanup_submission_wait_and_reopen(asynchronous, outcome): db = lancedb.connect(**kwargs) table = db.create_table("test", [{"id": 1}]) job = table.cleanup_async(min_age_seconds=0) - assert job.id == "cleanup-job" and not polls + assert job.id() == "cleanup-job" and not polls if outcome in ("missing", "FAILED", "CANCELLED"): with pytest.raises( Exception, @@ -133,7 +133,7 @@ async def test_cleanup_submission_wait_and_reopen(asynchronous, outcome): assert isinstance(stats, CleanupResult) assert stats.old_versions == result["old_versions"] reopened = ( - await db.open_job(job.id) if asynchronous else db.open_job(job.id) + await db.open_job(job.id()) if asynchronous else db.open_job(job.id()) ) assert (await reopened.wait() if asynchronous else reopened.wait()) == stats assert len(server.tickets) == 1 diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index 6113277a7..611d9b72b 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -9,10 +9,11 @@ from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock import pytest +import pyarrow as pa from lancedb.exceptions import JobCancelledError, JobFailedError from lancedb.db import DBConnection -from lancedb.job import AsyncJob, Job, _progress_eta +from lancedb.job import AsyncJob, Job, JobState, _progress_eta from lancedb.remote.errors import HttpError, RetryError @@ -69,17 +70,30 @@ async def test_job_checkout_latest_refreshes_the_complete_snapshot( creation_ms=2000, spec=spec, result=result, failure=failure ) inner = SimpleNamespace( - _state=None, _description=None, job_type=None, status=AsyncMock() + id="operation-1", + _state=None, + _description=None, + job_type=None, + status=AsyncMock(), ) async def observe(): inner._state = state inner.job_type = "refresh_column" inner._description = description + inner.job_id = "attempt-2" + inner.operation_id = "operation-1" + inner.attempt = 2 + inner.retry_of = "attempt-1" + inner.lifecycle_state = str(JobState(state)) + inner.source_table_version = 7 + inner.execution_epoch = 3 inner.refresh = AsyncMock(side_effect=observe) job, call = job_snapshot(inner) assert job.state() is None + assert job.job_id() == "operation-1" + assert job.lifecycle_state() is None assert job.job_type() is None assert job.creation_ms() is None assert job.spec() is None @@ -94,6 +108,14 @@ async def test_job_checkout_latest_refreshes_the_complete_snapshot( assert job.spec() is spec assert job.result() is result assert job.failure() is failure + assert job.id() == "operation-1" + assert job.job_id() == "attempt-2" + assert job.operation_id() == "operation-1" + assert job.attempt() == 2 + assert job.retry_of() == "attempt-1" + assert job.lifecycle_state() == JobState(state) + assert job.source_table_version() == 7 + assert job.execution_epoch() == 3 inner.refresh.assert_awaited_once_with() inner.status.assert_not_called() @@ -151,6 +173,38 @@ async def test_job_checkout_latest_for_completed_local_jobs(job_snapshot): assert Job(None).checkout_latest() is None +@pytest.mark.parametrize("sync", [False, True]) +def test_local_jobs_retain_identity_and_typed_state(sync): + job = AsyncJob(None) + if sync: + job = Job(job) + assert job.job_id() == job.operation_id() + assert job.job_id() == job.job_id() + assert job.attempt() == 1 + assert job.retry_of() is None + assert job.lifecycle_state() is JobState.SUCCEEDED + + +def test_unknown_job_state_is_preserved_without_becoming_success(): + state = JobState("future_publication_state") + assert state.value == "future_publication_state" + assert str(state) == "future_publication_state" + assert not state.is_terminal + assert not state.is_success + + +@pytest.mark.asyncio +async def test_history_follows_page_tokens(): + first = pa.table({"event_seq": [2, 1]}).replace_schema_metadata( + {b"lancedb.job_coordinator.page_token": b"next"} + ) + last = pa.table({"event_seq": [0]}) + inner = SimpleNamespace(events=AsyncMock(side_effect=[first, last])) + pages = [page async for page in AsyncJob(inner).history(limit=2)] + assert [page["event_seq"].to_pylist() for page in pages] == [[2, 1], [0]] + assert inner.events.call_args_list[1].kwargs["page_token"] == "next" + + @pytest.mark.parametrize("sync", [False, True]) def test_job_repr_bounds_large_payloads_without_fetching(sync): spec = {"initialization": list(range(100000)), "source": "x" * 100000} diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 8bb3a1ce0..4e531262d 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -9034,3 +9034,47 @@ def test_remote_prewarm_preview_reports_old_server_format_support(): ): table.explain_prewarm_data() assert len(server.tickets) == 1 + + +@pytest.mark.parametrize("async_table", [False, True]) +@pytest.mark.asyncio +async def test_paged_function_errors_retain_history_and_expose_continuation( + async_table, +): + received = [] + + def handler(request): + length = int(request.headers.get("content-length", 0)) + body = json.loads(request.rfile.read(length)) if length else {} + if request.path == "/v1/table/test/describe/": + response = {"version": 8, "schema": {"fields": []}} + else: + assert request.path == "/v1/table/test/errors" + received.append(body) + response = { + "records": [], + "fragments": [], + "truncated": False, + "workflow_version": 1, + "page_token": "next", + } + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + if async_table: + async with mock_lancedb_connection_async(handler) as db: + table = await db.open_table("test") + errors = await table.function_errors(job_id="attempt-1", page_token="") + assert errors.page_token == "next" + with pytest.raises(ValueError, match="current failures"): + await errors.rows() + else: + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + errors = table.function_errors(job_id="attempt-1", page_token="") + assert errors.page_token == "next" + with pytest.raises(ValueError, match="current failures"): + errors.rows() + assert received == [{"job_id": "attempt-1", "page_token": "", "history": True}] diff --git a/python/src/job.rs b/python/src/job.rs index 7e4c13f41..fdaa67ba6 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -81,6 +81,43 @@ impl Job { self.inner.id().map(str::to_string) } + #[getter] + pub fn job_id(&self) -> Option { + self.inner.job_id() + } + + #[getter] + pub fn operation_id(&self) -> Option { + self.inner.operation_id() + } + + #[getter] + pub fn attempt(&self) -> Option { + self.inner.attempt() + } + + #[getter] + pub fn retry_of(&self) -> Option { + self.inner.retry_of() + } + + #[getter] + pub fn lifecycle_state(&self) -> Option { + self.inner + .lifecycle_state() + .map(|state| state.as_str().to_string()) + } + + #[getter] + pub fn source_table_version(&self) -> Option { + self.inner.source_table_version() + } + + #[getter] + pub fn execution_epoch(&self) -> Option { + self.inner.execution_epoch() + } + #[getter] pub fn job_type(&self) -> Option { self.inner.job_type() @@ -132,6 +169,15 @@ impl Job { }) } + pub fn retry(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + Ok(Job { + inner: Arc::new(inner.retry().await.infer_error()?), + }) + }) + } + pub fn refresh(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -171,14 +217,19 @@ impl Job { future_into_py(self_.py(), async move { inner.stats().await.infer_error() }) } - #[pyo3(signature = (*, limit=None, filter=None))] + #[pyo3(signature = (*, limit=None, filter=None, page_token=None))] pub fn events( self_: PyRef<'_, Self>, limit: Option, filter: Option, + page_token: Option, ) -> PyResult> { let inner = self_.inner.clone(); - let request = JobEventsRequest { limit, filter }; + let request = JobEventsRequest { + limit, + filter, + page_token, + }; future_into_py(self_.py(), async move { let batches = inner.events(request).await.infer_error()?; Python::attach(|py| { @@ -301,6 +352,13 @@ impl JobFailureInfo { #[derive(Clone)] pub struct JobDescription { job_id: String, + attempt_job_id: Option, + operation_id: Option, + attempt: Option, + retry_of: Option, + lifecycle_state: Option, + source_table_version: Option, + execution_epoch: Option, job_type: String, state: String, creation_ms: i64, @@ -363,6 +421,15 @@ impl From for JobDescription { let progress_json = description.progress_snapshot().to_string(); Self { job_id: description.job_id, + attempt_job_id: description.attempt_job_id, + operation_id: description.operation_id, + attempt: description.attempt, + retry_of: description.retry_of, + lifecycle_state: description + .lifecycle_state + .map(|state| state.as_str().to_string()), + source_table_version: description.source_table_version, + execution_epoch: description.execution_epoch, job_type: description.job_type, state: description.state, creation_ms: description.creation_ms, diff --git a/python/src/table.rs b/python/src/table.rs index 7b92eab27..74f17f724 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1014,6 +1014,7 @@ pub struct FunctionErrors { pub records: Vec, pub fragments: Vec, pub truncated: bool, + pub page_token: Option, } #[pymethods] @@ -1037,6 +1038,7 @@ impl From for FunctionErrors { records: errors.records.into_iter().map(Into::into).collect(), fragments: errors.fragments.into_iter().map(Into::into).collect(), truncated: errors.truncated, + page_token: errors.page_token, } } } @@ -2914,13 +2916,14 @@ impl Table { }) } - #[pyo3(signature = (job_id=None, column=None, limit=None, history=false))] + #[pyo3(signature = (job_id=None, column=None, limit=None, history=false, page_token=None))] pub fn function_errors( self_: PyRef<'_, Self>, job_id: Option, column: Option, limit: Option, history: bool, + page_token: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); let request = lancedb::function::FunctionErrorsRequest { @@ -2928,6 +2931,7 @@ impl Table { column, limit, history, + page_token, }; future_into_py(self_.py(), async move { let errors = inner.function_errors(request).await.infer_error()?; diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 8a7a941f6..d53383ce5 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -326,6 +326,20 @@ impl JobInfo { #[derive(Debug, Clone)] pub struct JobDescription { pub job_id: String, + /// Exact selected attempt when job_id is a durable operation handle. + pub attempt_job_id: Option, + /// Root identity shared by the explicit retry lineage, when reported. + pub operation_id: Option, + /// One-based attempt ordinal, when reported. + pub attempt: Option, + /// Immediate predecessor attempt, when reported. + pub retry_of: Option, + /// Detailed state before folding it into legacy client labels. + pub lifecycle_state: Option, + /// Pinned source snapshot, when reported. + pub source_table_version: Option, + /// Most recent execution's fencing token, when reported. + pub execution_epoch: Option, pub job_type: String, /// Lifecycle state: "running", "finished", "failed", or "cancelled". pub state: String, @@ -385,6 +399,28 @@ impl JobDescription { snapshot.insert(key.clone(), value.clone()); } } + if let Some(operation_id) = &self.operation_id { + snapshot.insert("operation_id".to_string(), operation_id.clone().into()); + } + snapshot.insert("job_id".to_string(), self.job_id.clone().into()); + if let Some(attempt_job_id) = &self.attempt_job_id { + snapshot.insert("attempt_job_id".to_string(), attempt_job_id.clone().into()); + } + if let Some(attempt) = self.attempt { + snapshot.insert("attempt".to_string(), attempt.into()); + } + if let Some(retry_of) = &self.retry_of { + snapshot.insert("retry_of".to_string(), retry_of.clone().into()); + } + if let Some(state) = &self.lifecycle_state { + snapshot.insert("lifecycle_state".to_string(), state.as_str().into()); + } + if let Some(version) = self.source_table_version { + snapshot.insert("source_table_version".to_string(), version.into()); + } + if let Some(epoch) = self.execution_epoch { + snapshot.insert("execution_epoch".to_string(), epoch.into()); + } serde_json::Value::Object(snapshot) } } diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index e4fff29c5..db58afa99 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -1345,6 +1345,9 @@ pub struct FunctionErrorsRequest { /// At most this many records; the server default is 10000 and its cap /// 100000. [`FunctionErrors::truncated`] says whether the cap was hit. pub limit: Option, + /// Empty starts retained history for an exact job_id, including repaired rows. + /// A returned token continues that history regardless of `history`. + pub page_token: Option, } impl FunctionErrorsRequest { @@ -1375,6 +1378,13 @@ impl FunctionErrorsRequest { self.limit = Some(limit); self } + + /// Start with an empty token, then continue using the response's token. + /// Paging requires an exact job_id and a supporting backend. + pub fn page_token(mut self, token: impl Into) -> Self { + self.page_token = Some(token.into()); + self + } } /// One row a Function refresh skipped, as the server recorded it. The @@ -1468,6 +1478,10 @@ pub struct FunctionErrors { /// Whether the listing stopped at its limit. #[serde(default)] pub truncated: bool, + /// Continue this exact job/filter, or `None` when a paged read is complete. + /// Older servers and legacy non-paged reads omit this field. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub page_token: Option, } /// Which existing rows to recompute when upgrading a Function column. diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 14170d43c..fef2431d9 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -20,6 +20,12 @@ use crate::database::JobDescription; use crate::docs::DocLink; use crate::error::{Error, JobFailure, Result}; +mod state; +pub use state::JobState; + +/// Arrow schema metadata carrying the next retained event page. +pub const JOB_EVENT_PAGE_TOKEN_METADATA_KEY: &str = "lancedb.job_coordinator.page_token"; + /// Observer called with each description fetched by a job's existing wait /// poller. Keeping this callback on the poller avoids a second lifecycle or /// retry loop just to render progress. @@ -82,6 +88,8 @@ pub struct JobEventsRequest { /// `emitted_from`, `emitted_by`, and `claim_entity`. For example /// `state = 'claim_complete'` selects only per-claim completions. pub filter: Option, + /// Opaque continuation from the preceding page's Arrow schema metadata. + pub page_token: Option, } impl JobEventsRequest { @@ -94,6 +102,22 @@ impl JobEventsRequest { self.filter = Some(filter.into()); self } + + /// Continue a previous page without deriving a cursor from its row count. + pub fn page_token(mut self, token: impl Into) -> Self { + self.page_token = Some(token.into()); + self + } +} + +/// The continuation returned with one event page. Absence means the page is complete. +pub fn job_event_page_token(batches: &[RecordBatch]) -> Option<&str> { + batches + .first()? + .schema_ref() + .metadata() + .get(JOB_EVENT_PAGE_TOKEN_METADATA_KEY) + .map(String::as_str) } fn job_detail_not_supported(what: &str) -> Result { @@ -123,6 +147,9 @@ pub(crate) trait JobHandle: Send + Sync { self.wait().await } async fn cancel(&self) -> Result<()>; + async fn retry(&self) -> Result> { + job_detail_not_supported("retrying a job") + } /// The job's full server-side record. Backends that run the operation in /// this process have none and keep the default. async fn describe(&self) -> Result { @@ -239,7 +266,9 @@ enum JobInner { #[derive(Default)] struct JobCache { state: Option, + lifecycle_state: Option, description: Option, + local_operation_id: Option, } /// A handle to an operation that may still be running. @@ -302,7 +331,9 @@ impl Job<()> { inner: JobInner::Completed(()), cache: RwLock::new(JobCache { state: Some("finished".to_string()), + lifecycle_state: Some(JobState::Succeeded), description: None, + local_operation_id: Some(Uuid::new_v4().to_string()), }), } } @@ -325,6 +356,12 @@ impl Job<()> { { let mut cache = job.cache_write(); cache.state = Some(description.state.clone()); + cache.lifecycle_state = Some( + description + .lifecycle_state + .clone() + .unwrap_or_else(|| JobState::from(description.state.as_str())), + ); cache.description = Some(description); } job @@ -389,7 +426,9 @@ where { /// A typed job running as a task in this process. pub(crate) fn spawned(task: JoinHandle>) -> Self { - Self::new_typed(Box::new(SpawnedJob::new(task))) + let job = Self::new_typed(Box::new(SpawnedJob::new(task))); + job.cache_write().local_operation_id = Some(Uuid::new_v4().to_string()); + job } pub(crate) fn from_query_task( @@ -402,11 +441,13 @@ where Fut: Future> + Send + 'static, { let cancellation: Cancellation = Arc::new(move || Box::pin(cancel())); - Self::new_typed(Box::new(SpawnedJob::new_with_cancellation( + let job = Self::new_typed(Box::new(SpawnedJob::new_with_cancellation( query_id, task, cancellation, - ))) + ))); + job.cache_write().local_operation_id = Some(query_id.to_string()); + job } } @@ -454,13 +495,21 @@ where let state = description.state.clone(); let mut cache = self.cache_write(); cache.state = Some(state.clone()); + cache.lifecycle_state = Some( + description + .lifecycle_state + .clone() + .unwrap_or_else(|| JobState::from(state.as_str())), + ); cache.description = Some(description); Ok(state) } // An in-process job knows its own state and nothing more. Err(Error::NotSupported { .. }) => { let state = handle.status().await?; - self.cache_write().state = Some(state.clone()); + let mut cache = self.cache_write(); + cache.state = Some(state.clone()); + cache.lifecycle_state = Some(JobState::from(state.as_str())); Ok(state) } Err(err) => Err(err), @@ -493,6 +542,73 @@ where self.cache_read().state.clone() } + /// Detailed state last observed, preserving unknown future server values. + /// Local operations use the same typed states; legacy `state()` is unchanged. + pub fn lifecycle_state(&self) -> Option { + let cache = self.cache_read(); + cache + .lifecycle_state + .clone() + .or_else(|| cache.state.as_deref().map(JobState::from)) + } + + /// Refresh the state and return its forward-compatible typed form. + pub async fn status_typed(&self) -> Result { + self.refresh_state().await?; + Ok(self.lifecycle_state().expect("refresh records a state")) + } + + /// Identity of the selected attempt last observed by this handle. + /// For operation handles, [`Self::refresh`] or [`Self::status`] can select a + /// different attempt while [`Self::id`] stays unchanged. Save the returned + /// ID after refreshing and use that value throughout paged diagnostics. + /// Local identities cannot be passed to `Connection::open_job` and last + /// for the lifetime of this handle. + pub fn job_id(&self) -> Option { + self.with_description(|description| description.attempt_job_id.clone()) + .flatten() + .or_else(|| self.id().map(str::to_string)) + .or_else(|| self.cache_read().local_operation_id.clone()) + } + + /// Root of this attempt's explicit retry lineage. Older servers may omit it. + pub fn operation_id(&self) -> Option { + let cache = self.cache_read(); + cache + .description + .as_ref() + .and_then(|description| description.operation_id.clone()) + .or_else(|| cache.local_operation_id.clone()) + } + + /// One-based retry attempt. Worker replacement does not increment it. + pub fn attempt(&self) -> Option { + let cache = self.cache_read(); + cache + .description + .as_ref() + .and_then(|description| description.attempt) + .or_else(|| cache.local_operation_id.as_ref().map(|_| 1)) + } + + /// Immediate predecessor attempt, when supplied by the backend. + pub fn retry_of(&self) -> Option { + self.with_description(|description| description.retry_of.clone()) + .flatten() + } + + /// Source snapshot pinned for this attempt, when supplied by the backend. + pub fn source_table_version(&self) -> Option { + self.with_description(|description| description.source_table_version) + .flatten() + } + + /// Most recent execution's fencing token, when supplied by the backend. + pub fn execution_epoch(&self) -> Option { + self.with_description(|description| description.execution_epoch) + .flatten() + } + /// The whole server-side record this handle last observed. The accessors /// below read individual fields out of it. `None` for an in-process job, /// which has no such record. @@ -561,6 +677,32 @@ where } } + /// Collect retained event pages, following the backend's opaque cursors. + /// `limit` is the size of each page; it is not a total history limit. + pub async fn history(&self, mut request: JobEventsRequest) -> Result> { + let mut batches = Vec::new(); + loop { + let page = self.events(request.clone()).await?; + let next = job_event_page_token(&page).map(str::to_string); + let done = next.is_none(); + if next.is_some() && next == request.page_token { + return Err(Error::Runtime { + message: "job history repeated its page token".to_string(), + }); + } + batches.extend(page); + if done { + for batch in &mut batches { + batch + .schema_metadata_mut() + .remove(JOB_EVENT_PAGE_TOKEN_METADATA_KEY); + } + return Ok(batches); + } + request.page_token = next; + } + } + /// Fetch a recorded Function job timeline as Chrome Trace Event JSON. /// /// The snapshot opens in Perfetto or Chrome tracing. It contains retained @@ -707,11 +849,35 @@ where async fn wait_with_progress_opt(&self, progress: Option) -> Result { match &self.inner { JobInner::Handle { handle, decode } => { - let settled = handle.wait_with_progress(progress).await; + let observed_state = Arc::new(Mutex::new(None)); + let observed = observed_state.clone(); + let observer: JobProgressCallback = + Arc::new(Mutex::new(move |description: &JobDescription| { + *observed.lock().unwrap() = Some( + description + .lifecycle_state + .clone() + .unwrap_or_else(|| JobState::from(description.state.as_str())), + ); + if let Some(progress) = &progress + && let Ok(mut callback) = progress.lock() + { + callback(description); + } + })); + let settled = handle.wait_with_progress(Some(observer)).await; // Waiting already established a terminal state; record it so // the detail accessors do not need another round trip for it. if let Some(state) = terminal_state(&settled) { - self.cache_write().state = Some(state.to_string()); + let mut cache = self.cache_write(); + cache.state = Some(state.to_string()); + cache.lifecycle_state = Some( + observed_state + .lock() + .unwrap() + .take() + .unwrap_or_else(|| JobState::from(state)), + ); } (decode)(settled?) } @@ -732,6 +898,23 @@ where } } + /// Select a successor for this exact unsuccessful attempt. The backend + /// copies pinned inputs and coalesces repeated requests; it does not resolve + /// a newer Function alias. In-process operations cannot be retried because + /// they do not retain a replayable operation specification. + pub async fn retry(&self) -> Result { + match &self.inner { + JobInner::Handle { handle, decode } => Ok(Self { + inner: JobInner::Handle { + handle: handle.retry().await?, + decode: decode.clone(), + }, + cache: RwLock::default(), + }), + JobInner::Completed(_) => job_detail_not_supported("retrying a job"), + } + } + /// Maps a successful terminal result without changing the job lifecycle. /// The mapping may run once for each call to [`Job::wait`], so it should /// be deterministic and free of externally visible side effects. @@ -1015,6 +1198,58 @@ mod tests { )); } + struct HistoryPages(Arc>>>); + + #[async_trait] + impl JobHandle for HistoryPages { + async fn status(&self) -> Result { + Ok("running".to_string()) + } + async fn wait(&self) -> Result { + pending().await + } + async fn cancel(&self) -> Result<()> { + Ok(()) + } + async fn events(&self, request: JobEventsRequest) -> Result> { + self.0.lock().unwrap().push(request.page_token.clone()); + let metadata = if request.page_token.is_none() { + [( + JOB_EVENT_PAGE_TOKEN_METADATA_KEY.to_string(), + "next".to_string(), + )] + .into_iter() + .collect() + } else { + Default::default() + }; + Ok(vec![RecordBatch::new_empty(Arc::new( + arrow_schema::Schema::new_with_metadata( + Vec::::new(), + metadata, + ), + ))]) + } + } + + #[tokio::test] + async fn collected_history_follows_empty_pages_and_clears_continuations() { + let requests = Arc::new(Mutex::new(Vec::new())); + let job = Job::new(Box::new(HistoryPages(requests.clone()))); + let history = job.history(JobEventsRequest::default()).await.unwrap(); + assert_eq!(history.len(), 2); + assert_eq!( + *requests.lock().unwrap(), + vec![None, Some("next".to_string())] + ); + assert!(history.iter().all(|batch| { + !batch + .schema_ref() + .metadata() + .contains_key(JOB_EVENT_PAGE_TOKEN_METADATA_KEY) + })); + } + #[test] fn local_typed_result_decode_errors_are_runtime_errors() { assert!(matches!( diff --git a/rust/lancedb/src/job/state.rs b/rust/lancedb/src/job/state.rs new file mode 100644 index 000000000..c55e17d90 --- /dev/null +++ b/rust/lancedb/src/job/state.rs @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/// Detailed lifecycle of one job attempt. +/// +/// Unknown server values are retained and are never considered successful or +/// terminal. Legacy client and server labels are accepted by [`Self::from`]. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum JobState { + Created, + Queued, + InProgress, + Succeeded, + Failed, + Canceled, + TimedOut, + Unknown(String), +} + +impl JobState { + /// The canonical wire spelling, or the unrecognized value unchanged. + pub fn as_str(&self) -> &str { + match self { + Self::Created => "created", + Self::Queued => "queued", + Self::InProgress => "in_progress", + Self::Succeeded => "succeeded", + Self::Failed => "failed", + Self::Canceled => "canceled", + Self::TimedOut => "timed_out", + Self::Unknown(value) => value, + } + } + + /// Whether this is a recognized terminal state. + pub fn is_terminal(&self) -> bool { + matches!( + self, + Self::Succeeded | Self::Failed | Self::Canceled | Self::TimedOut + ) + } + + /// Only recognized success establishes that the operation completed. + pub fn is_success(&self) -> bool { + matches!(self, Self::Succeeded) + } +} + +impl From<&str> for JobState { + fn from(value: &str) -> Self { + match value { + "created" | "CREATED" => Self::Created, + "queued" | "QUEUED" => Self::Queued, + "running" | "in_progress" | "IN_PROGRESS" => Self::InProgress, + "finished" | "done" | "DONE" | "succeeded" | "SUCCEEDED" => Self::Succeeded, + "failed" | "FAILED" => Self::Failed, + "canceled" | "CANCELED" | "cancelled" | "CANCELLED" => Self::Canceled, + "timed_out" | "TIMED_OUT" => Self::TimedOut, + other => Self::Unknown(other.to_string()), + } + } +} diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index 7c78cc2f8..a2f271b80 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -237,7 +237,7 @@ pub use blob::{BlobRangeRequest, blob, is_blob}; pub use connection::{ConnectNamespaceBuilder, Connection}; pub use error::{Error, JobFailure, Result}; pub use function::FunctionVersion; -pub use job::Job; +pub use job::{Job, JobState}; pub use lance::table::format::BasePath; use lance_index::vector::ApproxMode as LanceApproxMode; use lance_linalg::distance::DistanceType as LanceDistanceType; diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index c60fa46ec..1c3678031 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -49,13 +49,15 @@ impl JobState { impl From<&str> for JobState { fn from(state: &str) -> Self { match state { - "IN_PROGRESS" | "in_progress" => Self::InProgress, - "CANCELLED" | "cancelled" | "canceled" => Self::Cancelled, + "IN_PROGRESS" | "in_progress" | "created" | "CREATED" | "queued" | "QUEUED" => { + Self::InProgress + } + "CANCELLED" | "cancelled" | "canceled" | "CANCELED" => Self::Cancelled, // The server reports a timed-out job as FAILED on describe; // accept the raw registry state too in case a future server // stops folding it. "FAILED" | "failed" | "TIMED_OUT" | "timed_out" => Self::Failed, - "DONE" | "done" | "succeeded" => Self::Done, + "DONE" | "done" | "succeeded" | "SUCCEEDED" => Self::Done, other => Self::Other(other.to_string()), } } @@ -109,6 +111,20 @@ pub(super) struct DescribeJobResponse { #[serde(default)] pub(super) job_id: String, #[serde(default)] + pub(super) attempt_job_id: Option, + #[serde(default)] + pub(super) operation_id: Option, + #[serde(default)] + pub(super) attempt: Option, + #[serde(default)] + pub(super) retry_of: Option, + #[serde(default)] + pub(super) lifecycle_state: Option, + #[serde(default)] + pub(super) source_table_version: Option, + #[serde(default)] + pub(super) execution_epoch: Option, + #[serde(default)] pub(super) job_type: String, pub(super) job_state: String, #[serde(default)] @@ -148,7 +164,7 @@ impl ReportedFailure { impl DescribeJobResponse { fn state(&self) -> JobState { - JobState::from(self.job_state.as_str()) + JobState::from(self.lifecycle_state.as_deref().unwrap_or(&self.job_state)) } fn into_terminal_result(self, request_id: String) -> TerminalResult { @@ -157,10 +173,21 @@ impl DescribeJobResponse { /// The public description this wire envelope stands for. pub(super) fn into_description(self) -> JobDescription { + let state = self.state().client_label(); JobDescription { job_id: self.job_id, + attempt_job_id: self.attempt_job_id, + operation_id: self.operation_id, + attempt: self.attempt, + retry_of: self.retry_of, + lifecycle_state: self + .lifecycle_state + .as_deref() + .map(crate::job::JobState::from), + source_table_version: self.source_table_version, + execution_epoch: self.execution_epoch, job_type: self.job_type, - state: JobState::from(self.job_state.as_str()).client_label(), + state, creation_ms: self.creation_ms, progress: self.operation_progress.or(self.progress), phase: self.phase, @@ -204,6 +231,32 @@ impl RemoteJob { Self { client, job_id } } + pub async fn retry_attempt(&self) -> Result { + let request = self + .client + .post("/v1/jobs/retry") + .json(&serde_json::json!({"job_id": self.job_id})); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let response: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("invalid job retry response: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + let job_id = response + .get("job_id") + .and_then(serde_json::Value::as_str) + .filter(|id| !id.is_empty()) + .ok_or_else(|| Error::Http { + source: "job retry response omitted the successor job_id".into(), + request_id, + status_code: None, + })?; + Ok(Self::new(self.client.clone(), job_id.to_string())) + } + /// One `/v1/jobs/describe` round trip. async fn fetch_description(&self) -> Result<(String, DescribeJobResponse)> { let request = self @@ -340,6 +393,9 @@ impl JobHandle for RemoteJob { if let Some(filter) = request.filter { body["filter"] = serde_json::Value::String(filter); } + if let Some(token) = request.page_token { + body["page_token"] = serde_json::Value::String(token); + } fetch_job_events(&self.client, body).await } @@ -418,6 +474,10 @@ impl JobHandle for RemoteJob { .await .map(|_| ()) } + + async fn retry(&self) -> Result> { + Ok(Box::new(self.retry_attempt().await?)) + } } #[cfg(test)] @@ -598,6 +658,202 @@ mod tests { ); } + #[tokio::test] + async fn wait_preserves_a_timed_out_attempt_without_an_extra_status_request() { + let requests = Arc::new(AtomicUsize::new(0)); + let observed = requests.clone(); + let client = client_with_handler(move |_| { + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body(r#"{"job_state":"FAILED","lifecycle_state":"timed_out"}"#.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "attempt-1".to_string()))); + for _ in 0..2 { + assert!(matches!( + job.wait().await, + Err(crate::Error::JobFailed { .. }) + )); + assert_eq!(job.state().as_deref(), Some("failed")); + assert_eq!(job.lifecycle_state(), Some(crate::JobState::TimedOut)); + } + assert_eq!(requests.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn local_and_remote_jobs_share_terminal_state_contract() { + for remote in [false, true] { + for state in [ + crate::JobState::Succeeded, + crate::JobState::Failed, + crate::JobState::Canceled, + ] { + let job = if remote { + let response_state = state.as_str().to_string(); + let client = client_with_handler(move |request| { + let body = if request.url().path() == "/v1/jobs/cancel" { + "{}".to_string() + } else { + serde_json::json!({ + "job_id": "attempt-2", "operation_id": "attempt-1", "attempt": 2, + "retry_of": "attempt-1", "job_state": "IN_PROGRESS", + "lifecycle_state": response_state, "source_table_version": 7, "execution_epoch": 3, + }).to_string() + }; + http::Response::builder().status(200).body(body).unwrap() + }); + Job::new(Box::new(RemoteJob::new(client, "attempt-2".to_string()))) + } else { + match state { + crate::JobState::Succeeded => Job::spawned(tokio::spawn(async { Ok(()) })), + crate::JobState::Failed => Job::spawned(tokio::spawn(async { + Err::<(), _>(crate::Error::Runtime { + message: "failed".to_string(), + }) + })), + _ => Job::spawned(tokio::spawn(std::future::pending::>())), + } + }; + if state == crate::JobState::Canceled { + job.cancel().await.unwrap(); + } + for _ in 0..2 { + let result = job.wait().await; + match state { + crate::JobState::Succeeded => result.unwrap(), + crate::JobState::Failed => { + assert!(matches!(result, Err(crate::Error::JobFailed { .. }))) + } + _ => assert!(matches!(result, Err(crate::Error::JobCancelled { .. }))), + } + assert_eq!(job.lifecycle_state(), Some(state.clone())); + assert_eq!(job.status_typed().await.unwrap(), state); + } + let identity = job.job_id().unwrap(); + let operation = job.operation_id(); + let mapped = job.map(|()| 7); + assert_eq!(mapped.job_id().as_deref(), Some(identity.as_str())); + assert_eq!(mapped.operation_id(), operation); + if remote { + assert_eq!(mapped.retry_of().as_deref(), Some("attempt-1")); + assert_eq!(mapped.attempt(), Some(2)); + assert_eq!(mapped.source_table_version(), Some(7)); + } else { + uuid::Uuid::parse_str(&identity).unwrap(); + assert_eq!(mapped.attempt(), Some(1)); + } + } + } + } + + #[tokio::test] + async fn unknown_detailed_state_never_inherits_legacy_success() { + let client = client_with_handler(|_| { + http::Response::builder().status(200).body( + r#"{"job_id":"job-1","job_state":"DONE","lifecycle_state":"publishing_in_future","result":null}"# + ).unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".to_string()))); + assert_eq!(job.status().await.unwrap(), "publishing_in_future"); + let state = job.status_typed().await.unwrap(); + assert_eq!(state.as_str(), "publishing_in_future"); + assert!(!state.is_success()); + assert!(!state.is_terminal()); + assert!(matches!( + job.wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(1))) + .await, + Err(crate::Error::Timeout { .. }) + )); + assert_eq!(job.lifecycle_state(), Some(state)); + } + + #[tokio::test] + async fn operation_handles_report_the_selected_attempt_without_changing_id() { + let client = client_with_handler(|_| { + http::Response::builder() + .status(200) + .body( + serde_json::json!({"job_id":"operation-1", "attempt_job_id":"attempt-2", + "operation_id":"operation-1", "attempt":2, "retry_of":"operation-1", + "job_state":"IN_PROGRESS", "lifecycle_state":"queued"}) + .to_string(), + ) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "operation-1".into()))); + assert_eq!(job.status_typed().await.unwrap(), crate::JobState::Queued); + assert_eq!(job.id(), Some("operation-1")); + assert_eq!(job.job_id().as_deref(), Some("attempt-2")); + assert_eq!(job.operation_id().as_deref(), Some("operation-1")); + assert_eq!(job.attempt(), Some(2)); + } + + #[tokio::test] + async fn retry_preserves_the_typed_result_decoder_and_exact_predecessor() { + let client = client_with_handler(|request| { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + let response = if request.url().path() == "/v1/jobs/retry" { + assert_eq!(body["job_id"], "attempt-1"); + serde_json::json!({"job_id": "attempt-2"}) + } else { + assert_eq!(body["job_id"], "attempt-2"); + serde_json::json!({"job_id": "attempt-2", "operation_id": "attempt-1", "attempt": 2, + "retry_of": "attempt-1", "job_state": "DONE", "lifecycle_state": "succeeded", "result": 41}) + }; + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }); + let job = Job::::new_typed(Box::new(RemoteJob::new(client, "attempt-1".to_string()))) + .map(|value| value + 1); + let successor = job.retry().await.unwrap(); + assert_eq!(successor.id(), Some("attempt-2")); + assert_eq!(successor.wait().await.unwrap(), 42); + successor.refresh().await.unwrap(); + assert_eq!(successor.operation_id().as_deref(), Some("attempt-1")); + assert_eq!(successor.attempt(), Some(2)); + assert_eq!(successor.retry_of().as_deref(), Some("attempt-1")); + } + + #[tokio::test] + async fn local_and_remote_wait_timeouts_leave_jobs_waitable() { + let (sender, receiver) = tokio::sync::oneshot::channel(); + let local = Job::spawned(tokio::spawn(async move { + receiver.await.map_err(|error| crate::Error::Runtime { + message: error.to_string(), + }) + })); + assert!(matches!( + local + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(1))) + .await, + Err(crate::Error::Timeout { .. }) + )); + sender.send(7).unwrap(); + assert_eq!(local.wait().await.unwrap(), 7); + + let done = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let observed = done.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + http::Response::builder().status(200).body(serde_json::json!({ + "job_state": if observed.load(Ordering::SeqCst) { "DONE" } else { "IN_PROGRESS" }, "result": 7 + }).to_string()).unwrap() + }); + let remote = Job::::new_typed(Box::new(RemoteJob::new(client, "job-1".to_string()))); + assert!(matches!( + remote + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(1))) + .await, + Err(crate::Error::Timeout { .. }) + )); + done.store(true, Ordering::SeqCst); + assert_eq!(remote.wait().await.unwrap(), 7); + } + #[tokio::test] async fn stats_reads_report_verbatim_and_preserves_unavailable_without_waiting() { let requests = Arc::new(AtomicUsize::new(0)); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 023f3bb69..ed2c7a70b 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -383,6 +383,16 @@ impl crate::job::JobHandle for FreshnessJob { async fn cancel(&self) -> Result<()> { crate::job::JobHandle::cancel(&self.inner).await } + + async fn retry(&self) -> Result> { + Ok(Box::new(Self { + inner: self.inner.retry_attempt().await?, + freshness: self.freshness.clone(), + version: self.version.clone(), + tracked_result: self.tracked_result, + freshness_request: self.freshness_request, + })) + } } /// A registry-backed materialized-view refresh. Registry completion is only @@ -4550,8 +4560,9 @@ impl BaseTable for RemoteTable { if request.history { self.require_function_failure_workflow().await?; } + let paged = request.page_token.is_some(); let mut body = serde_json::json!({}); - if request.history { + if request.history || paged { body["history"] = serde_json::json!(true); } if let Some(job_id) = &request.job_id { @@ -4563,6 +4574,9 @@ impl BaseTable for RemoteTable { if let Some(limit) = request.limit { body["limit"] = serde_json::json!(limit); } + if let Some(token) = &request.page_token { + body["page_token"] = serde_json::json!(token); + } self.apply_branch_body(&mut body); let request = self .client @@ -4571,11 +4585,16 @@ impl BaseTable for RemoteTable { 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(|e| Error::Http { - source: format!("Failed to parse errors response: {}", e).into(), - request_id, - status_code: None, - }) + let errors: crate::function::FunctionErrors = + serde_json::from_str(&body).map_err(|e| Error::Http { + source: format!("Failed to parse errors response: {}", e).into(), + request_id, + status_code: None, + })?; + if paged && errors.truncated && errors.page_token.is_none() { + return Err(Error::NotSupported {message: "server truncated Function errors without a page token; paged errors require server support".to_string()}); + } + Ok(errors) } async fn quarantine_function_errors( @@ -13639,6 +13658,84 @@ mod tests { ); } + #[tokio::test] + async fn retrying_a_refresh_preserves_result_decoding_and_read_freshness() { + let saw_version = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let observed = saw_version.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let body = match request.url().path() { + "/v1/table/my_table/backfill_column" => r#"{"job_id":"attempt-1"}"#.to_string(), + "/v1/jobs/retry" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["job_id"], "attempt-1"); + r#"{"job_id":"attempt-2"}"#.to_string() + } + "/v1/jobs/describe" => refresh_done("attempt-2"), + "/v1/table/my_table/count_rows/" => { + observed.store( + request + .headers() + .get("x-lancedb-min-read-version") + .and_then(|value| value.to_str().ok()) + == Some("8"), + Ordering::SeqCst, + ); + "1".to_string() + } + path => panic!("unexpected path {path}"), + }; + http::Response::builder() + .status(if request.url().path().ends_with("backfill_column") { + 202 + } else { + 200 + }) + .body(body) + .unwrap() + }); + let submitted = table.refresh_column_async("doubled").await.unwrap(); + let retry = submitted.retry().await.unwrap(); + assert_eq!(retry.id(), Some("attempt-2")); + assert_eq!(retry.wait().await.unwrap().rows_assigned, 12); + table.count_rows(None).await.unwrap(); + assert!(saw_version.load(Ordering::SeqCst)); + } + + #[tokio::test] + async fn paged_row_errors_preserve_tokens_and_refuse_silent_truncation() { + for legacy in [false, true] { + let table = Table::new_with_handler("my_table", move |request| { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["page_token"], ""); + assert_eq!(body["history"], true); + assert_eq!(body["job_id"], "attempt-1"); + let mut response = json!({"records":[],"fragments":[],"truncated":true}); + if !legacy { + response["page_token"] = json!("next"); + } + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }); + let result = table + .function_errors( + crate::function::FunctionErrorsRequest::new() + .job_id("attempt-1") + .page_token(""), + ) + .await; + if legacy { + assert!(matches!(result, Err(Error::NotSupported { .. }))); + } else { + assert_eq!(result.unwrap().page_token.as_deref(), Some("next")); + } + } + } + /// Index submissions use the same freshness wrapper. Its wait must forward /// observations and retain the successful-wait timestamp bookkeeping. #[tokio::test]