From ba4e3ef3f9dccb9e94623783120af04166cc2239 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Tue, 17 Nov 2026 02:54:18 -0800 Subject: [PATCH 01/78] feat: expose Function worker stack inspection (#5043) Adds `Job::stack(worker_id)` in Rust and `Job.stack(worker_id)` / `AsyncJob.stack(worker_id)` in Python for server-side Function jobs. The response preserves capture availability, timestamps, truncation, and session details; unsupported local or query handles retain their existing unsupported-operation behavior. Refresh wrappers forward the request to their tracked server job. ```python evidence = job.stack("worker-id") for session in evidence["stacks"]: print(session["status"], session["stack"]) ``` Requires a server implementing `/v1/jobs/stack` and system operate privilege. The API propagates authorization and transport errors without waiting for job completion. Existing progress snapshots already preserve server warning fields. Includes mocked request/response and synchronous/asynchronous Python coverage. Local builds and tests were intentionally skipped as requested. --- docs/web/basics/jobs.mdx | 30 ++++++++++ python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/job.py | 41 +++++++++++++ python/python/tests/test_job.py | 45 +++++++++++++++ python/src/job.rs | 7 +++ rust/lancedb/src/job.rs | 32 ++++++++++ rust/lancedb/src/remote/job.rs | 93 ++++++++++++++++++++++++++++++ rust/lancedb/src/remote/table.rs | 8 +++ 8 files changed, 257 insertions(+) diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index db5b49ab5..30d48e93e 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -332,6 +332,36 @@ by the jobs API. `estimated_remaining_time_millis` is a best-effort client-side estimate. It is omitted while a job is initializing, queued, or paused, and when there is no positive progress rate from two compatible samples. + +### Inspect a slow Function worker + +On a supported Enterprise server, Python's `Job.stack(worker_id)` and +`await AsyncJob.stack(worker_id)` capture Python thread stacks from a running +Function refresh worker. Rust provides `job.stack(worker_id).await?`. +TypeScript does not yet expose this method. Stack inspection requires the +system operate privilege. + +Select a worker ID from the job's progress warnings or recorded events. For +example, inspect a worker named in the current no-progress or slow-split warnings: + +```python +job = db.open_job(job_id) +snapshot = job.progress() or {} +warnings = snapshot.get("warnings", []) +if warnings: + evidence = job.stack(warnings[0]["worker_id"]) + print(evidence["status"], evidence["omitted_sessions"]) + for session in evidence["stacks"]: + print(session["status"], session["captured_at_millis"]) + print(session["stack"], session["truncated"]) +``` + +`unavailable` and `unsupported` are explicit capture statuses; missing frames +do not establish that a worker is healthy or finished. Captures are bounded and +may reuse a recent sample. They contain Python frames without source text, +locals or native frames. Local operations and SQL-backed query handles do not +support stack inspection. For a worker that already timed out, inspect the +recorded failure events for retained traceback evidence. */} ## Embedded and Enterprise execution {#in-process} diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 63d442703..2273e8628 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -449,6 +449,7 @@ class Job: async def cancel(self) -> None: ... async def refresh(self) -> None: ... async def timeline(self) -> str: ... + async def stack(self, worker_id: str) -> str: ... async def stats(self) -> Optional[str]: ... async def events( self, diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index e49609e1f..dab6d5903 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -4,6 +4,7 @@ """Handles to asynchronous registry jobs, SQL queries, and local operations.""" import asyncio +import json import logging import reprlib import time @@ -486,6 +487,30 @@ class AsyncJob(Generic[T]): description = self._inner._description if self._inner is not None else None return getattr(description, name) if description is not None else None + async def stack(self, worker_id: str) -> dict[str, Any]: + """Capture Python thread stacks from a running Function worker. + + Requires server support and system operate privilege. The response has + ``status``, ``worker_id``, ``execution_epoch`` and ``stacks``. Each session + reports its status, capture timestamp, Python frames and truncation. + ``omitted_sessions`` counts sessions beyond the server's capture limit. + Captures exclude source text, locals and native frames; a recent capture + may be reused to bound overhead. Unsupported or unavailable captures + have an explicit status. Transport and authorization errors propagate. + Local operations and SQL query handles raise ``NotImplementedError``. + Timeout stack evidence remains in the job's failure events. + + Examples + -------- + >>> evidence = await job.stack("worker-id") # doctest: +SKIP + >>> print(evidence["stacks"]) # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "worker stacks require a server-side Function job" + ) + return json.loads(await self._inner.stack(worker_id)) + async def stats(self) -> Optional[str]: """Return a printable run report for this Function job. @@ -736,6 +761,22 @@ class Job(Generic[T]): def _field(self, name: str) -> Optional[Any]: return getattr(self._inner, name) if self._inner is not None else None + def stack(self, worker_id: str) -> dict[str, Any]: + """Capture Python thread stacks from a running Function worker. + + See [AsyncJob.stack][lancedb.job.AsyncJob.stack] for availability, + permissions and response fields. + + Examples + -------- + >>> print(job.stack("worker-id")["stacks"]) # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "worker stacks require a server-side Function job" + ) + return LOOP.run(self._inner.stack(worker_id)) + def stats(self) -> Optional[str]: """Return a printable Function job run report. diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index e71945b7f..59e2fc3a8 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -1027,3 +1027,48 @@ async def test_export_timeline_reports_filesystem_errors(tmp_path): ) with pytest.raises(FileNotFoundError): await job.export_timeline(tmp_path / "missing" / "trace.json") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_stack_preserves_evidence_and_does_not_wait(sync): + evidence = { + "worker_id": "worker", + "status": "unavailable", + "execution_epoch": 1, + "stacks": [], + "omitted_sessions": 0, + } + inner = SimpleNamespace( + stack=AsyncMock(return_value=json.dumps(evidence)), + wait=AsyncMock(), + cancel=AsyncMock(), + ) + job = AsyncJob(inner) + actual = ( + await asyncio.to_thread(Job(job).stack, "worker") + if sync + else await job.stack("worker") + ) + assert actual == evidence + inner.stack.assert_awaited_once_with("worker") + inner.wait.assert_not_awaited() + inner.cancel.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_stack_propagates_errors_and_rejects_local_handles(sync): + error = RuntimeError("system operate privilege required") + job = AsyncJob(SimpleNamespace(stack=AsyncMock(side_effect=error))) + with pytest.raises(RuntimeError) as failure: + if sync: + await asyncio.to_thread(Job(job).stack, "worker") + else: + await job.stack("worker") + assert failure.value is error + with pytest.raises(NotImplementedError): + if sync: + Job(None).stack("worker") + else: + await AsyncJob(None).stack("worker") diff --git a/python/src/job.rs b/python/src/job.rs index 08f6440ab..7e4c13f41 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -159,6 +159,13 @@ impl Job { }) } + pub fn stack(self_: PyRef<'_, Self>, worker_id: String) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + Ok(inner.stack(worker_id).await.infer_error()?.to_string()) + }) + } + pub fn stats(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { inner.stats().await.infer_error() }) diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index b1e3c1bbf..39fee38d6 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -90,6 +90,10 @@ pub(crate) trait JobHandle: Send + Sync { job_detail_not_supported("job timeline export") } + async fn stack(&self, _worker_id: &str) -> Result { + job_detail_not_supported("worker stack capture") + } + /// A printable report of recorded Function job metrics. async fn stats(&self) -> Result> { job_detail_not_supported("job statistics") @@ -536,6 +540,34 @@ where } } + /// Capture Python thread stacks from a running Function worker. + /// + /// Requires a server supporting stack inspection and system operate privilege. + /// The JSON response reports capture availability per session, timestamps and + /// truncation. Stacks exclude source text, locals and native frames. A server + /// may reuse a recent capture to bound sampling overhead. Unsupported local + /// operations return [`crate::Error::NotSupported`]. + /// + /// ```no_run + /// # async fn inspect(job: &lancedb::job::Job) -> Result<(), Box> { + /// let evidence = job.stack("worker-id").await?; + /// println!("{evidence}"); + /// # Ok(()) + /// # } + /// ``` + pub async fn stack(&self, worker_id: impl AsRef) -> Result { + let worker_id = worker_id.as_ref(); + if worker_id.is_empty() || worker_id.len() > 256 { + return Err(Error::InvalidInput { + message: "worker_id must contain 1 to 256 bytes".into(), + }); + } + match &self.inner { + JobInner::Handle { handle, .. } => handle.stack(worker_id).await, + JobInner::Completed(_) => job_detail_not_supported("worker stack capture"), + } + } + /// Fetch a printable run report for a server-side Function job. /// /// The server report includes recorded phase timings, finishing-supervisor diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 7e59834d0..f233d4026 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -261,6 +261,46 @@ impl JobHandle for RemoteJob { Ok(trace) } + async fn stack(&self, worker_id: &str) -> Result { + let request = self + .client + .post("/v1/jobs/stack") + .json(&serde_json::json!({"job_id": self.job_id, "worker_id": worker_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 evidence: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse worker stack response: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + if evidence + .get("worker_id") + .and_then(serde_json::Value::as_str) + != Some(worker_id) + || !matches!( + evidence.get("status").and_then(serde_json::Value::as_str), + Some("captured" | "unavailable" | "unsupported") + ) + || !evidence + .get("stacks") + .is_some_and(serde_json::Value::is_array) + || !evidence + .get("execution_epoch") + .is_some_and(serde_json::Value::is_i64) + { + return Err(Error::Http { + source: + "server response is not worker stack evidence; capture requires server support" + .into(), + request_id, + status_code: None, + }); + } + Ok(evidence) + } + async fn stats(&self) -> Result> { let request = self .client @@ -401,6 +441,59 @@ mod tests { include_str!("../../tests/fixtures/first_class_functions/v1/remote_unit_job.json"); const MISSING_RESULT_JOB: &str = r#"{"job_state":"DONE"}"#; + #[tokio::test] + async fn stack_preserves_availability_and_uses_the_selected_worker() { + for status in ["captured", "unsupported", "unavailable"] { + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/stack"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!( + body, + serde_json::json!({"job_id":"job-1", "worker_id":"worker-1"}) + ); + http::Response::builder().status(200).body(serde_json::json!({ + "worker_id":"worker-1", "status":status, "execution_epoch":1, "stacks":[], "omitted_sessions":0 + }).to_string()).unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + assert_eq!(job.stack("worker-1").await.unwrap()["status"], status); + } + } + + #[tokio::test] + async fn stack_rejects_unrelated_responses_and_preserves_authorization_errors() { + for body in [ + "{}", + r#"{"worker_id":"other","status":"captured","execution_epoch":1,"stacks":[]}"#, + ] { + let client = client_with_handler(move |_| { + http::Response::builder().status(200).body(body).unwrap() + }); + assert!(matches!( + RemoteJob::new(client, "job-1".into()) + .stack("worker-1") + .await + .unwrap_err(), + crate::Error::Http { .. } + )); + } + let client = client_with_handler(|_| { + http::Response::builder() + .status(403) + .body("access denied") + .unwrap() + }); + assert!( + RemoteJob::new(client, "job-1".into()) + .stack("worker-1") + .await + .unwrap_err() + .to_string() + .contains("403") + ); + } + #[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 1394f1ab0..f89be7e69 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -324,6 +324,10 @@ impl crate::job::JobHandle for FreshnessJob { crate::job::JobHandle::timeline(&self.inner).await } + async fn stack(&self, worker_id: &str) -> Result { + crate::job::JobHandle::stack(&self.inner, worker_id).await + } + async fn events( &self, request: crate::job::JobEventsRequest, @@ -409,6 +413,10 @@ impl crate::job::JobHandle for MaterializedViewRefreshJob { crate::job::JobHandle::timeline(&self.inner).await } + async fn stack(&self, worker_id: &str) -> Result { + crate::job::JobHandle::stack(&self.inner, worker_id).await + } + async fn events( &self, request: crate::job::JobEventsRequest, From fb34b1c7837b525b4ebb27b71800d63efa2026fc Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Tue, 17 Nov 2026 03:26:45 -0800 Subject: [PATCH 02/78] feat(functions): add row failure recovery APIs (#5048) Function failures currently require callers to assemble row predicates and manage retry/version/quarantine state themselves. Add exact failed-row retry and Function upgrades through the Rust and Python refresh APIs, plus Python helpers for grouped causes, failing input rows, quarantine, and per-row producing-version metadata. ```python errors = table.function_errors(column="sharpness") errors.summary() errors.rows(columns=["frame_index", "frame"]) table.retry_failed("sharpness", function_version="2").wait() table.quarantine_failed("sharpness", after_attempts=3) table.retry_failed("sharpness", include_quarantined=True).wait() table.function_provenance("sharpness") ``` `upgrade_column(..., recompute="failed" | "all" | "none")` keeps the column available while selecting the intended work. `history=True` reads retained past errors. Capability checks reject these operations on servers that cannot honor the workflow, before any refresh is submitted. Includes synchronous/asynchronous API and older-server compatibility coverage. Formatting applied; local builds and tests were not run. --- docs/src/python/python.md | 10 +- docs/web/management/function-failures.mdx | 133 +++++++- nodejs/src/table.rs | 1 + python/python/lancedb/__init__.py | 11 +- python/python/lancedb/_lancedb.pyi | 35 ++ python/python/lancedb/functions.py | 221 +++++++++++++ python/python/lancedb/remote/table.py | 60 +++- python/python/lancedb/table.py | 370 ++++++++++++++++++++-- python/python/tests/test_remote_db.py | 211 +++++++++++- python/src/table.rs | 115 ++++++- rust/lancedb/src/function.rs | 106 +++++++ rust/lancedb/src/remote/table.rs | 104 ++++++ rust/lancedb/src/table.rs | 105 ++++++ rust/lancedb/src/table/refresh.rs | 85 +++++ 14 files changed, 1540 insertions(+), 27 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index b64940e39..d3713b634 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -640,7 +640,15 @@ with BlobReader(read_range, len(payload)) as reader: ::: lancedb.functions.RefreshColumnResult -::: lancedb.FunctionErrors +::: lancedb.functions.FunctionErrorGroup + +::: lancedb.functions.FunctionProvenance + +::: lancedb.functions.FunctionValueProvenance + +::: lancedb.functions.AsyncFunctionErrors + +::: lancedb.functions.FunctionErrors ::: lancedb.FunctionErrorRecord diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx index 4546129fa..131204382 100644 --- a/docs/web/management/function-failures.mdx +++ b/docs/web/management/function-failures.mdx @@ -10,8 +10,137 @@ availability: A Function refresh can encounter a bad row, fail to initialize a model, lose a worker, or fail while publishing results. These need different remedies. -This guide uses the existing [refresh error policy](/sql/dml/refresh-column#options) -and Python error records; it does not require a new retry or quarantine API. +The native workflow below is draft guidance for an unreleased SDK and a +matching Enterprise server. The recipes that follow it remain available for +older deployments. + +## Draft native workflow: server contract version 1 {#native} + +This section requires the SDK changes in [PR #5048](https://github.com/lancedb/lancedb/pull/5048) +and an Enterprise deployment advertising `workflow_version >= 1` in its +Function error response. No released SDK or Enterprise version is implied by +this draft. The SDK checks this capability before submitting native retry, +upgrade, quarantine, history or provenance requests, and rejects unsupported +servers before changing the column. + +New Function refreshes default to `error_policy="skip"` with a 5% failed-row +ceiling. Successful outputs are published before a threshold failure is +reported; failed rows and grouped causes remain available. Explicit `fail` +still stops on a row error. Initialization, infrastructure and publication +failures remain job failures. External effects can repeat during recovery. + +Read current unresolved failures, group their causes and inspect their inputs: + +```python +errors = table.function_errors(column="embedding") +print(errors.summary()) +inputs = errors.rows(columns=["text"]) +print(inputs) # Includes a __function_error struct for each failed column. + +history = table.function_errors(column="embedding", history=True) +print(history.records) # Retained attempts, including repaired failures. +``` + +The default listing deduplicates failures by row and Function column, retaining +attempt counts and first/last failure times. `summary()` and `rows()` refuse +incomplete selections; narrow a truncated request before inspecting it. +Historical records cannot be joined to current inputs through `rows()`. +Stable row IDs survive compaction; older physical-only records are rejected +for exact retry if their fragments have been rewritten. + +Select retry rows on the server, optionally by exception class or job: + +```python +retry_job = table.retry_failed("embedding", error_type="ValueError") +retry_job.wait() +``` + +Upgrade the existing Function binding and choose which values to recompute: + +```python +upgrade_job = table.upgrade_column("embedding", version="2", recompute="failed") +upgrade_job.wait() +provenance = table.function_provenance("embedding") +if not provenance.truncated: + print(provenance.records) +``` + +The immutable target version must already exist for the same Function. +`recompute="failed"` selects current failures; `"all"` recomputes all live rows; +`"none"` changes the binding while preserving existing values. The default is +`"all"`. New and changed inputs use the new version. Producing-version records +identify successful values written by this workflow; older values without +recorded provenance do not acquire an invented producing version. + +Quarantine failures that need input repair, then explicitly include them when +they are ready to retry: + +```python +table.quarantine_failed("embedding", after_attempts=3) +retry_job = table.retry_failed("embedding", include_quarantined=True) +retry_job.wait() +``` + +Ordinary and automatic refreshes exclude quarantined rows, including during +an `"all"` upgrade. Explicit inclusion releases quarantine before the retry. +Async tables expose the same operations with `await`; `function_errors()` +returns `AsyncFunctionErrors`, and its `rows()` method is also awaited. +These native recovery APIs are available in Python and Rust. TypeScript does +not yet expose them; its SDK support is tracked as a separate follow-up. + +The equivalent Rust operations use explicit request options: + +```rust +use lancedb::{Table, table::RefreshColumnOptions}; +use lancedb::function::{ + FunctionProvenanceOptions, FunctionQuarantineOptions, FunctionRecompute, +}; + +async fn recover(table: &Table) -> lancedb::Result<()> { + let retry = table.refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default() + .retry_errors(true) + .retry_error_type("ValueError"), + ).await?; + retry.wait().await?; + + let upgrade = table.refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default().upgrade("2", FunctionRecompute::Failed), + ).await?; + upgrade.wait().await?; + + table.quarantine_function_errors( + "embedding", + FunctionQuarantineOptions { + after_attempts: Some(3), + ..Default::default() + }, + ).await?; + let provenance = table.function_provenance( + "embedding", FunctionProvenanceOptions::default(), + ).await?; + if !provenance.truncated { + println!("{:?}", provenance.records); + } + Ok(()) +} +``` + +Set `include_quarantined(true)` on a Rust failed-row retry to explicitly +release quarantine before recomputing those failures. + +The native contract also applies skip/5% defaults to newly created materialized +views, with errors identified by Function invocation and source input. Column +retry and upgrade helpers apply to Function columns; use the materialized-view +refresh reference for view refresh options. + +## Older-deployment recipes {#older-deployments} + +The following sections describe deployments without workflow version 1. Their +legacy defaults, error-history semantics and application-managed quarantine +remain unchanged. ## Choose a row-error policy {#policy} diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index a0a220e24..c9e03b2a3 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -581,6 +581,7 @@ impl Table { }) .transpose()?; let request = lancedb::function::FunctionErrorsRequest { + history: false, job_id: options.job_id, column: options.column, limit, diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index acf25d35c..129a4b1c5 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -29,7 +29,6 @@ from ._lancedb import ( ) from ._lancedb import FunctionErrorFragment as FunctionErrorFragment from ._lancedb import FunctionErrorRecord as FunctionErrorRecord -from ._lancedb import FunctionErrors as FunctionErrors from ._lancedb import GpuClass as GpuClass from ._lancedb import RTEWriteSpec from ._lancedb import tokenize as _tokenize @@ -46,6 +45,11 @@ from .sql import AsyncQuery as AsyncSqlQuery from .sql import Query as SqlQuery from .sql import QueryDescription from .functions import ( + FunctionErrors as FunctionErrors, + AsyncFunctionErrors as AsyncFunctionErrors, + FunctionErrorGroup as FunctionErrorGroup, + FunctionProvenance as FunctionProvenance, + FunctionValueProvenance as FunctionValueProvenance, AssignmentMapping as AssignmentMapping, FunctionArtifactRequest as FunctionArtifactRequest, FunctionApplication as FunctionApplication, @@ -678,6 +682,11 @@ __all__ = [ "FunctionColumnLastRefreshJob", "FunctionColumnStatus", "FunctionColumnVersionStatus", + "FunctionErrors", + "AsyncFunctionErrors", + "FunctionErrorGroup", + "FunctionProvenance", + "FunctionValueProvenance", "col", "Expr", "func", diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 2273e8628..19454790a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -694,6 +694,12 @@ class Table: init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> RefreshColumnResult: ... async def refresh_column_async( self, @@ -716,13 +722,36 @@ class Table: init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> Job: ... async def function_errors( self, job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, + history: bool = False, ) -> FunctionErrors: ... + async def quarantine_function_errors( + self, + column: str, + *, + quarantined: bool = True, + job_id: Optional[str] = None, + error_type: Optional[str] = None, + after_attempts: Optional[int] = None, + ) -> int: ... + async def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> str: ... async def column_statuses( self, column: Optional[str] = None ) -> list[FunctionColumnStatus]: ... @@ -1128,6 +1157,10 @@ class RefreshColumnResult: version: int class FunctionErrorRecord: + first_seen_at_millis: Optional[int] + last_seen_at_millis: Optional[int] + quarantined: bool + input: Optional[str] attempts: Optional[int] job_id: str fragment_id: int @@ -1151,6 +1184,8 @@ class FunctionErrorFragment: rows_recorded: int class FunctionErrors: + workflow_version: Optional[int] + error_groups_json: str records: list[FunctionErrorRecord] fragments: list[FunctionErrorFragment] truncated: bool diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 9178d5194..5ea45a6a6 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1132,6 +1132,220 @@ class FunctionBinding(_RemoteValue): return reader.read_all().to_pylist()[0] +class FunctionErrorGroup(_RemoteValue): + """A grouped cause among returned Function failures.""" + + column: str + error_type: str + error_message: str + rows_failed: _UInt64 + + +class FunctionValueProvenance(_RemoteValue): + """The Function version and job that produced one stored value.""" + + column: str + job_id: str + function_name: str + function_version: str + row_id: Optional[_UInt64] = None + row_address: Optional[_UInt64] = None + source_version: _UInt64 + published_version: _UInt64 + + +class FunctionProvenance(_RemoteValue): + """A bounded per-row producing-version listing for a table snapshot.""" + + records: tuple[FunctionValueProvenance, ...] + truncated: bool = False + + +class _FunctionErrors: + """Current Function failures, with grouped causes and source-row lookup. + + Check ``truncated`` and ``fragments`` before treating a listing as complete. + ``history=True`` on ``table.function_errors`` returns retained past records. + """ + + def __init__(self, raw: Any, table: Any, *, history: bool = False): + self._raw = raw + self._table = table + self._history = history + self.records = raw.records + self.fragments = raw.fragments + self.truncated = raw.truncated + + def __repr__(self) -> str: + return repr(self._raw) + + def as_sync(self, table: Any) -> FunctionErrors: + return FunctionErrors(self._raw, table, history=self._history) + + def summary(self) -> list[FunctionErrorGroup]: + """Group returned failures by column, exception class, and message. + + Raises when records are incomplete, so sampled counts cannot be mistaken + for totals. Narrow the request by column or job, or raise its limit. + """ + if (getattr(self._raw, "workflow_version", None) or 0) < 1: + raise NotImplementedError( + "The server does not support the current Function failure workflow" + ) + if ( + self.truncated + or self.fragments + or any( + record.row_offset is None and record.input is None + for record in self.records + ) + ): + raise ValueError( + "Function errors are incomplete; narrow the request or raise limit" + ) + groups: dict[tuple[str, str, str], int] = {} + for record in self.records: + if record.row_offset is None and record.input is None: + continue + message = record.error_message + if record.input is not None: + message = message.split("\nSource input: ", 1)[0].split( + "\nFunction input ", 1 + )[0] + key = (record.column, record.error_type, message) + groups[key] = groups.get(key, 0) + 1 + return [ + FunctionErrorGroup( + column=column, error_type=kind, error_message=message, rows_failed=count + ) + for (column, kind, message), count in sorted(groups.items()) + ] + + def _identities(self) -> dict[tuple[str, int], list[Any]]: + if (getattr(self._raw, "workflow_version", None) or 0) < 1: + raise NotImplementedError( + "The server does not support the current Function failure workflow" + ) + if self._history: + raise ValueError( + "Source-row lookup requires current failures; " + "read retained history through records" + ) + if self.truncated or self.fragments: + raise ValueError( + "Function errors are incomplete; narrow the request or raise limit" + ) + result = {} + for record in self.records: + if record.input is not None or record.row_offset is None: + raise ValueError( + "This error names a Function invocation; " + "inspect its input source identities" + ) + identity = ( + record.row_id if record.row_id is not None else record.row_address + ) + if identity is None: + raise ValueError("This error has no source row identity") + key = ("_rowid" if record.row_id is not None else "_rowaddr", identity) + result.setdefault(key, []).append(record) + return result + + def _predicate(self, identities: dict[tuple[str, int], list[Any]]) -> str: + clauses = [] + for field in ("_rowid", "_rowaddr"): + selected = [identity for (kind, identity) in identities if kind == field] + if selected: + clauses.append(field + " IN (" + ",".join(map(str, selected)) + ")") + return " OR ".join(clauses) if clauses else "false" + + def _join_rows( + self, rows: pa.Table, identities: dict[tuple[str, int], list[Any]] + ) -> pa.Table: + matches = [] + indices = [] + found = set() + for index, (row_id, address) in enumerate( + zip(rows.column("_rowid").to_pylist(), rows.column("_rowaddr").to_pylist()) + ): + for key in (("_rowid", row_id), ("_rowaddr", address)): + for record in identities.get(key, []): + found.add(key) + indices.append(index) + matches.append(record) + if found != identities.keys(): + raise ValueError( + "Some failed inputs are no longer addressable in this snapshot; " + "refresh the error listing or use a historical snapshot" + ) + rows = rows.take(pa.array(indices, type=pa.int64())) + fields = [ + "column", + "error_type", + "error_message", + "attempts", + "function_version", + "job_id", + "first_seen_at_millis", + "last_seen_at_millis", + "quarantined", + ] + arrays = [ + pa.array([getattr(record, field) for record in matches]) for field in fields + ] + if "__function_error" in rows.column_names: + raise ValueError("Source columns already contain __function_error") + return rows.append_column( + "__function_error", pa.StructArray.from_arrays(arrays, names=fields) + ) + + +class FunctionErrors(_FunctionErrors): + """Current failures with grouped causes and synchronous source-row lookup.""" + + def rows(self, columns: Optional[list[str]] = None) -> pa.Table: + """Return current failing inputs with a ``__function_error`` struct. + + Row IDs come from the error records. The server joins stable identities + correctly after compaction; callers need no physical-address arithmetic. + """ + identities = self._identities() + predicate = self._predicate(identities) + query = ( + self._table.search() + .where(predicate) + .with_row_id(True) + .with_row_address() + .limit(max(1, len(identities))) + ) + selected = list(self._table.schema.names if columns is None else columns) + selected.extend(name for name in ("_rowid", "_rowaddr") if name not in selected) + query = query.select(selected) + return self._join_rows(query.to_arrow(), identities) + + +class AsyncFunctionErrors(_FunctionErrors): + """Current Function failures returned by an asynchronous table.""" + + async def rows(self, columns: Optional[list[str]] = None) -> pa.Table: + """Return current failing inputs with their ``__function_error`` metadata.""" + identities = self._identities() + predicate = self._predicate(identities) + query = ( + self._table.query() + .where(predicate) + .with_row_id() + .with_row_address() + .limit(max(1, len(identities))) + ) + selected = list( + (await self._table.schema()).names if columns is None else columns + ) + selected.extend(name for name in ("_rowid", "_rowaddr") if name not in selected) + query = query.select(selected) + return self._join_rows(await query.to_arrow(), identities) + + class RefreshColumnResult(_RemoteValue): """Terminal result of an expression-backed or Function-backed refresh Job. @@ -1169,6 +1383,8 @@ class RefreshColumnResult(_RemoteValue): """Exact table version the refresh read.""" published_version: Optional[_UInt64] = None + error_groups: tuple[FunctionErrorGroup, ...] = () + error_groups_truncated: bool = False """Table version made visible by the refresh, when one was published.""" @property @@ -3487,6 +3703,11 @@ __all__ = [ "ResolvedEnvironmentProvenance", "ResolvedPackage", "RefreshColumnResult", + "FunctionErrors", + "AsyncFunctionErrors", + "FunctionErrorGroup", + "FunctionProvenance", + "FunctionValueProvenance", "FunctionDefinition", ] diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 2d068536e..19e7ff454 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -50,6 +50,7 @@ from lancedb.index import ( ) from lancedb.job import Job from lancedb.functions import ( + FunctionProvenance, FunctionApplication, FunctionRetryPolicy, RefreshColumnResult, @@ -1185,6 +1186,12 @@ class RemoteTable(Table): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ): return LOOP.run( self._table.refresh_column( @@ -1206,6 +1213,12 @@ class RemoteTable(Table): init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ) ) @@ -1230,6 +1243,12 @@ class RemoteTable(Table): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> Job[RefreshColumnResult]: return Job( LOOP.run( @@ -1252,6 +1271,12 @@ class RemoteTable(Table): init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ) ) ) @@ -1261,9 +1286,42 @@ class RemoteTable(Table): job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, + history: bool = False, ): return LOOP.run( - self._table.function_errors(job_id=job_id, column=column, limit=limit) + self._table.function_errors( + job_id=job_id, column=column, limit=limit, history=history + ) + ).as_sync(self) + + def quarantine_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + after_attempts: Optional[int] = None, + quarantined: bool = True, + ) -> int: + return LOOP.run( + self._table.quarantine_failed( + column, + error_type=error_type, + job_id=job_id, + after_attempts=after_attempts, + quarantined=quarantined, + ) + ) + + def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> FunctionProvenance: + return LOOP.run( + self._table.function_provenance(column, limit=limit, version=version) ) def column_statuses( diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 7f378a34c..8d996d32e 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -84,6 +84,9 @@ from .index import ( ) from .expr import Expr from .functions import ( + FunctionErrors, + AsyncFunctionErrors, + FunctionProvenance, FunctionRetryPolicy, FunctionApplication, RefreshColumnResult as RefreshColumnJobResult, @@ -300,7 +303,6 @@ if TYPE_CHECKING: CompactionStats, Tag, AddColumnsResult, - FunctionErrors, RefreshColumnResult, AddResult, AlterColumnsResult, @@ -3290,6 +3292,12 @@ class Table(ABC): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> "RefreshColumnResult": """ Fill the rows of a computed column that hold no value yet. @@ -3365,6 +3373,9 @@ class Table(ABC): error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + Workflow version 1 servers default to skip with a 5% failure ceiling + and publish successful output before reporting a threshold failure. + Older deployments retain their existing defaults. max_failed_fraction: float, optional Under a skip policy, fail the job once more than this share of rows (0 to 1) has failed. LanceDB Enterprise only. @@ -3382,6 +3393,23 @@ class Table(ABC): max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. + retry_errors: bool, default False + Select current failed rows on the server. Cannot be combined with + ``where``. Requires Enterprise workflow version 1 or later. + retry_job_id: str, optional + Restrict a failed-row retry to errors recorded by this job. + retry_error_type: str, optional + Restrict a failed-row retry to this exception class. + include_quarantined: bool, default False + Explicitly release and include quarantined rows in a failed-row retry. + function_version: str, optional + Atomically rebind this column's Function to the specified immutable + version. Requires Enterprise workflow version 1 or later. + recompute: {"failed", "all", "none"}, optional + Which rows to recompute during an upgrade. Requires + ``function_version``; the default is ``all``. ``failed`` selects + current failures, and ``none`` preserves existing values. Quarantined + rows stay excluded unless explicitly included in a failed-row retry. Returns ------- @@ -3412,6 +3440,12 @@ class Table(ABC): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> Job[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job @@ -3486,6 +3520,9 @@ class Table(ABC): error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + Workflow version 1 servers default to skip with a 5% failure ceiling + and publish successful output before reporting a threshold failure. + Older deployments retain their existing defaults. max_failed_fraction: float, optional Under a skip policy, fail the job once more than this share of rows (0 to 1) has failed. LanceDB Enterprise only. @@ -3503,6 +3540,23 @@ class Table(ABC): max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. + retry_errors: bool, default False + Select current failed rows on the server. Cannot be combined with + ``where``. Requires Enterprise workflow version 1 or later. + retry_job_id: str, optional + Restrict a failed-row retry to errors recorded by this job. + retry_error_type: str, optional + Restrict a failed-row retry to this exception class. + include_quarantined: bool, default False + Explicitly release and include quarantined rows in a failed-row retry. + function_version: str, optional + Atomically rebind this column's Function to the specified immutable + version. Requires Enterprise workflow version 1 or later. + recompute: {"failed", "all", "none"}, optional + Which rows to recompute during an upgrade. Requires + ``function_version``; the default is ``all``. ``failed`` selects + current failures, and ``none`` preserves existing values. Quarantined + rows stay excluded unless explicitly included in a failed-row retry. Returns ------- @@ -3525,22 +3579,104 @@ class Table(ABC): 'finished' """ + def retry_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + **options: Any, + ) -> Job[RefreshColumnJobResult]: + """Start a job for exactly the current failed rows. + + Stable row identities survive compaction. Set ``function_version`` to + upgrade and retry failures atomically. ``include_quarantined=True`` + explicitly releases quarantined rows before retrying them. + + >>> job = table.retry_failed("sharpness") # doctest: +SKIP + >>> result = job.wait() # doctest: +SKIP + """ + return self.refresh_column_async( + column, + retry_errors=True, + retry_error_type=error_type, + retry_job_id=job_id, + include_quarantined=include_quarantined, + function_version=function_version, + recompute="failed" if function_version is not None else None, + **options, + ) + + def upgrade_column( + self, + column: str, + *, + version: str, + recompute: Literal["failed", "all", "none"] = "all", + **options: Any, + ) -> Job[RefreshColumnJobResult]: + """Upgrade a Function binding while keeping its columns available. + + ``failed`` recomputes current failures, ``all`` recomputes all live rows, + and ``none`` preserves existing values. New and changed rows use the new + version; ``function_provenance`` identifies each value's producing version. + """ + return self.refresh_column_async( + column, function_version=version, recompute=recompute, **options + ) + + def quarantine_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + after_attempts: Optional[int] = None, + quarantined: bool = True, + ) -> int: + """Quarantine current failures, or release them with ``quarantined=False``. + + Normal and automatic refreshes skip quarantined rows. ``after_attempts`` + restricts the selection to rows with at least that many failed calls. + Returns the number of selected rows. LanceDB Enterprise only. + """ + raise NotImplementedError("Function quarantine requires LanceDB Enterprise") + + def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> FunctionProvenance: + """Read each returned row's producing Function version and job. + + ``version`` selects a table snapshot. Check ``truncated`` before treating + the returned records as a complete snapshot. LanceDB Enterprise only. + """ + raise NotImplementedError("Function provenance requires LanceDB Enterprise") + @abstractmethod def function_errors( self, job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, + history: bool = False, ) -> "FunctionErrors": """ The per-row errors Function refreshes recorded on this table. - A refresh running under a skip policy records each row it skipped - with the input that failed and the error. This lists those records, - newest job first, plus a summary for any fragment whose per-row - detail was capped. LanceDB Enterprise only; reading errors - needs read access to the table, since a message carries the value - that failed. + A refresh running under a skip policy records each row it skipped. + On servers advertising workflow version 1 or later, the default lists + current unresolved failures, deduplicated by row and Function column, + with attempt counts and first/last failure times. ``history=True`` + returns retained observations, including repaired failures. Older servers + keep their legacy listing behavior and reject explicit history requests. + LanceDB Enterprise only; reading errors needs table read access because + messages can include the input that failed. Parameters ---------- @@ -3550,6 +3686,10 @@ class Table(ABC): Only errors on this column. limit: int, optional At most this many records (server default 10000, cap 100000). + history: bool, default False + Include retained historical errors instead of current failures. + Requires Enterprise workflow version 1 or later. Historical records + cannot be used with the current-input ``rows()`` helper. Returns ------- @@ -5706,6 +5846,12 @@ class LanceTable(Table): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> "RefreshColumnResult": """Fill a computed column's unfilled rows and recompute those whose inputs changed. See @@ -5730,6 +5876,12 @@ class LanceTable(Table): init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ) ) @@ -5754,6 +5906,12 @@ class LanceTable(Table): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> Job[RefreshColumnJobResult]: """Fill a computed column's unfilled rows and recompute those whose inputs changed, returning a handle to the refresh job. See @@ -5780,6 +5938,12 @@ class LanceTable(Table): init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ) ) ) @@ -5789,11 +5953,44 @@ class LanceTable(Table): job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, + history: bool = False, ) -> "FunctionErrors": """The per-row errors Function refreshes recorded on this table. See [`Table.function_errors`][lancedb.table.Table.function_errors].""" return LOOP.run( - self._table.function_errors(job_id=job_id, column=column, limit=limit) + self._table.function_errors( + job_id=job_id, column=column, limit=limit, history=history + ) + ).as_sync(self) + + def quarantine_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + after_attempts: Optional[int] = None, + quarantined: bool = True, + ) -> int: + return LOOP.run( + self._table.quarantine_failed( + column, + error_type=error_type, + job_id=job_id, + after_attempts=after_attempts, + quarantined=quarantined, + ) + ) + + def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> FunctionProvenance: + return LOOP.run( + self._table.function_provenance(column, limit=limit, version=version) ) def column_statuses( @@ -8221,6 +8418,12 @@ class AsyncTable: init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> RefreshColumnResult: """ Fill the rows of a computed column that hold no value yet. @@ -8296,6 +8499,9 @@ class AsyncTable: error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + Workflow version 1 servers default to skip with a 5% failure ceiling + and publish successful output before reporting a threshold failure. + Older deployments retain their existing defaults. max_failed_fraction: float, optional Under a skip policy, fail the job once more than this share of rows (0 to 1) has failed. LanceDB Enterprise only. @@ -8313,6 +8519,23 @@ class AsyncTable: max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. + retry_errors: bool, default False + Select current failed rows on the server. Cannot be combined with + ``where``. Requires Enterprise workflow version 1 or later. + retry_job_id: str, optional + Restrict a failed-row retry to errors recorded by this job. + retry_error_type: str, optional + Restrict a failed-row retry to this exception class. + include_quarantined: bool, default False + Explicitly release and include quarantined rows in a failed-row retry. + function_version: str, optional + Atomically rebind this column's Function to the specified immutable + version. Requires Enterprise workflow version 1 or later. + recompute: {"failed", "all", "none"}, optional + Which rows to recompute during an upgrade. Requires + ``function_version``; the default is ``all``. ``failed`` selects + current failures, and ``none`` preserves existing values. Quarantined + rows stay excluded unless explicitly included in a failed-row retry. Returns ------- @@ -8340,6 +8563,77 @@ class AsyncTable: init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, + ) + + async def retry_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + **options: Any, + ) -> AsyncJob[RefreshColumnJobResult]: + """Start an exact failed-row retry; see ``Table.retry_failed``.""" + return await self.refresh_column_async( + column, + retry_errors=True, + retry_error_type=error_type, + retry_job_id=job_id, + include_quarantined=include_quarantined, + function_version=function_version, + recompute="failed" if function_version is not None else None, + **options, + ) + + async def upgrade_column( + self, + column: str, + *, + version: str, + recompute: Literal["failed", "all", "none"] = "all", + **options: Any, + ) -> AsyncJob[RefreshColumnJobResult]: + """Upgrade the Function and choose which rows to recompute.""" + return await self.refresh_column_async( + column, function_version=version, recompute=recompute, **options + ) + + async def quarantine_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + after_attempts: Optional[int] = None, + quarantined: bool = True, + ) -> int: + """Quarantine current failures or release them for later refreshes.""" + return await self._inner.quarantine_function_errors( + column, + quarantined=quarantined, + error_type=error_type, + job_id=job_id, + after_attempts=after_attempts, + ) + + async def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> FunctionProvenance: + """Read per-row producing versions at a table snapshot.""" + return FunctionProvenance.from_json( + await self._inner.function_provenance(column, limit=limit, version=version) ) async def function_errors( @@ -8347,16 +8641,19 @@ class AsyncTable: job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, - ) -> "FunctionErrors": + history: bool = False, + ) -> "AsyncFunctionErrors": """ The per-row errors Function refreshes recorded on this table. - A refresh running under a skip policy records each row it skipped - with the input that failed and the error. This lists those records, - newest job first, plus a summary for any fragment whose per-row - detail was capped. LanceDB Enterprise only; reading errors - needs read access to the table, since a message carries the value - that failed. + A refresh running under a skip policy records each row it skipped. + On servers advertising workflow version 1 or later, the default lists + current unresolved failures, deduplicated by row and Function column, + with attempt counts and first/last failure times. ``history=True`` + returns retained observations, including repaired failures. Older servers + keep their legacy listing behavior and reject explicit history requests. + LanceDB Enterprise only; reading errors needs table read access because + messages can include the input that failed. Parameters ---------- @@ -8366,10 +8663,14 @@ class AsyncTable: Only errors on this column. limit: int, optional At most this many records (server default 10000, cap 100000). + history: bool, default False + Include retained historical errors instead of current failures. + Requires Enterprise workflow version 1 or later. Historical records + cannot be used with the current-input ``rows()`` helper. Returns ------- - FunctionErrors + AsyncFunctionErrors ``records``, ``fragments`` and ``truncated``, the last saying whether the listing stopped at its limit. @@ -8427,9 +8728,10 @@ class AsyncTable: >>> if errors.truncated: # doctest: +SKIP ... print("listing stopped at the limit") """ - return await self._inner.function_errors( - job_id=job_id, column=column, limit=limit + raw = await self._inner.function_errors( + job_id=job_id, column=column, limit=limit, history=history ) + return AsyncFunctionErrors(raw, self, history=history) async def column_statuses( self, column: Optional[str] = None @@ -8478,6 +8780,12 @@ class AsyncTable: init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> AsyncJob[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job @@ -8552,6 +8860,9 @@ class AsyncTable: error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + Workflow version 1 servers default to skip with a 5% failure ceiling + and publish successful output before reporting a threshold failure. + Older deployments retain their existing defaults. max_failed_fraction: float, optional Under a skip policy, fail the job once more than this share of rows (0 to 1) has failed. LanceDB Enterprise only. @@ -8569,6 +8880,23 @@ class AsyncTable: max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. + retry_errors: bool, default False + Select current failed rows on the server. Cannot be combined with + ``where``. Requires Enterprise workflow version 1 or later. + retry_job_id: str, optional + Restrict a failed-row retry to errors recorded by this job. + retry_error_type: str, optional + Restrict a failed-row retry to this exception class. + include_quarantined: bool, default False + Explicitly release and include quarantined rows in a failed-row retry. + function_version: str, optional + Atomically rebind this column's Function to the specified immutable + version. Requires Enterprise workflow version 1 or later. + recompute: {"failed", "all", "none"}, optional + Which rows to recompute during an upgrade. Requires + ``function_version``; the default is ``all``. ``failed`` selects + current failures, and ``none`` preserves existing values. Quarantined + rows stay excluded unless explicitly included in a failed-row retry. Returns ------- @@ -8613,6 +8941,12 @@ class AsyncTable: init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ), RefreshColumnJobResult.from_json, ) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 587e2d587..2cacc4716 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -21,6 +21,7 @@ import threading import time from urllib.parse import parse_qs, urlparse from unittest.mock import MagicMock, patch +from types import SimpleNamespace import uuid import warnings from packaging.version import Version @@ -2382,7 +2383,7 @@ async def test_remote_refresh_async_returns_typed_terminal_result( result = job.wait(timeout=timedelta(seconds=30)) assert isinstance(result, lancedb.RefreshColumnResult) - assert result.model_dump() == terminal_result + assert result.model_dump(exclude_defaults=True) == terminal_result assert result.rows_filled == 12 assert result.version == 8 @@ -7845,3 +7846,211 @@ def test_remote_fts_and_rejects_legacy_server(): with query_test_table(handler, vector_columns={}) as table: with pytest.raises(NotImplementedError, match="server version 0.3.0"): table.search("gripper closed", query_type="fts", operator="AND").to_list() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("async_table", [False, True]) +async def test_function_failure_workflow_uses_exact_retry_and_upgrade_apis(async_table): + received = [] + result = { + "rows_assigned": 1000, + "rows_failed": 100, + "rows_remaining": 0, + "source_version": 7, + "published_version": 8, + "error_groups": [ + { + "column": "derived", + "error_type": "RowTimeoutError", + "error_message": "timeout", + "rows_failed": 100, + } + ], + "error_groups_truncated": False, + } + + def handler(request): + length = int(request.headers.get("Content-Length", 0)) + body = json.loads(request.rfile.read(length)) if length else {} + received.append((request.path, body)) + status = 200 + if request.path == "/v1/table/test/describe/": + response = {"version": 8, "schema": {"fields": []}} + elif request.path == "/v1/table/test/backfill_column": + status = 202 + response = {"job_id": "refresh-1"} + elif request.path == "/v1/jobs/describe": + response = { + "job_id": "refresh-1", + "job_type": "function_refresh", + "job_state": "DONE", + "result": result, + } + elif request.path == "/v1/table/test/errors/quarantine": + response = {"rows_affected": 100} + elif request.path == "/v1/table/test/function_provenance": + response = { + "records": [ + { + "column": "derived", + "job_id": "refresh-1", + "function_name": "check", + "function_version": "2", + "row_id": 42, + "source_version": 7, + "published_version": 8, + } + ], + "truncated": False, + } + elif request.path == "/v1/table/test/errors": + response = { + "records": [], + "fragments": [], + "truncated": False, + "workflow_version": 1, + } + else: + status = 404 + response = {} + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + retry_options = dict( + error_type="ValueError", + job_id="first", + include_quarantined=True, + function_version="2", + max_failed_fraction=1.0, + ) + if async_table: + async with mock_lancedb_connection_async(handler) as db: + table = await db.open_table("test") + job = await table.retry_failed("derived", **retry_options) + terminal = await job.wait() + await table.upgrade_column("derived", version="3", recompute="none") + affected = await table.quarantine_failed("derived", after_attempts=3) + provenance = await table.function_provenance("derived") + errors = await table.function_errors(column="derived", history=True) + else: + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + terminal = table.retry_failed("derived", **retry_options).wait() + table.upgrade_column("derived", version="3", recompute="none") + affected = table.quarantine_failed("derived", after_attempts=3) + provenance = table.function_provenance("derived") + errors = table.function_errors(column="derived", history=True) + + refreshes = [body for path, body in received if path.endswith("backfill_column")] + assert refreshes == [ + { + "column": "derived", + "retry_errors": True, + "retry_job_id": "first", + "retry_error_type": "ValueError", + "include_quarantined": True, + "function_version": "2", + "recompute": "failed", + "max_failed_fraction": 1.0, + }, + {"column": "derived", "function_version": "3", "recompute": "none"}, + ] + assert terminal.rows_assigned == 1000 + assert terminal.error_groups[0].rows_failed == 100 + assert affected == 100 + assert provenance.records[0].function_version == "2" + assert provenance.records[0].row_id == 42 + assert errors.summary() == [] + assert ("/v1/table/test/errors", {"column": "derived", "history": True}) in received + + +def test_function_error_rows_returns_all_inputs_and_preserves_multiple_column_errors( + tmp_path, +): + db = lancedb.connect(tmp_path) + table = db.create_table("inputs", [{"id": index} for index in range(16)]) + inputs = table.search().select(["id", "_rowid", "_rowaddr"]).limit(16).to_arrow() + records = [ + SimpleNamespace( + column="first", + row_id=row_id, + row_address=999999, + row_offset=0, + input=None, + error_type="ValueError", + error_message="corrupt", + attempts=3, + function_version="1", + job_id="first", + first_seen_at_millis=100, + last_seen_at_millis=200, + quarantined=False, + ) + for row_id in inputs.column("_rowid").to_pylist() + ] + duplicate = copy.copy(records[0]) + duplicate.column = "second" + records.append(duplicate) + errors = lancedb.FunctionErrors( + SimpleNamespace( + records=records, fragments=[], truncated=False, workflow_version=1 + ), + table, + ) + rows = errors.rows(columns=["id"]) + assert rows.num_rows == 17 + assert sorted(set(rows.column("id").to_pylist())) == list(range(16)) + assert rows.column("__function_error").type.field("column").name == "column" + assert [group.rows_failed for group in errors.summary()] == [16, 1] + legacy = copy.copy(records[0]) + legacy.row_id = None + legacy.row_address = inputs.column("_rowaddr")[0].as_py() + legacy_errors = lancedb.FunctionErrors( + SimpleNamespace( + records=[legacy], fragments=[], truncated=False, workflow_version=1 + ), + table, + ) + assert legacy_errors.rows(columns=["id"]).column("id").to_pylist() == [0] + + incomplete = lancedb.FunctionErrors( + SimpleNamespace( + records=records, fragments=[], truncated=True, workflow_version=1 + ), + table, + ) + with pytest.raises(ValueError, match="incomplete"): + incomplete.rows() + + +def test_exact_function_retries_fail_before_writing_to_older_servers(): + writes = [] + + def handler(request): + length = int(request.headers.get("Content-Length", 0)) + body = request.rfile.read(length) if length else b"" + if request.path == "/v1/table/test/describe/": + response = {"version": 1, "schema": {"fields": []}} + elif request.path == "/v1/table/test/errors": + response = {"records": [], "fragments": [], "truncated": False} + else: + writes.append((request.path, body)) + response = {} + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + with pytest.raises(NotImplementedError, match="server does not support"): + table.retry_failed("derived") + with pytest.raises(NotImplementedError, match="server does not support"): + table.upgrade_column("derived", version="2", recompute="failed") + with pytest.raises(NotImplementedError, match="server does not support"): + table.function_errors(history=True) + with pytest.raises(NotImplementedError, match="server does not support"): + table.function_errors().summary() + assert writes == [] diff --git a/python/src/table.rs b/python/src/table.rs index 25a99e5db..3bc23ec95 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -48,6 +48,12 @@ mod scannable; /// Keyword arguments shared by `refresh_column` and `refresh_column_async`. struct RefreshColumnArgs { + retry_errors: bool, + retry_job_id: Option, + retry_error_type: Option, + include_quarantined: bool, + function_version: Option, + recompute: Option, where_clause: Option, batch_size: Option, max_concurrency: Option, @@ -259,6 +265,12 @@ fn parse_planning_workers( fn refresh_column_options(args: RefreshColumnArgs) -> PyResult { let RefreshColumnArgs { + retry_errors, + retry_job_id, + retry_error_type, + include_quarantined, + function_version, + recompute, where_clause, batch_size, max_concurrency, @@ -278,6 +290,17 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult for RefreshColumnResult { #[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] #[derive(Clone, Debug)] pub struct FunctionErrorRecord { + pub first_seen_at_millis: Option, + pub last_seen_at_millis: Option, + pub quarantined: bool, + pub input: Option, pub attempts: Option, pub job_id: String, pub fragment_id: u64, @@ -915,6 +942,10 @@ impl FunctionErrorRecord { impl From for FunctionErrorRecord { fn from(record: lancedb::function::FunctionErrorRecord) -> Self { Self { + first_seen_at_millis: record.first_seen_at_millis, + last_seen_at_millis: record.last_seen_at_millis, + quarantined: record.quarantined, + input: record.input.map(|value| value.to_string()), attempts: record.attempts, job_id: record.job_id, fragment_id: record.fragment_id, @@ -968,6 +999,8 @@ impl From for FunctionErrorFragment { #[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] #[derive(Clone, Debug)] pub struct FunctionErrors { + pub workflow_version: Option, + pub error_groups_json: String, pub records: Vec, pub fragments: Vec, pub truncated: bool, @@ -988,6 +1021,9 @@ impl FunctionErrors { impl From for FunctionErrors { fn from(errors: lancedb::function::FunctionErrors) -> Self { Self { + workflow_version: errors.workflow_version, + error_groups_json: serde_json::to_string(&errors.error_groups) + .expect("serializable Function error groups"), records: errors.records.into_iter().map(Into::into).collect(), fragments: errors.fragments.into_iter().map(Into::into).collect(), truncated: errors.truncated, @@ -2599,7 +2635,7 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column<'py>( self_: PyRef<'py, Self>, @@ -2621,8 +2657,20 @@ impl Table { init_timeout_seconds: Option, num_workers: Option, max_executor_processes_per_worker: Option, + retry_errors: bool, + retry_job_id: Option, + retry_error_type: Option, + include_quarantined: bool, + function_version: Option, + recompute: Option, ) -> PyResult> { let options = refresh_column_options(RefreshColumnArgs { + retry_errors, + retry_job_id, + retry_error_type, + include_quarantined, + function_version, + recompute, where_clause: r#where, batch_size, max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, @@ -2651,7 +2699,7 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column_async<'py>( self_: PyRef<'py, Self>, @@ -2673,8 +2721,20 @@ impl Table { init_timeout_seconds: Option, num_workers: Option, max_executor_processes_per_worker: Option, + retry_errors: bool, + retry_job_id: Option, + retry_error_type: Option, + include_quarantined: bool, + function_version: Option, + recompute: Option, ) -> PyResult> { let options = refresh_column_options(RefreshColumnArgs { + retry_errors, + retry_job_id, + retry_error_type, + include_quarantined, + function_version, + recompute, where_clause: r#where, batch_size, max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, @@ -2703,18 +2763,20 @@ impl Table { }) } - #[pyo3(signature = (job_id=None, column=None, limit=None))] + #[pyo3(signature = (job_id=None, column=None, limit=None, history=false))] pub fn function_errors( self_: PyRef<'_, Self>, job_id: Option, column: Option, limit: Option, + history: bool, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); let request = lancedb::function::FunctionErrorsRequest { job_id, column, limit, + history, }; future_into_py(self_.py(), async move { let errors = inner.function_errors(request).await.infer_error()?; @@ -2722,6 +2784,53 @@ impl Table { }) } + #[pyo3(signature = (column, *, quarantined=true, job_id=None, error_type=None, after_attempts=None))] + pub fn quarantine_function_errors( + self_: PyRef<'_, Self>, + column: String, + quarantined: bool, + job_id: Option, + error_type: Option, + after_attempts: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + inner + .quarantine_function_errors( + &column, + lancedb::function::FunctionQuarantineOptions { + quarantined, + job_id, + error_type, + after_attempts, + }, + ) + .await + .infer_error() + }) + } + + #[pyo3(signature = (column, *, limit=None, version=None))] + pub fn function_provenance( + self_: PyRef<'_, Self>, + column: String, + limit: Option, + version: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let result = inner + .function_provenance( + &column, + lancedb::function::FunctionProvenanceOptions { limit, version }, + ) + .await + .infer_error()?; + serde_json::to_string(&result) + .map_err(|error| PyRuntimeError::new_err(error.to_string())) + }) + } + #[pyo3(signature = (column=None))] pub fn column_statuses( self_: PyRef<'_, Self>, diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 4e7157c37..e4fff29c5 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -1308,6 +1308,12 @@ pub struct FunctionRefreshPlan { /// Enterprise decodes the same value from the durable job's terminal payload. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RefreshColumnResult { + /// Grouped row failures, when the server reports them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub error_groups: Vec, + /// Whether the grouped counts omit any failures. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub error_groups_truncated: bool, /// Rows assigned a value by this refresh. pub rows_assigned: u64, /// Rows whose computation failed. @@ -1330,6 +1336,8 @@ pub struct RefreshColumnResult { /// covers every refresh of every column. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct FunctionErrorsRequest { + /// Include retained historical errors, including repaired rows. + pub history: bool, /// Only errors recorded by this job. pub job_id: Option, /// Only errors on this column. @@ -1340,6 +1348,11 @@ pub struct FunctionErrorsRequest { } impl FunctionErrorsRequest { + /// Include retained historical records instead of current failures. + pub fn history(mut self, history: bool) -> Self { + self.history = history; + self + } /// A request with no filter. pub fn new() -> Self { Self::default() @@ -1369,6 +1382,18 @@ impl FunctionErrorsRequest { /// read access to the table. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionErrorRecord { + /// Earliest retained failure time for this current failure. + #[serde(default)] + pub first_seen_at_millis: Option, + /// Most recent failure time. + #[serde(default)] + pub last_seen_at_millis: Option, + /// Whether normal refreshes skip this row until explicitly retried. + #[serde(default)] + pub quarantined: bool, + /// Source identities for a materialized-view Function invocation. + #[serde(default)] + pub input: Option, /// Number of user-code calls for this failed invocation, when recorded. #[serde(default, skip_serializing_if = "Option::is_none")] pub attempts: Option, @@ -1429,6 +1454,12 @@ pub struct FunctionErrorFragment { /// A table's per-row Function errors; see [`crate::Table::function_errors`]. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionErrors { + /// Version of the server's current-failure, retry, upgrade, and quarantine contract. + #[serde(default)] + pub workflow_version: Option, + /// Grouped causes for the returned records. Counts are bounded by the listing. + #[serde(default)] + pub error_groups: Vec, /// The recorded rows, newest job first. pub records: Vec, /// Fragments whose detail was capped. @@ -1439,6 +1470,79 @@ pub struct FunctionErrors { pub truncated: bool, } +/// Which existing rows to recompute when upgrading a Function column. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FunctionRecompute { + /// Recompute exactly the current failures. + Failed, + /// Recompute all live rows. + All, + /// Preserve existing values; new and changed rows use the new Function. + None, +} + +/// One cause in a Function failure listing or refresh result. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionErrorGroup { + pub column: String, + pub error_type: String, + pub error_message: String, + pub rows_failed: u64, +} + +/// Selection and state for explicitly quarantining or releasing failed rows. +#[derive(Debug, Clone, Serialize)] +pub struct FunctionQuarantineOptions { + pub quarantined: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub job_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub error_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub after_attempts: Option, +} + +impl Default for FunctionQuarantineOptions { + fn default() -> Self { + Self { + quarantined: true, + job_id: None, + error_type: None, + after_attempts: None, + } + } +} + +/// Which snapshot and how much producing-version metadata to read. +#[derive(Debug, Clone, Default, Serialize)] +pub struct FunctionProvenanceOptions { + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// The Function and job that produced one stored value. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FunctionValueProvenance { + pub job_id: String, + pub column: String, + pub function_name: String, + pub function_version: String, + pub row_id: Option, + pub row_address: Option, + pub source_version: u64, + pub published_version: u64, +} + +/// A bounded set of per-row producing-version records. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FunctionProvenance { + pub records: Vec, + pub truncated: bool, +} + impl RefreshColumnResult { /// Deprecated compatibility alias for `rows_assigned`. pub fn rows_filled(&self) -> u64 { @@ -1465,6 +1569,8 @@ mod refresh_result_tests { source_version: 7, published_version: Some(8), plan, + error_groups: Vec::new(), + error_groups_truncated: false, } } diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index f89be7e69..ad53f8722 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -969,6 +969,33 @@ impl RemoteTable { } } + async fn require_function_failure_workflow(&self) -> Result<()> { + let mut body = serde_json::json!({"limit": 1}); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/errors", self.identifier)) + .json(&body); + let (request_id, response) = self.send(request, true).await?; + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let value: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: error.into(), + request_id, + status_code: None, + })?; + if value + .get("workflow_version") + .and_then(serde_json::Value::as_u64) + .is_some_and(|version| version >= 1) + { + Ok(()) + } else { + Err(Error::NotSupported { message: "The server does not support the Function row-failure workflow; upgrade the server before retrying, upgrading, or quarantining rows".into() }) + } + } + async fn describe(&self) -> Result { self.describe_read_snapshot(self.snapshot_read_state().await) .await @@ -4322,6 +4349,9 @@ impl BaseTable for RemoteTable { ) -> Result> { options.validate()?; self.check_mutable().await?; + if options.retry_errors == Some(true) || options.function_version.is_some() { + self.require_function_failure_workflow().await?; + } let mut body = serde_json::to_value(&options).map_err(|e| Error::Runtime { message: format!("failed to serialize refresh options: {e}"), })?; @@ -4363,7 +4393,13 @@ impl BaseTable for RemoteTable { &self, request: &crate::function::FunctionErrorsRequest, ) -> Result { + if request.history { + self.require_function_failure_workflow().await?; + } let mut body = serde_json::json!({}); + if request.history { + body["history"] = serde_json::json!(true); + } if let Some(job_id) = &request.job_id { body["job_id"] = serde_json::json!(job_id); } @@ -4388,6 +4424,70 @@ impl BaseTable for RemoteTable { }) } + async fn quarantine_function_errors( + &self, + column: &str, + options: &crate::function::FunctionQuarantineOptions, + ) -> Result { + self.require_function_failure_workflow().await?; + self.check_mutable().await?; + if options.after_attempts == Some(0) { + return Err(Error::InvalidInput { + message: "after_attempts must be at least 1".into(), + }); + } + let mut body = serde_json::json!({"column": column, "quarantined": options.quarantined, + "job_id": options.job_id, "error_type": options.error_type, "after_attempts": options.after_attempts}); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/errors/quarantine", self.identifier)) + .json(&body); + let (request_id, response) = self.send(request, false).await?; + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let value: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: error.into(), + request_id: request_id.clone(), + status_code: None, + })?; + value + .get("rows_affected") + .and_then(serde_json::Value::as_u64) + .ok_or_else(|| Error::Http { + source: "Function quarantine response has no rows_affected".into(), + request_id, + status_code: None, + }) + } + + async fn function_provenance( + &self, + column: &str, + options: &crate::function::FunctionProvenanceOptions, + ) -> Result { + self.require_function_failure_workflow().await?; + let mut body = serde_json::json!({"column": column, "limit": options.limit, + "version": match options.version { Some(version) => version, None => self.version().await? }}); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!( + "/v1/table/{}/function_provenance", + self.identifier + )) + .json(&body); + let (request_id, response) = self.send(request, true).await?; + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + serde_json::from_str(&body).map_err(|error| Error::Http { + source: error.into(), + request_id, + status_code: None, + }) + } + async fn function_column_statuses( &self, column: Option<&str>, @@ -12925,6 +13025,10 @@ mod tests { assert_eq!( errors.records, [FunctionErrorRecord { + first_seen_at_millis: None, + last_seen_at_millis: None, + quarantined: false, + input: None, attempts: Some(3), job_id: "j-7".into(), fragment_id: 3, diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 00505220b..f247a386f 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -980,6 +980,28 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { .append_to("per-row Function errors are recorded only in LanceDB Enterprise"), }) } + /// Change the quarantine state of current failed rows. + async fn quarantine_function_errors( + &self, + _column: &str, + _options: &crate::function::FunctionQuarantineOptions, + ) -> Result { + Err(Error::NotSupported { + message: "Function quarantine requires LanceDB Enterprise".into(), + }) + } + + /// Read per-row producing Function versions from LanceDB Enterprise. + async fn function_provenance( + &self, + _column: &str, + _options: &crate::function::FunctionProvenanceOptions, + ) -> Result { + Err(Error::NotSupported { + message: "Function provenance requires LanceDB Enterprise".into(), + }) + } + /// Exact four-way freshness status for Function-backed output columns. /// /// `column` filters to one user-visible output; `None` returns every @@ -2285,6 +2307,30 @@ impl Table { /// refreshes ignore the batch-size and GPU options, and reject resource /// budgets, publication thresholds, and other Enterprise-only options. /// + /// Native failed-row retry and upgrades require Enterprise workflow version + /// 1 or later. The SDK checks the server capability before submitting them. + /// An upgrade targets an existing immutable version of the same Function. + /// + /// ``` + /// # use lancedb::{Table, table::RefreshColumnOptions}; + /// use lancedb::function::FunctionRecompute; + /// # async fn retry_and_upgrade(table: &Table) -> lancedb::Result<()> { + /// let retry = table.refresh_column_async_with_options( + /// "embedding", + /// RefreshColumnOptions::default() + /// .retry_errors(true) + /// .retry_error_type("ValueError"), + /// ).await?; + /// retry.wait().await?; + /// let upgrade = table.refresh_column_async_with_options( + /// "embedding", + /// RefreshColumnOptions::default().upgrade("2", FunctionRecompute::Failed), + /// ).await?; + /// upgrade.wait().await?; + /// # Ok(()) + /// # } + /// ``` + /// /// ``` /// # use lancedb::{Table, table::RefreshColumnOptions}; /// # async fn refresh(table: &Table) -> Result<(), Box> { @@ -2388,6 +2434,9 @@ impl Table { /// A record carries a stable `row_id` when the refresh source used stable /// row IDs. Prefer it over the physical `row_address` for retries: /// compaction and rewrite can change the address. + /// With Enterprise workflow version 1, the default lists current failures; + /// [`FunctionErrorsRequest::history`] selects retained historical attempts. + /// Earlier servers retain their existing default behavior. /// /// LanceDB Enterprise only, and the caller needs read access /// to the table, since a message carries the value that failed. @@ -2413,6 +2462,62 @@ impl Table { self.inner.function_errors(&request).await } + /// Quarantine current failures, or release them with `quarantined=false`. + /// Normal and automatic Function refreshes skip quarantined rows. + /// Requires Enterprise workflow version 1 or later. + /// + /// ``` + /// # use lancedb::Table; + /// use lancedb::function::FunctionQuarantineOptions; + /// # async fn quarantine(table: &Table) -> lancedb::Result<()> { + /// let count = table.quarantine_function_errors( + /// "embedding", + /// FunctionQuarantineOptions { + /// after_attempts: Some(3), + /// ..Default::default() + /// }, + /// ).await?; + /// println!("quarantined {count} rows"); + /// # Ok(()) + /// # } + /// ``` + pub async fn quarantine_function_errors( + &self, + column: &str, + options: crate::function::FunctionQuarantineOptions, + ) -> Result { + self.inner + .quarantine_function_errors(column, &options) + .await + } + + /// Read the producing Function version and job for each returned row. + /// Inspect `truncated` before treating this as a complete snapshot. + /// Requires Enterprise workflow version 1 or later. + /// + /// ``` + /// # use lancedb::Table; + /// use lancedb::function::FunctionProvenanceOptions; + /// # async fn provenance(table: &Table) -> lancedb::Result<()> { + /// let values = table.function_provenance( + /// "embedding", FunctionProvenanceOptions::default(), + /// ).await?; + /// if !values.truncated { + /// for value in values.records { + /// println!("{:?}: {}", value.row_id, value.function_version); + /// } + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn function_provenance( + &self, + column: &str, + options: crate::function::FunctionProvenanceOptions, + ) -> Result { + self.inner.function_provenance(column, &options).await + } + /// Change a column's name, data type, or nullability. /// /// Each alteration must specify at least one of `rename`, `data_type`, or diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index f6bab98f5..78530497f 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -212,6 +212,24 @@ impl FunctionRefreshPlanningConfig { #[derive(Debug, Clone, Default, Serialize)] #[non_exhaustive] pub struct RefreshColumnOptions { + /// Select exactly the current failed rows. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_errors: Option, + /// Restrict retry selection to this job. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_job_id: Option, + /// Restrict retry selection to this exception class. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_error_type: Option, + /// Explicitly release and retry quarantined rows. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub include_quarantined: Option, + /// Upgrade the bound Function to this exact version. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub function_version: Option, + /// Rows recomputed by a Function upgrade. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub recompute: Option, /// Only refresh the rows matching this SQL filter. Enterprise only. #[serde(rename = "where", skip_serializing_if = "Option::is_none")] pub where_clause: Option, @@ -290,6 +308,40 @@ pub struct RefreshColumnOptions { } impl RefreshColumnOptions { + /// Retry only current failures, using the server's row identities. + pub fn retry_errors(mut self, enabled: bool) -> Self { + self.retry_errors = Some(enabled); + self + } + + /// Restrict a failed-row retry to one recorded job. + pub fn retry_job_id(mut self, job_id: impl Into) -> Self { + self.retry_job_id = Some(job_id.into()); + self + } + + /// Restrict a failed-row retry to one exception class. + pub fn retry_error_type(mut self, error_type: impl Into) -> Self { + self.retry_error_type = Some(error_type.into()); + self + } + + /// Release quarantine when explicitly retrying failures. + pub fn include_quarantined(mut self, include: bool) -> Self { + self.include_quarantined = Some(include); + self + } + + /// Change the Function version and select the upgrade's recomputation policy. + pub fn upgrade( + mut self, + version: impl Into, + recompute: crate::function::FunctionRecompute, + ) -> Self { + self.function_version = Some(version.into()); + self.recompute = Some(recompute); + self + } /// Only refresh the rows matching `filter`. pub fn where_clause(mut self, filter: impl Into) -> Self { self.where_clause = Some(filter.into()); @@ -399,6 +451,12 @@ impl RefreshColumnOptions { /// The first set option a LanceDB Embedded refresh cannot honor, if any. pub fn enterprise_only_option(&self) -> Option<&'static str> { [ + ("retry_errors", self.retry_errors.is_some()), + ("retry_job_id", self.retry_job_id.is_some()), + ("retry_error_type", self.retry_error_type.is_some()), + ("include_quarantined", self.include_quarantined.is_some()), + ("function_version", self.function_version.is_some()), + ("recompute", self.recompute.is_some()), ("where", self.where_clause.is_some()), ("retry_policy", self.retry_policy.is_some()), ("error_policy", self.error_policy.is_some()), @@ -426,6 +484,31 @@ impl RefreshColumnOptions { /// Validate client-side constraints before any request is sent. pub fn validate(&self) -> Result<()> { + let retry = self.retry_errors == Some(true); + if (retry || self.function_version.is_some()) && self.where_clause.is_some() { + return Err(Error::InvalidInput { + message: "retry_errors and Function upgrades cannot be combined with where".into(), + }); + } + if !retry + && (self.retry_job_id.is_some() + || self.retry_error_type.is_some() + || self.include_quarantined == Some(true)) + { + return Err(Error::InvalidInput { + message: "retry filters require retry_errors=true".into(), + }); + } + if self + .function_version + .as_ref() + .is_some_and(|version| version.is_empty()) + || (self.recompute.is_some() && self.function_version.is_none()) + { + return Err(Error::InvalidInput { + message: "recompute requires a nonempty function_version".into(), + }); + } if self .where_clause .as_deref() @@ -780,6 +863,8 @@ pub(crate) async fn execute_refresh_column_async( let execution = execute_refresh_column_with_source(&table, &column).await?; table.bump_freshness(); Ok(crate::function::RefreshColumnResult { + error_groups: Vec::new(), + error_groups_truncated: false, rows_assigned: execution.result.rows_filled, rows_failed: 0, rows_remaining: 0, From 1670859327d5503e8bf7e02c58f93260da4881b4 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 17 Nov 2026 20:58:43 +0800 Subject: [PATCH 03/78] fix(deps): ignore unmaintained chrono family advisories (#5073) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `cargo deny` fails on main because RUSTSEC-2026-0543 (`chrono`), RUSTSEC-2026-0555 (`chrono-tz`) and RUSTSEC-2026-0542 (`humantime`) mark the chrono family unmaintained. Add exceptions reviewed on 2026-11-17, with the advisory links and the upstream migration constraint; none of the three is a vulnerability and RustSec lists no patched version for any of them (chrono recommends jiff/time). Dependency paths (from `cargo tree -i` at version fb34b1c7 of main): - `chrono` 0.4.45: arrow 59 / datafusion 55 and the lance stack, across the workspace. - `chrono-tz` 0.10.4: arrow-array → arrow → datafusion/lance. - `humantime` 2.3.0: lance, object_store (through datafusion), and xet-runtime. Clearing the advisories requires the arrow/datafusion/lance ecosystem to migrate off chrono; no upstream fix exists to consume. Also remove the RUSTSEC-2026-0441 `pin-utils` ignore, which the current lockfile no longer needs. Validation on commit 04259a04 (cargo-deny 0.21.0, the version the CI action installs): - Before: `cargo deny check advisories` failed on the three chrono-family advisories, and warned that the pin-utils ignore was not encountered. - After: `cargo deny check advisories bans licenses sources` passes all four checks, matching the Rust CI deny job. - `git diff --check` passes. --- deny.toml | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/deny.toml b/deny.toml index 458559936..b10550a54 100644 --- a/deny.toml +++ b/deny.toml @@ -132,13 +132,31 @@ ignore = [ { id = "RUSTSEC-2026-0398", reason = "zstd-safe 7 via arrow-ipc 58; affected seekable API is not enabled" }, { id = "RUSTSEC-2026-0403", reason = "zstd-safe 7 via arrow-ipc 58; affected streaming decoder API is unused" }, - # pin-utils: unmaintained; reviewed 2026-11-05. Transitive via - # aws-smithy-http/runtime/types, including aws-config -> lance-io. - # No safe upgrade exists; clearing requires AWS Smithy to migrate to - # core::pin::pin!, pin-project, or pin-project-lite. Revisit on AWS updates. + # pin-utils: unmaintained; reviewed 2026-11-05, removed 2026-11-17 after + # the lockfile dropped the aws-smithy pins that carried it. # https://rustsec.org/advisories/RUSTSEC-2026-0441 - # https://github.com/rustsec/advisory-db/issues/3314 - { id = "RUSTSEC-2026-0441", reason = "pin-utils unmaintained via AWS Smithy; no safe upgrade, awaiting upstream migration" }, + + # chrono: unmaintained; reviewed 2026-11-17. Informational notice, not a + # vulnerability. Transitive via arrow 59 / datafusion 55 and the lance + # stack throughout the workspace. RustSec lists no patched version and + # recommends jiff/time; clearing it requires the arrow/datafusion/lance + # ecosystem to migrate. + # https://rustsec.org/advisories/RUSTSEC-2026-0543 + { id = "RUSTSEC-2026-0543", reason = "chrono unmaintained via arrow/datafusion/lance; no fixed upstream release, awaiting ecosystem migration" }, + + # chrono-tz: unmaintained; reviewed 2026-11-17. Informational notice, not + # a vulnerability. Transitive via arrow-array → arrow → datafusion/lance. + # No patched version exists; clearing it needs the same ecosystem + # migration off chrono as RUSTSEC-2026-0543. + # https://rustsec.org/advisories/RUSTSEC-2026-0555 + { id = "RUSTSEC-2026-0555", reason = "chrono-tz unmaintained via arrow/datafusion/lance; no fixed upstream release" }, + + # humantime: unmaintained; reviewed 2026-11-17. Informational notice, not + # a vulnerability. Transitive via lance, object_store (through datafusion) + # and xet-runtime. No patched version exists; the advisory follows chrono's + # maintenance status. + # https://rustsec.org/advisories/RUSTSEC-2026-0542 + { id = "RUSTSEC-2026-0542", reason = "humantime unmaintained via lance/object_store/xet-runtime; no fixed upstream release" }, ] From 961a4518fd67677779e751de698c2815a6c318c3 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 17 Nov 2026 22:49:40 +0800 Subject: [PATCH 04/78] fix(remote): forward job statistics through refresh handles (#5071) A Function refresh submitted through the LanceDB SDK returns a handle wrapped for read-freshness tracking. lancedb/lancedb#5016 added canonical `Job::stats()` on the server-job handle, but the refresh wrapper did not forward `stats`. The returned handle therefore reported `job statistics is only available for server-side jobs`, while `db.open_job().stats()` returned the server report. Forward `stats` through the refresh wrapper and cover it at the public refresh entry point. The regression submits with `refresh_column_async`, then reads `stats` from that returned handle without reopening the job. With the forwarding removed, the test fails with the same `NotSupported` error; with the change, it passes. Validation on `57b20fb11`: the targeted Rust test passed, `cargo fmt --check` passed, and `cargo clippy -p lancedb --features remote --lib --tests -- -D warnings` passed. Part of ENT-3974. --- rust/lancedb/src/remote/table.rs | 43 ++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index ad53f8722..2ed46147d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -335,6 +335,10 @@ impl crate::job::JobHandle for FreshnessJob { crate::job::JobHandle::events(&self.inner, request).await } + async fn stats(&self) -> Result> { + crate::job::JobHandle::stats(&self.inner).await + } + async fn wait(&self) -> Result { crate::job::JobHandle::wait_with_progress(self, None).await } @@ -424,6 +428,10 @@ impl crate::job::JobHandle for MaterializedViewRefreshJob { crate::job::JobHandle::events(&self.inner, request).await } + async fn stats(&self) -> Result> { + crate::job::JobHandle::stats(&self.inner).await + } + async fn wait(&self) -> Result { crate::job::JobHandle::wait_with_progress(self, None).await } @@ -11601,6 +11609,19 @@ mod tests { .to_string(), ) .unwrap(), + "/v1/jobs/stats" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["job_id"], "job-1"); + http::Response::builder() + .status(200) + .body( + r#"{"job_id":"job-1","profile":{},"report":"Function job: finished\nRows: 1600\n"}"# + .to_string(), + ) + .unwrap() + } "/v1/table/ns$view/describe/" => http::Response::builder() .status(200) .body(r#"{"version":42,"schema":{"fields":[]}}"#.to_string()) @@ -11623,6 +11644,10 @@ mod tests { })); assert_eq!(job.id(), Some("job-1")); + assert_eq!( + job.stats().await.unwrap().as_deref(), + Some("Function job: finished\nRows: 1600\n") + ); let observations = Arc::new(Mutex::new(Vec::new())); let observed = observations.clone(); let result: RefreshMaterializedViewResult = if with_progress { @@ -13142,6 +13167,20 @@ mod tests { .body(events.clone()) .unwrap() } + "/v1/jobs/stats" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["job_id"], "j-42"); + http::Response::builder() + .status(200) + .body( + r#"{"job_id":"j-42","profile":{},"report":"Function job: finished\nRows: 1600\n"}"# + .as_bytes() + .to_vec(), + ) + .unwrap() + } "/v1/jobs/timeline" => http::Response::builder().status(200) .body(br#"{"traceEvents":[],"metadata":{"partial":true}}"#.to_vec()).unwrap(), other => panic!("unexpected path {other}"), @@ -13149,6 +13188,10 @@ mod tests { }); let job = table.refresh_column_async("doubled").await.unwrap(); + assert_eq!( + job.stats().await.unwrap().as_deref(), + Some("Function job: finished\nRows: 1600\n") + ); job.refresh().await.unwrap(); assert_eq!(job.state().as_deref(), Some("running")); assert_eq!(job.job_type().as_deref(), Some("refresh_column")); From e3a0a29bdbe4cdc39f6f4eeb0c45e3e57fdf6b19 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Tue, 17 Nov 2026 14:51:33 +0000 Subject: [PATCH 05/78] =?UTF-8?q?Bump=20version:=200.42.0-beta.18=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.19?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 8f10d67f0..6efd2bf48 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.18" +current_version = "0.42.0-beta.19" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 6a23569a8..7b43449a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6005,7 +6005,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" dependencies = [ "ahash", "anyhow", @@ -6116,7 +6116,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" dependencies = [ "anyhow", "arrow-array", @@ -6159,7 +6159,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" dependencies = [ "arrow-array", "arrow-buffer", @@ -6184,7 +6184,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 1a8347ad5..f6e7497d0 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.18 + 0.42.0-beta.19 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index c15bc0774..5a49a1a60 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.18 + 0.42.0-beta.19 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index dce3deba3..46d5fac54 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.18 + 0.42.0-beta.19 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index e523c1138..d0ccd2efd 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index d603a2c8f..4f6851519 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.18", + "version": "0.42.0-beta.19", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 8115e27f9..a4027033a 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.18", + "version": "0.42.0-beta.19", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index f3cdd7253..49a50f33f 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.18", + "version": "0.42.0-beta.19", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 4d165c4de..8f9f3ec18 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.18", + "version": "0.42.0-beta.19", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index d884605b6..bc32a415f 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.18", + "version": "0.42.0-beta.19", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 2b6bdc8da..7e7db948b 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.18", + "version": "0.42.0-beta.19", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 1402f5bee..e1cd2879e 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.18", + "version": "0.42.0-beta.19", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index a0cf05acb..e040cb2b8 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.18", + "version": "0.42.0-beta.19", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 9ba87dcd5..1b9c44290 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 28e8c501b..97d2e732b 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 689200452..8e0348a2b 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" edition = "2021" license.workspace = true repository.workspace = true From 16af729792240195e503af986c0d338036f466d5 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Tue, 17 Nov 2026 10:57:56 -0800 Subject: [PATCH 06/78] feat(sdk)!: add typed SQL job handles for compaction and data prewarm (#5056) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remote data prewarm used REST even though SQL supported filters and concurrency, and both maintenance APIs returned after acceptance without exposing a consistent typed completion handle. Compaction's legacy statistics therefore could not describe the work committed by its durable job. This PR adds job-returning compaction and data-prewarm methods across Rust, Python sync/async and TypeScript, and moves data-prewarm submission to SQL. Legacy methods retain return-after-acceptance behavior; data prewarm now requires a compatible SQL PREWARM server and Flight SQL connectivity. This consolidates #5037, #5055 and #4906. This was accomplished with the following changes: - Added `compact_async()` / `compactAsync()` and `prewarm_data_async()` / `prewarmDataAsync()`, retaining the command receipt's durable job ID. - Added `PrewarmDataOptions` for columns, a metadata-pruning filter and concurrency; both operations inherit database, namespace and branch from the table handle. - Added filter/concurrency arguments to legacy Python `prewarm_data()` and a TypeScript `prewarmData(options)` overload, preserving the columns-array form and discarding the handle after acceptance. - Added typed `CompactionResult` and `PrewarmDataResult` decoding, including reopened jobs; missing result payloads fail explicitly and omitted measurements remain unknown. - Reused the shared Job lifecycle for status, refresh, progress callbacks, cancellation and events; Python maintenance progress bars display rewritten rows or completed executors. - Added TypeScript `wait({ timeoutMs, onProgress })` and Rust `wait_with_options(JobWaitOptions)`, complementing Python's existing timeout argument without cancelling the durable job. - Validated single unambiguous receipts, preserved compaction option presence/default inheritance, and returned actionable unsupported-server errors without dropping options or falling back to REST. - Updated native bindings, API references and maintenance documentation with job methods, result semantics, tuning and compatibility requirements. ### Usage and behaviour **New** = added here; **Enhanced** = existing support extended; **Existing** = already on main. This table describes remote SDK behavior; server-side SQL/CLI capabilities are prerequisites, not additions made by this SDK PR. | Surface | Capability | Compact | Data prewarm | Assessment | | --- | --- | --- | --- | --- | | Rust / Python sync+async / TypeScript | Submission transport | Existing SQL OPTIMIZE | **New:** REST → SQL PREWARM | Both now submit through SQL | | All SDKs | Durable job-returning API | **New:** `compact_async` / `compactAsync` | **New:** `prewarm_data_async` / `prewarmDataAsync` | Same lifecycle model | | All SDKs | Options and target scope | **New handle:** four existing compaction overrides, with omitted fields inherited | **New options:** columns/filter/concurrency | Namespace and branch preserved for both | | Python / TypeScript | Legacy convenience calls | Existing optimize acceptance behavior preserved | **Enhanced:** legacy methods accept filter/concurrency and use SQL | Return after acceptance; no completion wait | | All SDKs | Typed successful result | **New:** committed rows, file/fragment changes, partial commit and `more_work` | **New:** pinned version, fragments and executor outcomes | Different measurements are intentional | | All SDKs | Status / refresh / progress | Existing Job APIs reused by **new** maintenance handle | Existing Job APIs reused by **new** maintenance handle | HTTP monitoring remains | | Python / TypeScript | Progress presentation | **Enhanced:** rewrite rows/groups | **Enhanced:** executor progress | Shared callbacks; Python bars use operation counters | | All SDKs | Bounded wait | Python existing; **new** TS/Rust timeout controls | Same shared timeout support | Timeout stops this wait; job continues | | All SDKs | Reopen and await typed outcome | **New:** compaction result decoding on reopened handle | **New:** prewarm result decoding on reopened handle | Rust selects the typed result explicitly | | All SDKs | Cancel / events | Existing shared APIs available on **new** handle | Same | HTTP underneath; permissions unchanged | | All SDKs | Typed preview helper | Unavailable | Unavailable | General SQL where exposed; no helper added | | Authorization | Submission | Existing table Ownership plus parent Usage | SQL path uses Select plus parent Usage | Intentional difference | | All SDKs | Local / historical handles | New durable API rejects them | New durable API rejects them | Remote current-branch jobs only | ```python from datetime import timedelta # Legacy convenience call: returns None after acceptance. table.prewarm_data(["payload"], filter="id >= 1000", concurrency=4) warm = table.prewarm_data_async(["payload"], filter="id >= 1000", concurrency=4) warmed = warm.wait(timeout=timedelta(minutes=10), progress=print) print(warmed.table_version, warmed.executors_completed) compact = table.compact_async(compaction_options={"max_source_rows": 1000000}) committed = compact.wait(timeout=timedelta(minutes=10), progress=print) print(committed.rows_succeeded, committed.fragments_removed, committed.more_work) reopened_result = db.open_job(compact.id).wait() ``` ```typescript await table.prewarmData({ columns: ["payload"], filter: "id >= 1000", concurrency: 4 }); const job = await table.prewarmDataAsync({ columns: ["payload"], filter: "id >= 1000", concurrency: 4, }); const result = await job.wait({ timeoutMs: 600_000, onProgress: console.log }); ``` ```rust use std::time::Duration; use lancedb::job::JobWaitOptions; let job = table.compact_async(Default::default()).await?; let result = job.wait_with_options( JobWaitOptions::new().timeout(Duration::from_secs(600)), ).await?; ``` Python async tables await both submission and Job methods. Rust's legacy `prewarm_data(columns)` keeps its columns-only signature; use `PrewarmDataOptions` on the new job-returning method for filtering/concurrency. Wait deadlines cover pending status requests and polling delays. Existing `wait()`, TypeScript `wait(callback)` and Rust `wait_with_progress(callback)` remain supported. Status/progress/refresh/cancel/events still use generic HTTP job APIs; those endpoints and their read/event/cancel permissions must remain available. Cancelling or timing out does not roll back committed work. Compaction results describe committed rewrites and include deletion files in file counts. Prewarm results describe work against a pinned snapshot, with partial executors included in completed executors; nonempty byte/range measurements remain unknown. Missing results require compatible server/worker support rather than placeholder zero statistics. Filtering uses conservative metadata pruning, not an exact row-filter scan. ### Testing Six checked-in live Python sync/async cases pass against matching server/worker builds for compaction, job-returning prewarm and legacy filtered submission. Ten additional live Node scenarios pass for legacy/default/options forms, filters/concurrency, empty plans, validation, persisted specifications and readback. Targeted regressions pass: Python remote maintenance (80), shared jobs (82), local prewarm rejection (4); Node remote (107) and prewarm API cases (28), plus the previously exercised Rust remote regressions. Tests cover receipt parsing, typed results, reopening, unknown measurements, timeouts, and legacy calls returning None/undefined without polling. Dependency pins are unchanged. Azure account-hint acknowledgment was verified locally with filesystem storage; real Azure-backed storage still needs deployment-specific validation. --- Cargo.lock | 1 + docs/src/js/classes/Connection.md | 20 +- docs/src/js/classes/Job.md | 23 +- docs/src/js/classes/Table.md | 137 +++++- docs/src/js/globals.md | 4 + docs/src/js/interfaces/CompactionResult.md | 99 +++++ docs/src/js/interfaces/JobProgress.md | 98 +++++ docs/src/js/interfaces/JobWaitOptions.md | 31 ++ docs/src/js/interfaces/PrewarmDataOptions.md | 39 ++ docs/src/js/interfaces/PrewarmDataResult.md | 79 ++++ docs/src/python/python.md | 4 + docs/web/basics/embedded-vs-enterprise.mdx | 29 +- docs/web/basics/jobs.mdx | 27 +- .../advanced-conflict-resolution.mdx | 12 +- docs/web/enterprise/cache-prewarm.mdx | 151 ++++++- .../web/enterprise/distributed-compaction.mdx | 8 + .../intelligent-auto-maintenance.mdx | 14 +- docs/web/indexing/incremental-indexing.mdx | 7 +- docs/web/indexing/scalar-index.mdx | 7 +- docs/web/indexing/vector-index.mdx | 4 +- docs/web/maintenance/cleanup.mdx | 6 +- docs/web/maintenance/compaction.mdx | 268 +++++++++++- docs/web/management/table.mdx | 5 +- docs/web/sql/ddl/job.mdx | 20 +- docs/web/sql/ddl/table.mdx | 54 ++- docs/web/tools/cli.mdx | 6 + nodejs/Cargo.toml | 1 + nodejs/__test__/remote.test.ts | 267 ++++++++++++ nodejs/__test__/table.test.ts | 105 ++++- nodejs/lancedb/compaction.ts | 41 ++ nodejs/lancedb/connection.ts | 6 +- nodejs/lancedb/index.ts | 7 +- nodejs/lancedb/job.ts | 116 ++++- nodejs/lancedb/prewarm.ts | 35 ++ nodejs/lancedb/table.ts | 145 ++++++- nodejs/src/connection.rs | 14 +- nodejs/src/job.rs | 82 +++- nodejs/src/table.rs | 60 +++ python/python/lancedb/_lancedb.pyi | 10 + python/python/lancedb/compaction.py | 37 ++ python/python/lancedb/job.py | 25 +- python/python/lancedb/prewarm.py | 32 ++ python/python/lancedb/remote/table.py | 48 +- python/python/lancedb/table.py | 199 ++++++++- python/python/tests/test_e2e_remote_db.py | 128 ++++++ python/python/tests/test_job.py | 92 ++++ python/python/tests/test_remote_db.py | 374 +++++++++++++++- python/python/tests/test_table.py | 19 + python/src/connection.rs | 8 + python/src/table.rs | 51 +++ rust/lancedb/src/job.rs | 181 +++++++- rust/lancedb/src/remote/db.rs | 29 +- rust/lancedb/src/remote/job.rs | 110 ++++- rust/lancedb/src/remote/sql.rs | 52 ++- rust/lancedb/src/remote/sql_test.rs | 410 +++++++++++++++++- rust/lancedb/src/remote/table.rs | 170 ++++---- rust/lancedb/src/remote/table/optimize.rs | 77 ++++ rust/lancedb/src/remote/table/prewarm.rs | 248 +++++++++++ rust/lancedb/src/table.rs | 93 +++- rust/lancedb/src/table/optimize.rs | 45 +- rust/lancedb/src/table/prewarm.rs | 118 +++++ 61 files changed, 4339 insertions(+), 249 deletions(-) create mode 100644 docs/src/js/interfaces/CompactionResult.md create mode 100644 docs/src/js/interfaces/JobWaitOptions.md create mode 100644 docs/src/js/interfaces/PrewarmDataOptions.md create mode 100644 docs/src/js/interfaces/PrewarmDataResult.md create mode 100644 nodejs/lancedb/compaction.ts create mode 100644 nodejs/lancedb/prewarm.ts create mode 100644 python/python/lancedb/compaction.py create mode 100644 python/python/lancedb/prewarm.py create mode 100644 rust/lancedb/src/remote/table/prewarm.rs create mode 100644 rust/lancedb/src/table/prewarm.rs diff --git a/Cargo.lock b/Cargo.lock index 7b43449a0..923b7e94e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6179,6 +6179,7 @@ dependencies = [ "napi", "napi-build", "napi-derive", + "serde", "serde_json", ] diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index 4876e3a52..83c182cf2 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -456,7 +456,7 @@ Rejects a table that exists but is not a materialized view. ### dropMaterializedViewAsync() ```ts -abstract dropMaterializedViewAsync(name, namespacePath?): Promise +abstract dropMaterializedViewAsync(name, namespacePath?): Promise> ``` Start dropping the materialized view named `name` and return its job. @@ -473,7 +473,7 @@ Rejects a table that exists but is not a materialized view. #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> *** @@ -532,7 +532,7 @@ Drop an existing table. ### dropTableAsync() ```ts -abstract dropTableAsync(name, namespacePath?): Promise +abstract dropTableAsync(name, namespacePath?): Promise> ``` Start dropping a table and return its cleanup job. @@ -548,7 +548,7 @@ on the returned job to know when cleanup has finished. #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> *** @@ -579,7 +579,7 @@ catalog removal; physical cleanup continues in the background. ### dropViewAsync() ```ts -abstract dropViewAsync(name, namespacePath?): Promise +abstract dropViewAsync(name, namespacePath?): Promise> ``` Drop a view and return its SQL query job. @@ -594,7 +594,7 @@ catalog removal; physical cleanup continues in the background. #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> *** @@ -729,7 +729,7 @@ state and error behavior; options control page size and the starting token. ### openJob() ```ts -abstract openJob(jobId): Promise +abstract openJob(jobId): Promise> ``` Open a server-side job by id, returning a handle with its record already @@ -740,13 +740,17 @@ The returned [Job](Job.md) answers for its own state, specification, result, failure and event history, so there is no separate connection-level call for any of them. +#### Type Parameters + +• **T** = `void` + #### Parameters * **jobId**: `string` #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`T`>> *** diff --git a/docs/src/js/classes/Job.md b/docs/src/js/classes/Job.md index 8fd59c964..43d532cdd 100644 --- a/docs/src/js/classes/Job.md +++ b/docs/src/js/classes/Job.md @@ -4,7 +4,7 @@ [@lancedb/lancedb](../globals.md) / Job -# Class: Job +# Class: Job<T> A handle to an operation that may still be running. @@ -20,6 +20,10 @@ extra round trip on every call: - Registry details are null until one of those runs. Query handles report jobType "query" immediately. +## Type Parameters + +• **T** = `void` + ## Accessors ### creationMs @@ -241,7 +245,7 @@ printing it. ### wait() ```ts -wait(progressCallback?): Promise +wait(optionsOrProgress?): Promise ``` Wait until the operation reaches a terminal state. @@ -253,10 +257,21 @@ synchronous observer: its return value is ignored and not awaited. If it throws, the error is logged with `console.warn` and waiting continues; a callback exception does not reject `wait`. +Pass an options object to set a client-side timeout. Expiry rejects with an +error and stops this wait, including pending status requests and backoff. +The operation continues; use the same handle to wait again. Registry jobs +can also be reopened with `Connection.openJob`; query IDs cannot. + #### Parameters -* **progressCallback?**: [`JobProgressCallback`](../type-aliases/JobProgressCallback.md) +* **optionsOrProgress?**: [`JobWaitOptions`](../interfaces/JobWaitOptions.md) \| [`JobProgressCallback`](../type-aliases/JobProgressCallback.md) #### Returns -`Promise`<`void`> +`Promise`<`T`> + +#### Example + +```ts +const result = await job.wait({ timeoutMs: 60_000, onProgress: console.log }); +``` diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index f93c1b7cd..0a230ac94 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -305,6 +305,40 @@ It is a no-op when no writers are cached. *** +### compactAsync() + +```ts +compactAsync(_options?): Promise> +``` + +Submit remote compaction and return its durable job after acceptance. + +Uses SQL OPTIMIZE, inheriting branch and namespace from this table. Requires +a compatible remote server and table Ownership plus parent Usage. Local and +historical-version handles are unsupported. Existing optimize() behavior is unchanged. +Waiting tracks the rewrite itself and returns actual row/file statistics. +Missing result payloads are errors; older workers can omit file counts. +Status, progress, events and cancellation reuse the generic HTTP job APIs. +Reopen with db.openJob(job.id!). A wait timeout does not cancel work. + +#### Parameters + +* **\_options?**: [`CompactionOptions`](../interfaces/CompactionOptions.md) + +#### Returns + +`Promise`<[`Job`](Job.md)<[`CompactionResult`](../interfaces/CompactionResult.md)>> + +#### Example + +```ts +const job = await table.compactAsync({ targetRowsPerFragment: 1000 }); +const result = await job.wait(); +console.log(result.rowsSucceeded, result.fragmentsRemoved); +``` + +*** + ### compactRTE() ```ts @@ -423,7 +457,7 @@ await table.createIndex("my_float_col"); ### createIndexAsync() ```ts -abstract createIndexAsync(column, options?): Promise +abstract createIndexAsync(column, options?): Promise> ``` Create an index, returning a handle to the indexing job. @@ -444,7 +478,7 @@ account for the replacement caveat described in [Table.createIndex](Table.md#cre #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> *** @@ -1047,29 +1081,98 @@ retrying with the settings removed. ### prewarmData() +#### prewarmData(options) + ```ts -abstract prewarmData(columns?): Promise +abstract prewarmData(options?): Promise ``` Prewarm one or more columns of data in the table. -#### Parameters +This will load the column data into the page cache so that future queries that +read those columns avoid the initial cold-start latency. This call initiates +prewarming and returns once the request is accepted; the warming itself may +continue in the background. Submission uses SQL PREWARM and needs Flight +SQL connectivity. Use [prewarmDataAsync](Table.md#prewarmdataasync) to retain the job handle. + +Prewarming is generally useful for columns used in filters or projections. +Large columns (e.g. high-dimensional vectors or binary data) may not be +practical to prewarm. + +This feature is currently only supported in LanceDB Enterprise. + +##### Parameters + +* **options?**: [`PrewarmDataOptions`](../interfaces/PrewarmDataOptions.md) + Columns, a metadata-pruning filter, and per-executor concurrency. + Omitted or empty columns warm every column. + +##### Returns + +`Promise`<`void`> + +##### Example + +```ts +await table.prewarmData({ + columns: ["payload"], filter: "quality > 0.7", concurrency: 4, +}); +``` + +#### prewarmData(columns) + +```ts +abstract prewarmData(columns?): Promise +``` + +Submit data prewarm using the columns-array form and return after acceptance. + +##### Parameters * **columns?**: `string`[] - The columns to prewarm. If undefined, all columns are prewarmed. - This will load the column data into the page cache so that future queries that - read those columns avoid the initial cold-start latency. This call initiates - prewarming and returns once the request is accepted; the warming itself may - continue in the background. Calling it on already-prewarmed columns is a - no-op on the server. - Prewarming is generally useful for columns used in filters or projections. - Large columns (e.g. high-dimensional vectors or binary data) may not be - practical to prewarm. - This feature is currently only supported in LanceDB Enterprise. + Columns to warm; omitted or empty means every column. + +##### Returns + +`Promise`<`void`> + +*** + +### prewarmDataAsync() + +```ts +abstract prewarmDataAsync(options?): Promise> +``` + +Submit data prewarm through SQL and return its durable warming-job handle. + +The table handle supplies the branch and namespace. Requires a compatible +SQL PREWARM server and Flight SQL connectivity. Standard authorization +requires table Select and database/namespace Usage. Status/wait use generic +HTTP job APIs; events and cancellation retain their own privileges. +No REST fallback or option-dropping retry is performed. Historical-version +handles are unsupported; call `checkoutLatest()` first. + +Submission returns after acceptance. Use `job.wait()` for completion, or +save `job.id` and reopen it with `db.openJob(id)`. A timeout does not cancel +the job. After `job.refresh()`, `job.spec.table_version` is the pinned version. + +#### Parameters + +* **options?**: [`PrewarmDataOptions`](../interfaces/PrewarmDataOptions.md) #### Returns -`Promise`<`void`> +`Promise`<[`Job`](Job.md)<[`PrewarmDataResult`](../interfaces/PrewarmDataResult.md)>> + +#### Example + +```ts +const job = await table.prewarmDataAsync({ + columns: ["video"], filter: "quality > 0.7", concurrency: 4, +}); +await job.wait(); +``` *** @@ -1200,7 +1303,7 @@ number of rows filled and the new version number of the table. ### refreshColumnAsync() ```ts -abstract refreshColumnAsync(column, options?): Promise +abstract refreshColumnAsync(column, options?): Promise> ``` Like [Table#refreshColumn](Table.md#refreshcolumn), but returns a handle to the refresh @@ -1253,7 +1356,7 @@ LanceDB Enterprise it is the server's backfill job. #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> #### Example diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 23e576877..3893f9a7e 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -75,6 +75,7 @@ - [ColumnAlteration](interfaces/ColumnAlteration.md) - [ColumnOrdering](interfaces/ColumnOrdering.md) - [CompactionOptions](interfaces/CompactionOptions.md) +- [CompactionResult](interfaces/CompactionResult.md) - [CompactionStats](interfaces/CompactionStats.md) - [ConnectNamespaceOptions](interfaces/ConnectNamespaceOptions.md) - [ConnectionOptions](interfaces/ConnectionOptions.md) @@ -119,6 +120,7 @@ - [JobFailureInfo](interfaces/JobFailureInfo.md) - [JobInfo](interfaces/JobInfo.md) - [JobProgress](interfaces/JobProgress.md) +- [JobWaitOptions](interfaces/JobWaitOptions.md) - [ListingOptions](interfaces/ListingOptions.md) - [MaterializedViewDefinition](interfaces/MaterializedViewDefinition.md) - [MemtableStats](interfaces/MemtableStats.md) @@ -128,6 +130,8 @@ - [OpenTableOptions](interfaces/OpenTableOptions.md) - [OptimizeOptions](interfaces/OptimizeOptions.md) - [OptimizeStats](interfaces/OptimizeStats.md) +- [PrewarmDataOptions](interfaces/PrewarmDataOptions.md) +- [PrewarmDataResult](interfaces/PrewarmDataResult.md) - [QueryExecutionOptions](interfaces/QueryExecutionOptions.md) - [RTEStats](interfaces/RTEStats.md) - [RTEWriteSpec](interfaces/RTEWriteSpec.md) diff --git a/docs/src/js/interfaces/CompactionResult.md b/docs/src/js/interfaces/CompactionResult.md new file mode 100644 index 000000000..623dfe453 --- /dev/null +++ b/docs/src/js/interfaces/CompactionResult.md @@ -0,0 +1,99 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / CompactionResult + +# Interface: CompactionResult + +Actual committed outcome of one remote compaction job. + +## Properties + +### completionPercentage + +```ts +completionPercentage: number; +``` + +Percentage of planned live rows committed, from 0 to 100. + +*** + +### filesAdded + +```ts +filesAdded: null | number; +``` + +Files added, including deletion files; null if an older worker omitted it. + +*** + +### filesRemoved + +```ts +filesRemoved: null | number; +``` + +Files removed, including deletion files; null if an older worker omitted it. + +*** + +### fragmentsAdded + +```ts +fragmentsAdded: null | number; +``` + +Fragments added by committed rewrites; null if an older worker omitted it. + +*** + +### fragmentsRemoved + +```ts +fragmentsRemoved: null | number; +``` + +Fragments removed by committed rewrites; null if an older worker omitted it. + +*** + +### moreWork + +```ts +moreWork: boolean; +``` + +A bounded run left eligible work for another invocation. + +*** + +### partialCommit + +```ts +partialCommit: boolean; +``` + +Some planned groups were not committed. + +*** + +### rowsFailed + +```ts +rowsFailed: number; +``` + +Planned live rows not committed by this job. + +*** + +### rowsSucceeded + +```ts +rowsSucceeded: number; +``` + +Live source rows in committed rewrite groups. diff --git a/docs/src/js/interfaces/JobProgress.md b/docs/src/js/interfaces/JobProgress.md index dde202794..6c9bc5466 100644 --- a/docs/src/js/interfaces/JobProgress.md +++ b/docs/src/js/interfaces/JobProgress.md @@ -17,6 +17,14 @@ different counters. A missing counter is unknown; it is not zero. ## Properties +### bytes\_read? + +```ts +optional bytes_read: null | number; +``` + +*** + ### estimated\_remaining\_time\_millis? ```ts @@ -37,6 +45,72 @@ Execution identity and sample time used for client-side ETA derivation. *** +### executors\_active? + +```ts +optional executors_active: null | number; +``` + +*** + +### executors\_completed? + +```ts +optional executors_completed: null | number; +``` + +*** + +### executors\_failed? + +```ts +optional executors_failed: null | number; +``` + +*** + +### executors\_partial? + +```ts +optional executors_partial: null | number; +``` + +*** + +### executors\_targeted? + +```ts +optional executors_targeted: null | number; +``` + +*** + +### fragments\_selected? + +```ts +optional fragments_selected: null | number; +``` + +*** + +### groups\_completed? + +```ts +optional groups_completed: null | number; +``` + +*** + +### groups\_planned? + +```ts +optional groups_planned: null | number; +``` + +Maintenance work observations; rewritten rows are not committed rows. + +*** + ### paused? ```ts @@ -57,6 +131,22 @@ Coarse server-derived phase, including phases from newer servers. *** +### ranges\_completed? + +```ts +optional ranges_completed: null | number; +``` + +*** + +### ranges\_planned? + +```ts +optional ranges_planned: null | number; +``` + +*** + ### rows\_computed? ```ts @@ -92,6 +182,14 @@ optional rows_remaining: null | number; *** +### rows\_rewritten? + +```ts +optional rows_rewritten: null | number; +``` + +*** + ### rows\_skipped? ```ts diff --git a/docs/src/js/interfaces/JobWaitOptions.md b/docs/src/js/interfaces/JobWaitOptions.md new file mode 100644 index 000000000..38f1795f5 --- /dev/null +++ b/docs/src/js/interfaces/JobWaitOptions.md @@ -0,0 +1,31 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / JobWaitOptions + +# Interface: JobWaitOptions + +Client-side controls for waiting without cancelling the underlying job. + +## Properties + +### onProgress? + +```ts +optional onProgress: JobProgressCallback; +``` + +Observe progress using the same poller that waits for completion. + +*** + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Maximum wait in milliseconds, including status requests and polling backoff. +Must be a nonnegative safe integer. Omit to wait indefinitely; zero allows +only an immediately ready result. diff --git a/docs/src/js/interfaces/PrewarmDataOptions.md b/docs/src/js/interfaces/PrewarmDataOptions.md new file mode 100644 index 000000000..def1eb822 --- /dev/null +++ b/docs/src/js/interfaces/PrewarmDataOptions.md @@ -0,0 +1,39 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / PrewarmDataOptions + +# Interface: PrewarmDataOptions + +Settings for submitting a durable remote data-cache prewarm job. + +## Properties + +### columns? + +```ts +optional columns: string[]; +``` + +Lance field paths to warm; omitted or empty means every column. + +*** + +### concurrency? + +```ts +optional concurrency: number; +``` + +Positive per-executor concurrency, at most 4294967295. + +*** + +### filter? + +```ts +optional filter: string; +``` + +A single SQL predicate for conservative metadata pruning. diff --git a/docs/src/js/interfaces/PrewarmDataResult.md b/docs/src/js/interfaces/PrewarmDataResult.md new file mode 100644 index 000000000..ce43b927c --- /dev/null +++ b/docs/src/js/interfaces/PrewarmDataResult.md @@ -0,0 +1,79 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / PrewarmDataResult + +# Interface: PrewarmDataResult + +Reported executor work for a pinned snapshot; unavailable measurements stay null. + +## Properties + +### bytesRead + +```ts +bytesRead: null | number; +``` + +Reported bytes read, or null when unavailable. + +*** + +### executorsCompleted + +```ts +executorsCompleted: null | number; +``` + +Executors that finished successfully or partially, or null when unavailable. + +*** + +### executorsPartial + +```ts +executorsPartial: null | number; +``` + +Subset of completed executors reporting partial warming, or null when unavailable. + +*** + +### executorsTargeted + +```ts +executorsTargeted: null | number; +``` + +Reported executors targeted, or null when unavailable. + +*** + +### fragmentsSelected + +```ts +fragmentsSelected: null | number; +``` + +Reported fragments selected, or null when unavailable. + +*** + +### rangesCompleted + +```ts +rangesCompleted: null | number; +``` + +Reported ranges completed, or null when unavailable. + +*** + +### tableVersion + +```ts +tableVersion: number; +``` + +The source snapshot captured by submission. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index d3713b634..b7859c2f7 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -1494,3 +1494,7 @@ that accepts `python_bundle.resources`. Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or `conda=` for platform-specific dependencies and `models=` for large model snapshots. + +::: lancedb.compaction.CompactionResult + +::: lancedb.prewarm.PrewarmDataResult diff --git a/docs/web/basics/embedded-vs-enterprise.mdx b/docs/web/basics/embedded-vs-enterprise.mdx index a4e00040b..7d30a0e92 100644 --- a/docs/web/basics/embedded-vs-enterprise.mdx +++ b/docs/web/basics/embedded-vs-enterprise.mdx @@ -19,7 +19,7 @@ file format, so moving data from one edition to the other does not require a dat | **Mode** | Single process | Distributed fleet | LanceDB Embedded runs on one host, so scale is limited to what it can provide. Enterprise spreads work across nodes, adds capacity by adding nodes, and keeps serving even if one node fails. | | **Query serving** | Uses the resources of your application process | Adds independently scaled query compute | Size the Enterprise cluster for your workload and latency target. See the expected-performance sections on [vector search](/search/vector-search#expected-performance) and [full-text search](/search/full-text-search#expected-performance) for representative measurements. | | **Cache** | In-process index and metadata caches | Adds a distributed NVMe data cache | LanceDB Embedded caches indexes and metadata in your application's memory. Enterprise also keeps hot table data near compute on NVMe and avoids repeated S3 calls -- see the [Data Page Cache](/enterprise/data-page-cache). | -| **Indexing & compaction** | Manual | Platform-managed workflows | LanceDB Embedded requires application-managed maintenance; Enterprise schedules it in the background. See [Indexing in LanceDB](/indexing/). | +| **Indexing & compaction** | Manual | Platform-managed workflows and explicit compaction | LanceDB Embedded requires application-managed maintenance; Enterprise schedules it in the background. See [Indexing in LanceDB](/indexing/). | | **Data format** | Lance | Lance | Both use the same open table format. Plan catalog registration, access and transfer when moving existing data. | | **Deployment** | Embedded in your code | BYOC or Managed | Enterprise adds deployment operations and support for shared workloads. | | **SQL analytics** | Not available | Arrow Flight SQL | Enterprise runs joins, grouping, sampling and [curation](/curation) over SQL. See [SQL reference](/sql). | @@ -137,15 +137,26 @@ Instead, materialize results through query/search builders, for example ### 4\. Maintenance lifecycle {#4-maintenance-lifecycle} -In LanceDB Embedded, you run maintenance yourself: `optimize()` compacts data files, adds new rows to -existing indexes, and removes old table versions. In Enterprise, the cluster runs this work -- along with -async write and reindexing workflows -- as background jobs, and the SDK's maintenance calls do not trigger -it. On an Enterprise table, the synchronous Python `optimize()`, `compact_files()`, and -`cleanup_old_versions()` only emit a warning, and the asynchronous Python, TypeScript, and Rust clients -reject `optimize()` as not supported. +In LanceDB Embedded, `optimize()` compacts data files, adds new rows to existing +indexes, and removes old table versions. LanceDB Enterprise schedules that work +through separate background jobs and also accepts explicit compaction requests +with compatible releases. -That means maintenance is managed by platform behavior and cluster configuration, not by explicit -per-table maintenance calls in your application code. +Python sync/async `compact_async()`, TypeScript `compactAsync()`, and Rust +`Table::compact_async(CompactionOverrides)` return durable compaction job handles; +waiting returns the committed rewrite statistics. Legacy remote `optimize()` +and Rust `Table::compact()` return after submission with placeholder counts. +Remote optimize does not prune versions or optimize indexes; +explicit requests for those unsupported operations are rejected. The synchronous +Python `compact_files()` and `cleanup_old_versions()` helpers remain warning-only +no-ops in LanceDB Enterprise. + +Manual compaction accepts four invocation options and inherits omitted fields +from the selected branch's table tuning, then deployment/built-in defaults. +Automatic-compaction enablement gates background scheduling while explicit +manual jobs can still run. See +[manual Enterprise compaction](/maintenance/compaction#enterprise-manual-compaction) +for CLI, SQL, and SDK examples and rollout requirements. ### 5\. Guardrails and limits {#5-guardrails-and-limits} diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 30d48e93e..7761ab07c 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -95,7 +95,7 @@ In Python, `job.status()` returns the current state: It returns `failed` or `cancelled` for unsuccessful jobs. Use `job.wait()` to wait for completion and raise if the job fails or is -cancelled. Both `Job.wait()` and `AsyncJob.wait()` retry transient connection +cancelled. Python's `Job.wait()` and `AsyncJob.wait()` retry transient connection and read errors with capped exponential backoff within the caller's timeout. Without a timeout, retries continue indefinitely. @@ -123,8 +123,33 @@ except ConnectionError as exc: except TimeoutError: print(f"still running: {job.status()}") ``` +```typescript TypeScript +const result = await job.wait({ + timeoutMs: 600_000, + onProgress: progress => console.log(progress), +}); +``` +```rust Rust +use std::time::Duration; +use lancedb::job::JobWaitOptions; + +let result = job.wait_with_options( + JobWaitOptions::new() + .timeout(Duration::from_secs(600)) + .progress(|description| println!("{}", description.progress_snapshot())), +).await?; +``` +TypeScript's `timeoutMs` and Rust's `JobWaitOptions::timeout` bound the existing +wait poller, including pending status requests and retry/polling delays. +Expiry rejects the TypeScript promise or returns Rust's `Error::Timeout`; +the operation is not cancelled. Calling `wait()` without options still waits +indefinitely. TypeScript's existing `wait(callback)` and Rust's +`wait_with_progress(callback)` remain available. A zero timeout only permits +an immediately ready result. TypeScript timeouts use nonnegative safe-integer +milliseconds; Rust uses `std::time::Duration`. + After connectivity returns, reopen an Enterprise registry job by its saved ID and continue waiting on the existing operation: diff --git a/docs/web/enterprise/advanced-conflict-resolution.mdx b/docs/web/enterprise/advanced-conflict-resolution.mdx index 3826de8a5..a48d23952 100644 --- a/docs/web/enterprise/advanced-conflict-resolution.mdx +++ b/docs/web/enterprise/advanced-conflict-resolution.mdx @@ -20,11 +20,13 @@ independently: `optimize()` compacts and remaps affected indexes in the same call, before returning. Compaction's `defer_index_remap` option opts out of that -- the call returns once compaction itself commits, leaving the remap for later -- which is what lets a custom remapper or a -stable-row-ID table skip the synchronous step. LanceDB Enterprise runs -compaction and indexing as separate, independently scheduled -background jobs -- a table can compact while an index build is still -catching up from an earlier compaction -- so it needs a way to keep an index -correct without forcing every compaction to wait for a synchronous remap. +stable-row-ID table skip the synchronous step. LanceDB Enterprise schedules +automatic compaction and indexing independently, so an eligible table can compact +while an index build is still catching up from earlier compaction. Deferred +remapping keeps indexes correct without making every automatic compaction wait +for a synchronous remap. Explicit +[manual compaction](/maintenance/compaction#enterprise-manual-compaction) uses one +worker with atomic execution and inline index remapping instead. ## The fragment reuse index {#fri} diff --git a/docs/web/enterprise/cache-prewarm.mdx b/docs/web/enterprise/cache-prewarm.mdx index 3ce773d73..c2a5347f1 100644 --- a/docs/web/enterprise/cache-prewarm.mdx +++ b/docs/web/enterprise/cache-prewarm.mdx @@ -1,23 +1,25 @@ --- title: "Cache Prewarm" sidebarTitle: "Cache Prewarm" -description: "Populate the tiered index cache ahead of a request, instead of filling it lazily on first read." +description: "Warm indexes at executor startup or submit on-demand jobs to populate the data page cache." icon: "fire" -keywords: ["prewarm", "cache", "index cache", "startup"] +keywords: ["prewarm", "cache", "index cache", "data page cache", "startup"] availability: embedded: unavailable enterprise: available --- -Cache Prewarm loads the [tiered index cache](/enterprise/tiered-index-cache) -a plan executor keeps as part of Enterprise's serving layer, instead of -leaving it to fill lazily on first read. You configure which tables to -prewarm; on startup, each plan executor loads those tables' indexes into -cache before it joins the fleet. The executor does not accept queries until -prewarming finishes, so it never serves a request against a cold cache. +Enterprise supports two kinds of cache prewarm: startup index prewarm fills +the [tiered index cache](/enterprise/tiered-index-cache), and +[on-demand data prewarm](#on-demand-data-prewarm) fills the +[data page cache](/enterprise/data-page-cache) through a durable job. -LanceDB Embedded has no such cache, so there is nothing for it to warm -there. Embedded does have its own, separate `prewarm_index()` on a table -- +For startup index prewarm, you configure which tables to warm. Each plan +executor loads those tables' indexes before it joins the fleet. The executor +does not accept queries until startup prewarming finishes. + +These Enterprise caches are not available in LanceDB Embedded. +Embedded does have its own, separate `prewarm_index()` on a table -- an idempotent hint that loads a built index into memory ahead of a query.
@@ -72,14 +74,139 @@ and rollouts instead of dipping right after each one. [Contact us](https://www.lancedb.com/contact) to learn more about how prewarming is configured for your deployment. +## On-demand data prewarm {#on-demand-data-prewarm} + +On compatible Enterprise deployments, the SDK submits data prewarm through +SQL. Flight SQL connectivity is required; the existing generic HTTP job API is +used to inspect or wait for the durable warming job. Under Standard +authorization, submission requires table Select plus Usage on the database +and namespace hierarchy. Job events require System Usage and cancellation +requires System Operate. + +The table handle determines the database, namespace, and branch in every SDK. + + + +```python +from datetime import timedelta + +job = table.prewarm_data_async( + ["video"], filter="quality > 0.7", concurrency=4 +) +print(job.id) +result = job.wait(timeout=timedelta(minutes=10), progress=print) +print(result.table_version, result.executors_completed, result.fragments_selected) + +# Reattach in a later process using the same database connection settings. +db.open_job(job.id).wait() +``` + + +```typescript +const job = await table.prewarmDataAsync({ + columns: ["video"], + filter: "quality > 0.7", + concurrency: 4, +}); +console.log(job.id); +const result = await job.wait({ timeoutMs: 600_000, onProgress: console.log }); +console.log(result.tableVersion, result.executorsCompleted); + +// Reattach using the same database connection settings. +if (job.id !== null) { + await (await db.openJob(job.id)).wait(); +} +``` + + +```rust +use std::time::Duration; +use lancedb::job::JobWaitOptions; +use lancedb::table::{PrewarmDataOptions, PrewarmDataResult}; + +let job = table + .prewarm_data_async( + PrewarmDataOptions::new() + .columns(["video"]) + .filter("quality > 0.7") + .concurrency(4), + ) + .await?; +println!("{:?}", job.id()); +let result = job.wait_with_options( + JobWaitOptions::new().timeout(Duration::from_secs(600)), +).await?; +println!("Snapshot {}: {:?} executors completed", result.table_version, result.executors_completed); + +// Reattach using the same database connection settings. +if let Some(id) = job.id() { + db.open_job(id).await?.into_typed::()?.wait().await?; +} +``` + + + +The method returns when the job is accepted. Waiting finishes when warming +reaches a terminal state; a timeout does not cancel the job. Use +`job.refresh()` and `job.spec["table_version"]` to inspect the captured source +version. In Python's asynchronous API, await submission and `job.wait()`. +Node exposes `table.prewarmDataAsync({ columns, filter, concurrency })` with +the same lifecycle. + +Waiting returns a typed `PrewarmDataResult`: the pinned source version, +selected fragment count, targeted/completed executor counts, and partial +executor count when reported. Completed executors include partial completions; +`executors_partial` is that subset, which can reflect cache pressure. These are observations of executor work, not a guarantee that every +page remains resident. Counters omitted by older workers stay unknown. + +The current executor status protocol does not report byte/range measurements +for nonempty prewarms, so `bytes_read` and `ranges_completed` are None/null there. +A new worker performing an empty plan reports known zero work. Progress exposes +planning/dispatch phases, selected fragments, executor fan-out, and the latest +active/completed/partial/failed executor counts without inventing percentages. +In Python, `job.wait(progress=True)` displays completed executors. Pass a +callback instead to inspect the full structured snapshots. + +The Enterprise administrative CLI supports the same lifecycle: + +```bash +lancedb admin cache prewarm data --profile production --table events \ + --column payload --filter 'id >= 1000' --concurrency 4 \ + --wait --wait-timeout-seconds 600 --poll-interval-seconds 5 +``` + +SQL submission and preview use the same options. Submission returns a job ID +and pinned source version; preview creates no job: + +```sql +PREWARM WITH (concurrency = 4) AS SELECT payload FROM events WHERE id >= 1000; +EXPLAIN PREWARM WITH (concurrency = 4) AS SELECT payload FROM events WHERE id >= 1000; +DESCRIBE JOB '' FORMAT JSON; +``` + +The filter is a single SQL predicate used for conservative metadata pruning. +Unknown or unavailable metadata keeps data eligible for warming. Omitted +columns warm all fields; concurrency must be a positive integer. Historical +version checkouts are unsupported: use the latest version of the selected +branch. The server never needs to scan rows merely to evaluate the predicate. + +`prewarm_data(columns, filter=..., concurrency=...)` and +`prewarmData({ columns, filter, concurrency })` accept the same options as the +job-returning methods but return after acceptance without retaining the handle. +The existing TypeScript `prewarmData(columns)` array form remains supported. +These methods require SQL PREWARM support and Flight SQL connectivity. +Unsupported servers fail without a REST fallback or silently +dropping options. Repeated submissions may create distinct jobs; warming +already-cached data is safe. Index prewarm keeps its existing behavior. + ## What to read next {#next} - The raw-data-page cache -- a separate cache from the one prewarm fills. + The raw-data-page cache populated by on-demand data prewarm jobs. - The deserialized-index cache prewarm fills. + The deserialized-index cache populated by startup index prewarm. Where plan executors and query nodes sit in the serving fleet. diff --git a/docs/web/enterprise/distributed-compaction.mdx b/docs/web/enterprise/distributed-compaction.mdx index 8d1fb4191..30d8a8863 100644 --- a/docs/web/enterprise/distributed-compaction.mdx +++ b/docs/web/enterprise/distributed-compaction.mdx @@ -76,6 +76,14 @@ rest of the job's tasks commit without waiting on it. See [Advanced Conflict Resolution](/enterprise/advanced-conflict-resolution) for when compaction defers a remap at all. +Automatic compaction can use this distributed path when table state and index +safety permit it. Explicit CLI, SQL, and SDK compaction jobs use one worker with +atomic execution and inline index remapping. Their tuning resolves from the +invocation, then table settings, then deployment/built-in defaults. Automatic +jobs use table settings before those defaults. See +[manual compaction](/maintenance/compaction#enterprise-manual-compaction) for +submission, the four tuning fields, and job completion checks. + ## Compaction interfaces {#compaction-interfaces} - [Compaction](/maintenance/compaction) for triggering and configuring a compaction. diff --git a/docs/web/enterprise/intelligent-auto-maintenance.mdx b/docs/web/enterprise/intelligent-auto-maintenance.mdx index 38cbdd2a5..cabac3643 100644 --- a/docs/web/enterprise/intelligent-auto-maintenance.mdx +++ b/docs/web/enterprise/intelligent-auto-maintenance.mdx @@ -112,13 +112,21 @@ a compaction and a cleanup are unrelated and can both launch together -- but some gate each other where running them at the same time would be unsafe, like index operations waiting on a compaction that can't defer its remap. +Compaction's four tuning fields can be set per table. Automatic jobs use table +tuning before deployment/built-in defaults; explicit manual invocation values +take precedence over both. Automatic enablement still gates background jobs, +while manual compaction can run with it disabled. Resolved tuning is captured in +each job. See [table compaction defaults](/maintenance/compaction#table-compaction-defaults) +for the fields, precedence, source-budget planning failures, and compatible-version requirements. + ### When cleanup is due {#cleanup} [Cleanup](/maintenance/cleanup) prunes old table versions and the files only they referenced. In LanceDB Embedded, that always happens because you asked -for it -- a call to `optimize()`. LanceDB Enterprise does not support a -manual `optimize()` call at all; cleanup there is entirely this planner's own -decision, off by default unless the deployment sets a minimum version age -- +for it, through a call to `optimize()`. In LanceDB Enterprise, a +[manual `optimize()` call](/maintenance/compaction#enterprise-manual-compaction) +submits compaction only. Cleanup remains this planner's own decision, off by +default unless the deployment sets a minimum version age: with no minimum age configured, nothing is ever old enough to clean up automatically, and old versions simply accumulate until an operator enables it. A table can also disable it individually even when the deployment allows diff --git a/docs/web/indexing/incremental-indexing.mdx b/docs/web/indexing/incremental-indexing.mdx index 42c864ae9..6c79102f0 100644 --- a/docs/web/indexing/incremental-indexing.mdx +++ b/docs/web/indexing/incremental-indexing.mdx @@ -41,10 +41,11 @@ default. The name says which algorithm is building, not a separate feature. ## Triggering an incremental update {#incremental-reindexing} In the embedded library, you trigger an incremental indexing operation on -updated data with the `optimize()` method on a table. A deployment does this -for you and does not support `optimize()`, as described below. +updated data with the `optimize()` method on a table. LanceDB Enterprise updates +indexes in the background. Its [manual `optimize()` path](/maintenance/compaction#enterprise-manual-compaction) +submits compaction only and does not trigger incremental index updates. -Table optimization performs three maintenance operations: +In LanceDB Embedded, table optimization performs three maintenance operations: 1. **Compaction**: merges small fragments into larger ones to improve read performance 2. **Pruning/Cleanup**: removes files from versions older than a retention window (7 days by default) -- see [Cleanup](/maintenance/cleanup) for how retention works diff --git a/docs/web/indexing/scalar-index.mdx b/docs/web/indexing/scalar-index.mdx index fbd818b64..3d7b3a864 100644 --- a/docs/web/indexing/scalar-index.mdx +++ b/docs/web/indexing/scalar-index.mdx @@ -90,7 +90,12 @@ Updating the table data (adding, deleting, or modifying records) requires that y -New data added after creating the scalar index will still appear in search results if optimize is not used, but with increased latency due to a flat search on the unindexed portion. LanceDB Enterprise does not support `optimize()`; instead it adds new rows to `BTREE`, `BITMAP` and `LABEL_LIST` indexes in the background once enough have accumulated. It does not update `FM` indexes automatically. +New data added after creating the scalar index remains searchable through a +slower flat scan of the unindexed rows. LanceDB Enterprise adds new rows to +`BTREE`, `BITMAP`, and `LABEL_LIST` indexes in the background once enough have +accumulated. It does not update `FM` indexes automatically. The Enterprise +[manual `optimize()` path](/maintenance/compaction#enterprise-manual-compaction) +submits compaction only and does not trigger this index maintenance. ### 4\. Run Indexed Searches diff --git a/docs/web/indexing/vector-index.mdx b/docs/web/indexing/vector-index.mdx index 33fc802fa..2800463af 100644 --- a/docs/web/indexing/vector-index.mdx +++ b/docs/web/indexing/vector-index.mdx @@ -301,7 +301,9 @@ fallback and searches only indexed rows. **Operational checks** In the embedded library, use `optimize()` after appends or other writes to fold new rows into existing indexes. -A deployment does this in the background, and `optimize()` is not available there. +LanceDB Enterprise does this in the background. Its +[manual `optimize()` path](/maintenance/compaction#enterprise-manual-compaction) +submits compaction only and does not add unindexed rows to the vector index. #### Check Index Status diff --git a/docs/web/maintenance/cleanup.mdx b/docs/web/maintenance/cleanup.mdx index 21ba079f9..8ccf4e242 100644 --- a/docs/web/maintenance/cleanup.mdx +++ b/docs/web/maintenance/cleanup.mdx @@ -96,8 +96,10 @@ maintenance workers to a version that understands Managed blobs before using them, and reopen handles created before that upgrade. For LanceDB Embedded tables, `optimize()` performs compaction and cleanup. -Enterprise runs these as background jobs; Python tables connected to Enterprise -do not support `optimize()`. +Enterprise schedules them as separate background jobs. With compatible releases, +remote `optimize()` also submits [manual compaction](/maintenance/compaction#enterprise-manual-compaction), +but does not prune versions or remove their files. Cleanup remains governed by +the deployment's separate policy. See [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance#cleanup) for the Enterprise path. ## Disk usage does not drop immediately {#disk} diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index e7b79f768..d8638419e 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -13,8 +13,10 @@ import { PyStorageCompactionTuning, PyStorageRebuildVectorIndex, RsStorageCompac Every write commits a new table version, and versions accumulate: small files from frequent appends, superseded files from updates and deletes, and rows added since an index was built. In the embedded library, `optimize()` addresses all -three. Enterprise handles maintenance in the background and also supports -on-demand compaction through `optimize()` on compatible servers. +three. LanceDB Enterprise schedules maintenance in the background and also +supports explicit compaction jobs through the CLI, SQL, and compatible SDKs. +[Manual Enterprise compaction](#enterprise-manual-compaction) rewrites data files; +cleanup and index optimization remain separate operations. Run optimization as regular table maintenance, particularly after many small writes or a large ingest. @@ -37,7 +39,7 @@ optimize. Rebuilding with the default IVF partitioning can also choose enough partitions. */} -## Optimize a table {#what-it-does} +## Optimize an Embedded table {#what-it-does} ```python Python icon="python" @@ -63,6 +65,266 @@ separately from [`cleanup`](/maintenance/cleanup). The two are distinct jobs even though `optimize()` bundles both in one LanceDB Embedded call. +## Track on-demand Enterprise compaction {#compaction-jobs} + +On compatible Enterprise deployments, `compact_async()` / `compactAsync()` +submits SQL `OPTIMIZE ... REWRITE DATA` and returns a durable job handle. +The table handle supplies the namespace and branch. The existing remote +`optimize()` call keeps returning after submission with placeholder statistics; +use the job-returning API to wait for the actual rewrite and obtain its result. + + +```python Python +from datetime import timedelta + +job = table.compact_async( + compaction_options={"target_rows_per_fragment": 1000, "batch_size": 128} +) +result = job.wait(timeout=timedelta(minutes=10)) +print(result.rows_succeeded, result.fragments_removed, result.fragments_added) + +# Resume from another process with the same connection settings. +result = db.open_job(job.id).wait() +``` +```typescript TypeScript +import type { CompactionResult } from "@lancedb/lancedb"; + +const job = await table.compactAsync({ + targetRowsPerFragment: 1000, batchSize: 128, +}); +const result = await job.wait({ timeoutMs: 600_000 }); +console.log(result.rowsSucceeded, result.fragmentsRemoved, result.fragmentsAdded); + +if (job.id !== null) { + await (await db.openJob(job.id)).wait(); +} +``` +```rust Rust +use std::time::Duration; +use lancedb::job::JobWaitOptions; +use lancedb::table::{CompactionResult, optimize::CompactionOverrides}; + +let job = table.compact_async(CompactionOverrides { + target_rows_per_fragment: Some(1000), + batch_size: Some(128), + ..Default::default() +}).await?; +let result = job.wait_with_options( + JobWaitOptions::new().timeout(Duration::from_secs(600)), +).await?; +println!("Committed {} rows", result.rows_succeeded); + +if let Some(id) = job.id() { + db.open_job(id).await?.into_typed::()?.wait().await?; +} +``` + + +The result describes this job's committed rewrites, not a comparison of table +versions that could include concurrent writes. `partial_commit` identifies an +incomplete commit; `rows_failed` counts planned rows left uncommitted. +`more_work` means a bounded run left eligible work for another invocation. +A genuine no-op reports zero file/fragment counts; counts omitted by an older +worker are `None` in Python/Rust or `null` in TypeScript. A server that publishes +no compaction result raises an error when waiting, rather than fabricating zero +statistics. + +Submission requires Flight SQL connectivity and, under Standard authorization, +table Ownership plus Usage on the database and namespace hierarchy. Status, +progress, events, and cancellation use the generic HTTP job APIs and their +existing permissions. A wait timeout or dropping the handle does not cancel +the job. Local tables and historical-version checkouts are unsupported by the +job-returning API; ordinary embedded `optimize()` remains available. + +## Submit Enterprise compaction {#enterprise-manual-compaction} + +Use an existing Enterprise table and a connection configured for its database. +The `lancedb admin ...` and `lancedb job ...` examples on this page require the +**Enterprise administrative CLI**, available from your deployment administrator. +Check that `lancedb --help` lists `admin` and `job`. It needs Flight SQL +connectivity to submit the job and REST connectivity to read table settings and +job progress. + +The [public CLI installation](/tools/cli#install) supplies the client commands +`auth`, `profile`, and `sql`, without the administrative commands. You can use +that client for the SQL alternative below or submit through an SDK. Ask your +deployment administrator for the Enterprise CLI when you need the administrative +examples. + + +Use versions of the SDK, query nodes, agents, and workers that support these +options. +Older agents or workers can silently discard new job fields and run without the +requested source-row cap. Older-server errors propagate through the SDK without +retrying after dropping the settings. Manual submission requires a deployment +with SQL job submission enabled. Targets are resolved through the service +catalog, including PostgreSQL-backed SaaS catalogs. + + +Submit the same four invocation settings through any of these interfaces: + + +```bash CLI icon="terminal" +lancedb admin table optimize --table events \ + --target-rows-per-fragment 100000 \ + --max-source-rows 1000000 \ + --io-buffer-size 67108864 \ + --batch-size 1024 \ + --wait --wait-timeout-seconds 600 --poll-interval-seconds 5 +``` +```sql SQL icon="database" +OPTIMIZE events REWRITE DATA WITH ( + target_rows_per_fragment = 100000, + max_source_rows = 1000000, + io_buffer_size = 67108864, + batch_size = 1024 +); +``` + + +With the public CLI, execute SQL directly using a profile configured for the +same database and Flight SQL endpoint: + +```bash +lancedb sql --profile production --command \ + 'OPTIMIZE events REWRITE DATA WITH (max_source_rows = 1000000);' +``` + +Add `--branch exp` to the Enterprise CLI's `admin table optimize` command or +`branch = 'exp'` to SQL's `WITH` clause to target a branch. SDK calls use the table handle's selected branch. +Without a branch, the job targets main. CLI and SQL validate the table and branch +through the service catalog before creating a job. + +SQL and the CLI without `--wait` return after durable submission. The +job-returning SDK methods above preserve the ID and return committed statistics +when waiting completes. The CLI's `--wait` polls the same durable job and prints +its result. A timeout leaves the job running. Legacy remote `optimize()` still +returns after acceptance with placeholder statistics. + +Find earlier submissions with a table-scoped list, replacing `DATABASE` with +the database name: + +```bash +lancedb job list --db-name DATABASE --table-name events --job-type compact +``` + +For a namespaced table or branch, also pass `--namespace` or `--branch-name`. +Correlate the job's submission time and stored specification, then inspect +completion and worker events with a CLI profile for that deployment: + +```bash +lancedb job describe --job-id JOB_ID +lancedb job events --job-id JOB_ID +``` + +Under Standard authorization, submission requires table Ownership. `job describe` +accepts system Usage or, for a table job, Usage on its database and every namespace +in its path. `job list` and `job events` require system Usage; `job cancel` +requires system Operate. An unauthorized describe request returns 404 to hide +the job's existence; denied list/events requests return 403. Submission does not +grant system-level access to job lists or events. + +Manual compaction uses one worker with atomic execution and inline index +remapping. Remote `optimize` does not prune old versions or optimize indexes; +explicit pruning, index optimization, and unsupported non-default compaction +settings are rejected. Cleanup continues through the deployment's separate +[cleanup policy](/maintenance/cleanup). + +### Preview and inspect a run + +```sql +EXPLAIN OPTIMIZE events REWRITE DATA WITH ( + target_rows_per_fragment = 100000, + max_source_rows = 1000000 +); + +DESCRIBE JOB '' FORMAT JSON; +``` + +The preview uses the execution planner to report the source version, resolved +options, planned groups/fragments/rows, and whether more eligible work remains. +It creates no job. Submission plans against its own snapshot, so concurrent +writes can change the work after a preview. `EXPLAIN ANALYZE` is unsupported. + +JSON job diagnostics include reported maintenance progress and the completed +operation result alongside the existing time profile. While a job runs, its +result is null. SDK progress callbacks and CLI `--wait` expose the same worker +observations: rewritten groups/rows are execution progress, not proof of a +successful commit. Repeated task reports are counted once within an execution. +Python's `job.wait(progress=True)` displays rewritten rows; read the completion +result for committed statistics. + +### Choose invocation settings {#compaction-invocation-options} + +| SQL / Python / Rust | TypeScript | Meaning | +| --- | --- | --- | +| `target_rows_per_fragment` | `targetRowsPerFragment` | Positive target rows per output fragment; also affects candidate selection. This is a target, not an exact output-size guarantee. | +| `max_source_rows` | `maxSourceRows` | Positive live-source-row budget across whole planned tasks. Selection stops before a task would exceed the remaining budget. If the first useful task exceeds the budget, worker planning fails with the required live rows and source fragment count. | +| `io_buffer_size` | `ioBufferSize` | Nonnegative I/O read-ahead budget in bytes. Zero disables byte-based I/O backpressure; a positive value limits read-ahead. It is not a total-memory limit. | +| `batch_size` | `batchSize` | Positive scanner input-batch size in rows. | + +These settings do not impose a runtime limit. Values must be integers in the +interface's supported range. Python and TypeScript fragment targets and batch +sizes are limited to `u32::MAX`; TypeScript additionally requires safe integers. + +### Set table defaults {#table-compaction-defaults} + +Table tuning supports the same four fields under `job_types.compaction`: + +```bash +lancedb admin table overrides get --table events +lancedb admin table overrides set --table events \ + '{"job_types":{"compaction":{"enabled":false,"target_rows_per_fragment":100000,"max_source_rows":1000000,"io_buffer_size":67108864,"batch_size":1024}}}' +``` + +`set` replaces the whole overrides object. The example assumes no other settings +need preserving; read the current object and retain unrelated fields when +editing an existing policy. Use the same namespace and branch for policy reads, +writes, and compaction submission. + +Each manual field resolves as **invocation option → table tuning → +deployment/built-in default**. Automatic jobs resolve **table tuning → +deployment/built-in default**. The fragment target has a shared deployment +default. Automatic atomic jobs also use the deployment +`agent.jobTypes.compaction.atomicMaxSourceRows` when the table has no source-row +override; manual and deferred-remap jobs do not inherit that agent-only fallback. +Otherwise, an omitted source-row budget is unbounded. Unset I/O and batch settings +use the existing Lance/scanner defaults. + +The table's `enabled` flag controls automatic scheduling and admission. An +explicit manual job can run while table or deployment automatic compaction is +disabled. For example, inherit the table's target, source budget, and batch size +while overriding I/O backpressure for one run: + +```bash +lancedb admin table optimize --table events --io-buffer-size 0 +``` + +```sql +OPTIMIZE events REWRITE DATA WITH (io_buffer_size = 0); +``` + +Resolved tuning is stored with the durable job. A later table-policy change +affects future jobs and does not rewrite an existing job's settings. If the +budget cannot admit the first useful task, automatic preflight reports an error +without launching a compaction worker. A submitted manual job fails in worker +planning. Raise the budget to the reported requirement or review a smaller +fragment target; the target alone does not guarantee that a whole task fits. +Genuinely empty plans are still skipped by automatic preflight. + +Successful bounded automatic atomic runs record whether work remains, allowing +later runs below the normal fragment-count threshold. Run intervals, index +readiness, refresh, and failure-backoff gates still apply. Failed or timed-out +attempts retain pending continuation; explicit cancellation clears it. Changing +the effective source-row budget re-arms automatic failures recorded under a +different budget; toggling automatic enablement alone does not reset backoff. + +SDKs forward supplied fields and leave inheritance to the server. An explicitly +supplied SDK-default fragment target still overrides table tuning. Rust callers +should use `Table::compact_async(CompactionOverrides)` for that distinction: the legacy +`OptimizeAction::Compact` path treats its default-valued Lance fragment target +as unspecified because the options type has no presence bit. + ## Retraining indexes {#retrain} Folding new rows into an index preserves the structure the index was trained on. diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index facb9bdfe..ff56aff10 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -1790,7 +1790,10 @@ mixing in lower-level Lance file operations. System operations like `optimize()`, index updates, and table compaction also increment table version numbers. In LanceDB Embedded, `optimize()` can prune older versions based on its retention setting (`cleanup_older_than`, 7 days by default), which is when old-version files are removed and disk space is reclaimed. A deployment prunes them in the background -when its configuration enables [cleanup](/maintenance/cleanup); `optimize()` is not available there. +when its configuration enables [cleanup](/maintenance/cleanup). With compatible +releases, Enterprise `optimize()` submits [manual compaction](/maintenance/compaction#enterprise-manual-compaction) +only; it does not prune old versions. Submission returns before workers finish, +so observe the completed job and resulting table state before expecting a new version. **Tagged versions are never pruned.** A version with a tag pointing at it is retained regardless of age. When a tagged version is older than the retention window and diff --git a/docs/web/sql/ddl/job.mdx b/docs/web/sql/ddl/job.mdx index a4cf13490..8b507e6bc 100644 --- a/docs/web/sql/ddl/job.mdx +++ b/docs/web/sql/ddl/job.mdx @@ -67,9 +67,23 @@ DESC JOB '' [FORMAT TEXT | TABLE | JSON] ``` -Both spellings show a finished root job's timing profile. `TEXT` is the -default; `TABLE` returns typed phase/step rows and `JSON` returns the -profile as one document. A running job has no profile rows. +`TEXT` is the default and shows a finished root job's timing profile; +`TABLE` returns typed phase/step rows. These formats have no profile rows +while a job runs. + +On compatible deployments, `JSON` returns one document in the `profile` +column with `job_id`, `job_type`, `job_state`, reported `progress`, and the +successful operation's `result`, alongside any timing profile. It works +while the job runs, when `result` is null. Compaction counters describe +committed work only in the result; progress counters describe observed +execution work. Data prewarm results identify the pinned table version and +reported executor work. Unavailable measurements remain absent or null. + +```sql +DESCRIBE JOB '' FORMAT JSON; +``` + +Older deployments return only the timing profile. ## SHOW ERRORS {#errors} diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index d2196b93a..e2b50168a 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -1,9 +1,9 @@ --- title: "Table" sidebarTitle: "Table" -description: "CREATE, DESCRIBE, ALTER, CLONE and DROP TABLE." +description: "CREATE, DESCRIBE, ALTER, OPTIMIZE, CLONE and DROP TABLE." icon: table -keywords: ["create table", "alter table", "drop table", "describe", "clone", "ddl"] +keywords: ["create table", "alter table", "drop table", "describe", "clone", "optimize", "ddl"] availability: embedded: unavailable enterprise: available @@ -258,6 +258,56 @@ deployment stores its catalog. See [Object teardown](/basics/jobs#teardown). +## OPTIMIZE REWRITE DATA {#optimize} + +Submit a durable manual compaction job on a compatible Enterprise deployment: + +```sql +OPTIMIZE events REWRITE DATA WITH ( + target_rows_per_fragment = 100000, + max_source_rows = 1000000, + io_buffer_size = 67108864, + batch_size = 1024 +); +``` + +Write the table name immediately after `OPTIMIZE`, without a `TABLE` keyword. +All four settings are optional. Add `branch = 'exp'` in the same `WITH (...)` +clause to select a branch; an omitted branch targets main. Row targets, +source-row budgets, and scanner batch sizes must be positive integers. The I/O +budget is in bytes and accepts zero to disable byte-based I/O backpressure. +Unknown or duplicate options and invalid numbers are rejected before submission. + +Each field uses its invocation value, then that branch's table tuning, then +deployment/built-in defaults. The automatic-compaction `enabled` flags do not +block an explicit manual job. Tuning is captured in the durable specification; +later table changes affect future jobs. + +The statement returns a `job_id` after submission, before worker completion. +It runs atomic compaction on one worker with inline index remapping, without +pruning versions or optimizing indexes. The source-row budget admits whole +tasks; if the first useful task exceeds it, worker planning fails with the +required live rows and source fragment count. The table and branch are validated +through the service catalog before creating a job. + +See [manual compaction](/maintenance/compaction#enterprise-manual-compaction) +for the option meanings, supported deployment and version requirements, +authorization, job inspection, table defaults, and equivalent CLI/SDK examples. + + +### Preview manual compaction + +```sql +EXPLAIN OPTIMIZE events REWRITE DATA WITH (max_source_rows = 1000000); +DESCRIBE JOB '' FORMAT JSON; +``` + +The preview reports the selected source version, effective options, planned +work and continuation using the worker's planner without submitting a job. +`EXPLAIN ANALYZE` is unsupported. The JSON diagnostic includes reported progress +and a successful job's committed result. See [Compaction](/maintenance/compaction#compaction-jobs) +for durable SDK handles and CLI waiting. + ## What to read next {#next} diff --git a/docs/web/tools/cli.mdx b/docs/web/tools/cli.mdx index 2d5104322..0259bf9fb 100644 --- a/docs/web/tools/cli.mdx +++ b/docs/web/tools/cli.mdx @@ -10,6 +10,12 @@ Use the `lancedb` command-line client to open an interactive SQL shell, run a statement, or execute a SQL file. SQL requires a running deployment with an [Arrow Flight SQL endpoint](/basics/sql#sql-is-remote). +This public client exposes `auth`, `profile`, and `sql`. Commands such as +`lancedb admin ...` and `lancedb job ...` require the Enterprise administrative +CLI from your deployment administrator; the public client archive and source +installation below do not include them. Use `lancedb sql --command` for SQL +statements supported by your deployment. + ## Install Download a CLI archive and `SHA256SUMS` from the diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index d0ccd2efd..d0d000e10 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -30,6 +30,7 @@ napi = { version = "3.15.0", default-features = false, features = [ "serde-json", ] } chrono.workspace = true +serde.workspace = true serde_json.workspace = true napi-derive = "3.6.13" # Prevent dynamic linking of lzma, which comes from datafusion diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 9baa51292..c5f81391a 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -2662,3 +2662,270 @@ describe("lazy resource listings", () => { }); } }); + +describe("remote compaction job results", () => { + test.each([true, false])( + "reopens typed compaction result (counts=%s)", + async (counts) => { + await withMockDatabase( + (request, response) => { + expect(request.url).toBe("/v1/jobs/describe"); + const result = JSON.parse(`{ + "partial_commit": false, + "rows_succeeded": 12, + "rows_failed": 0, + "completion_percentage": 100 + }`); + if (counts) { + Object.assign( + result, + JSON.parse(`{ + "files_added": 1, + "files_removed": 3, + "fragments_added": 1, + "fragments_removed": 3 + }`), + ); + } + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + `{"job_id":"compacting-job","job_type":"compact","job_state":"DONE","result":${JSON.stringify(result)}}`, + ); + }, + async (db) => { + const job = + await db.openJob( + "compacting-job", + ); + const result = await job.wait(); + expect(result.rowsSucceeded).toBe(12); + expect(result.moreWork).toBe(false); + expect(result.fragmentsRemoved).toBe(counts ? 3 : null); + }, + ); + }, + ); +}); + +describe("data prewarm typed results", () => { + test.each([null, {}])( + "rejects a missing typed outcome (%p)", + async (result) => { + await withMockDatabase( + (_request, response) => { + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + `{"job_id":"warming-job","job_type":"prewarm_page_cache","job_state":"DONE","result":${JSON.stringify(result)}}`, + ); + }, + async (db) => { + const job = await db.openJob("warming-job"); + await expect(job.wait()).rejects.toThrow(); + }, + ); + }, + ); + + test.each([true, false])( + "reopens a result (counters=%s)", + async (counters) => { + await withMockDatabase( + (_request, response) => { + const result = JSON.parse( + counters + ? '{"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4}' + : '{"table_version":42}', + ); + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + JSON.stringify({ + ["job_id"]: "warming-job", + ["job_type"]: "prewarm_page_cache", + ["job_state"]: "DONE", + progress: null, + ["operation_progress"]: { + phase: "reading", + ["executors_completed"]: 2, + }, + result, + }), + ); + }, + async (db) => { + const job = + await db.openJob( + "warming-job", + ); + const result = await job.wait(); + expect(result.tableVersion).toBe(42); + expect(result.executorsCompleted).toBe(counters ? 2 : null); + expect(result.bytesRead).toBeNull(); + expect((await job.progress())?.executors_completed).toBe(2); + }, + ); + }, + ); +}); + +describe("job wait deadlines", () => { + function response(kind: string, done: boolean) { + const result = + kind === "compact" + ? '{"partial_commit":false,"rows_succeeded":12,"rows_failed":0,"completion_percentage":100}' + : kind === "prewarm_page_cache" + ? '{"table_version":42,"executors_targeted":2,"executors_completed":2}' + : "null"; + return `{"job_id":"bounded-job","job_type":"${kind}","job_state":"${done ? "DONE" : "IN_PROGRESS"}","result":${done ? result : "null"}}`; + } + + test.each(["compact", "prewarm_page_cache", "create_index"])( + "%s stops polling at timeout, resumes, and reopens", + async (kind) => { + let done = false; + let describes = 0; + const progress: JobProgress[] = []; + await withMockDatabase( + (request, res) => { + expect(request.url).toBe("/v1/jobs/describe"); + describes++; + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(response(kind, done)); + }, + async (db) => { + const fallback = setTimeout(() => { + done = true; + }, 1000); + try { + const job = await db.openJob("bounded-job"); + await expect( + job.wait({ timeoutMs: 50, onProgress: (p) => progress.push(p) }), + ).rejects.toThrow(/bounded-job.*continues/); + expect(job.state).toBe("running"); + await new Promise((resolve) => setImmediate(resolve)); + const requestsAtTimeout = describes; + const updatesAtTimeout = progress.length; + await new Promise((resolve) => setTimeout(resolve, 350)); + expect(describes).toBe(requestsAtTimeout); + expect(progress).toHaveLength(updatesAtTimeout); + done = true; + const result = await job.wait({ + timeoutMs: 1000, + onProgress: (p) => progress.push(p), + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(progress.some((p) => p.state === "finished")).toBe(true); + expect(job.state).toBe("finished"); + expect(result).toEqual( + kind === "compact" + ? expect.objectContaining({ rowsSucceeded: 12 }) + : kind === "prewarm_page_cache" + ? expect.objectContaining({ tableVersion: 42 }) + : undefined, + ); + // Existing callback-only and argument-free calls remain supported. + expect(await job.wait((p) => progress.push(p))).toEqual(result); + expect(await job.wait()).toEqual(result); + const reopened = await db.openJob("bounded-job"); + expect(await reopened.wait({ timeoutMs: 1000 })).toEqual(result); + } finally { + clearTimeout(fallback); + } + }, + ); + }, + ); + + it("bounds a pending HTTP response and permits a later wait", async () => { + let slow = false; + let requests = 0; + await withMockDatabase( + (request, res) => { + expect(request.url).toBe("/v1/jobs/describe"); + requests++; + const send = () => { + if (!res.destroyed) { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(response("prewarm_page_cache", slow)); + } + }; + if (slow) setTimeout(send, 300); + else send(); + }, + async (db) => { + const job = await db.openJob("bounded-job"); + slow = true; + await expect(job.wait({ timeoutMs: 50 })).rejects.toThrow("continues"); + expect(job.state).toBe("running"); + const stoppedAt = requests; + await new Promise((resolve) => setTimeout(resolve, 350)); + expect(requests).toBe(stoppedAt); + const result = await job.wait({ timeoutMs: 1000 }); + expect(result).toEqual(expect.objectContaining({ tableVersion: 42 })); + }, + ); + }); + + it("accepts zero timeout and validates options before polling", async () => { + let requests = 0; + let done = false; + await withMockDatabase( + (_request, res) => { + requests++; + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(response("compact", done)); + }, + async (db) => { + const fallback = setTimeout(() => { + done = true; + }, 1000); + try { + const job = await db.openJob("bounded-job"); + for (const timeoutMs of [ + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + Number.MAX_SAFE_INTEGER + 1, + "10", + true, + ]) { + await expect( + job.wait({ timeoutMs: timeoutMs as number }), + ).rejects.toThrow("nonnegative safe integer"); + } + await expect(job.wait({ timeout: 10 } as never)).rejects.toThrow( + "Unknown job wait option", + ); + await expect(job.wait({ onProgress: 7 } as never)).rejects.toThrow( + "onProgress must be a function", + ); + await expect(job.wait(10 as never)).rejects.toThrow("options object"); + expect(requests).toBe(1); + await expect(job.wait({ timeoutMs: 0 })).rejects.toThrow("Timeout"); + } finally { + clearTimeout(fallback); + } + }, + ); + }); + + test.each(["FAILED", "CANCELLED"])( + "preserves a %s outcome when a timeout is configured", + async (state) => { + await withMockDatabase( + (_request, res) => { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end( + `{"job_id":"bounded-job","job_type":"compact","job_state":"${state}"}`, + ); + }, + async (db) => { + const job = await db.openJob("bounded-job"); + await expect(job.wait({ timeoutMs: 1000 })).rejects.toThrow( + state === "FAILED" ? /failed/i : /cancelled/i, + ); + }, + ); + }, + ); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 99c58a8c9..7a103d2c9 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -4678,15 +4678,94 @@ describe.each(arrowVersions)( ]; const table = await db.createTable("prewarm_data_test", data); - // prewarmData is only supported in LanceDB Enterprise. We verify the call - // is wired through napi and surfaces the expected error for both - // arg shapes (undefined and string[]). await expect(table.prewarmData()).rejects.toThrow( - "prewarm_data is currently only supported in LanceDB Enterprise", + "only supported on remote tables", ); await expect(table.prewarmData(["text"])).rejects.toThrow( - "prewarm_data is currently only supported in LanceDB Enterprise", + "only supported on remote tables", ); + await expect( + table.prewarmData({ + columns: ["text"], + filter: "text = 'alpha'", + concurrency: 2, + }), + ).rejects.toThrow("only supported on remote tables"); + }); + + test("prewarmData preserves argument forms and returns after submission", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("prewarm_submission", [{ id: 1 }]); + const wait = jest.fn(); + const submit = jest + .spyOn(table, "prewarmDataAsync") + .mockResolvedValue({ wait } as unknown as Awaited< + ReturnType + >); + const options = { columns: ["id"], filter: "id > 0", concurrency: 2 }; + try { + await expect(table.prewarmData(options)).resolves.toBeUndefined(); + expect(submit).toHaveBeenLastCalledWith(options); + await expect(table.prewarmData(["id"])).resolves.toBeUndefined(); + expect(submit).toHaveBeenLastCalledWith({ columns: ["id"] }); + await expect(table.prewarmData([])).resolves.toBeUndefined(); + expect(submit).toHaveBeenLastCalledWith({ columns: [] }); + await expect(table.prewarmData()).resolves.toBeUndefined(); + expect(submit).toHaveBeenLastCalledWith(undefined); + expect(wait).not.toHaveBeenCalled(); + } finally { + submit.mockRestore(); + } + }); + + test("prewarmData validates options before submission", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("prewarm_options", [{ id: 1 }]); + await expect( + table.prewarmData({ unsupported: 1 } as never), + ).rejects.toThrow("Unsupported data prewarm option: unsupported"); + for (const concurrency of [ + 0, + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + 4294967296, + ]) { + await expect(table.prewarmData({ concurrency })).rejects.toThrow( + "concurrency must be an integer", + ); + } + }); + + test("prewarmDataAsync validates options and rejects local tables", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("prewarm_job", [{ id: 1 }]); + await expect(table.prewarmDataAsync()).rejects.toThrow( + "only supported on remote tables", + ); + await expect( + table.prewarmDataAsync({ + columns: ["id"], + filter: "id > 0", + concurrency: 2, + }), + ).rejects.toThrow("only supported on remote tables"); + await expect( + table.prewarmDataAsync({ unsupported: 1 } as never), + ).rejects.toThrow("Unsupported data prewarm option: unsupported"); + for (const concurrency of [ + 0, + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + 4294967296, + ]) { + await expect(table.prewarmDataAsync({ concurrency })).rejects.toThrow( + "concurrency must be an integer", + ); + } }); test("full text index on list", async () => { @@ -5791,3 +5870,19 @@ describe("computed columns", () => { expect(rows.map((r) => r.doubled).sort()).toEqual([10, 2]); }); }); + +describe("durable compaction validation", () => { + test("rejects local tables and unknown options", async () => { + const db = await connect(`memory://compaction-job-${Date.now()}`); + const table = await db.createTable("test", [{ id: 1 }]); + await expect(table.compactAsync()).rejects.toThrow( + "only supported on remote tables", + ); + await expect( + table.compactAsync({ unrecognizedLimit: 1 } as never), + ).rejects.toThrow("Unsupported compaction option"); + await expect( + table.compactAsync({ targetRowsPerFragment: 0 }), + ).rejects.toThrow("safe integer"); + }); +}); diff --git a/nodejs/lancedb/compaction.ts b/nodejs/lancedb/compaction.ts new file mode 100644 index 000000000..3aaf3907c --- /dev/null +++ b/nodejs/lancedb/compaction.ts @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/** Actual committed outcome of one remote compaction job. */ +export interface CompactionResult { + /** A bounded run left eligible work for another invocation. */ + moreWork: boolean; + /** Some planned groups were not committed. */ + partialCommit: boolean; + /** Live source rows in committed rewrite groups. */ + rowsSucceeded: number; + /** Planned live rows not committed by this job. */ + rowsFailed: number; + /** Percentage of planned live rows committed, from 0 to 100. */ + completionPercentage: number; + /** Files added, including deletion files; null if an older worker omitted it. */ + filesAdded: number | null; + /** Files removed, including deletion files; null if an older worker omitted it. */ + filesRemoved: number | null; + /** Fragments added by committed rewrites; null if an older worker omitted it. */ + fragmentsAdded: number | null; + /** Fragments removed by committed rewrites; null if an older worker omitted it. */ + fragmentsRemoved: number | null; +} + +/** @internal */ +export function decodeCompactionResult(value: unknown): CompactionResult { + // The Rust typed-job decoder validates the wire payload before it reaches JS. + const result = value as Record; + return { + moreWork: result.more_work as boolean, + partialCommit: result.partial_commit as boolean, + rowsSucceeded: result.rows_succeeded as number, + rowsFailed: result.rows_failed as number, + completionPercentage: result.completion_percentage as number, + filesAdded: (result.files_added as number | null) ?? null, + filesRemoved: (result.files_removed as number | null) ?? null, + fragmentsAdded: (result.fragments_added as number | null) ?? null, + fragmentsRemoved: (result.fragments_removed as number | null) ?? null, + }; +} diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index 9c83d833f..ce71c4e89 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -583,7 +583,7 @@ export abstract class Connection { * result, failure and event history, so there is no separate * connection-level call for any of them. */ - abstract openJob(jobId: string): Promise; + abstract openJob(jobId: string): Promise>; /** * Iterate lazily over server-side jobs across the database's tables. @@ -1017,8 +1017,8 @@ export class LocalConnection extends Connection { ); } - async openJob(jobId: string): Promise { - return new Job(await this.inner.openJob(jobId)); + async openJob(jobId: string): Promise> { + return new Job(await this.inner.openJob(jobId)); } listJobs(options: ListingOptions = {}): Listing { diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index a6bcd68f5..3f0aed61f 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -118,7 +118,7 @@ export { Job, JobEventsOptions, } from "./job"; -export type { JobProgress, JobProgressCallback } from "./job"; +export type { JobProgress, JobProgressCallback, JobWaitOptions } from "./job"; export { AutoQuery, @@ -175,6 +175,7 @@ export { UpdateOptions, OptimizeOptions, CompactionOptions, + PrewarmDataOptions, Version, WriteProgress, FtsToken, @@ -664,3 +665,7 @@ export { } from "./catalog"; export { Listing, ListingOptions } from "./listing"; + +export type { CompactionResult } from "./compaction"; + +export type { PrewarmDataResult } from "./prewarm"; diff --git a/nodejs/lancedb/job.ts b/nodejs/lancedb/job.ts index f38d8d7fa..40c27365e 100644 --- a/nodejs/lancedb/job.ts +++ b/nodejs/lancedb/job.ts @@ -2,7 +2,9 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors import { Table as ArrowTable, tableFromIPC } from "apache-arrow"; +import { decodeCompactionResult } from "./compaction"; import { JobFailureInfo, Job as NativeJob } from "./native"; +import { decodePrewarmDataResult } from "./prewarm"; /** Which of a job's events {@link Job.events} returns. */ export interface JobEventsOptions { @@ -39,6 +41,31 @@ export interface JobProgress { rows_remaining?: number | null; // biome-ignore lint/style/useNamingConvention: server wire format rows_failed?: number | null; + /** Maintenance work observations; rewritten rows are not committed rows. */ + // biome-ignore lint/style/useNamingConvention: server wire format + groups_planned?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + groups_completed?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + rows_rewritten?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_targeted?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_completed?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_partial?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_active?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_failed?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + fragments_selected?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + ranges_completed?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + ranges_planned?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + bytes_read?: number | null; /** Execution identity and sample time used for client-side ETA derivation. */ // biome-ignore lint/style/useNamingConvention: server wire format execution_epoch?: number | null; @@ -54,6 +81,18 @@ export interface JobProgress { /** Callback for progress snapshots observed while waiting for a job. */ export type JobProgressCallback = (progress: JobProgress) => void; +/** Client-side controls for waiting without cancelling the underlying job. */ +export interface JobWaitOptions { + /** + * Maximum wait in milliseconds, including status requests and polling backoff. + * Must be a nonnegative safe integer. Omit to wait indefinitely; zero allows + * only an immediately ready result. + */ + timeoutMs?: number; + /** Observe progress using the same poller that waits for completion. */ + onProgress?: JobProgressCallback; +} + /** * A handle to an operation that may still be running. * @@ -71,11 +110,20 @@ export type JobProgressCallback = (progress: JobProgress) => void; * * @hideconstructor */ -export class Job { +export class Job { private readonly inner: NativeJob; - constructor(inner: NativeJob) { + private readonly resultDecoder?: (value: unknown) => T; + + constructor(inner: NativeJob, resultDecoder?: (value: unknown) => T) { this.inner = inner; + this.resultDecoder = + resultDecoder ?? + (inner.jobType === "prewarm_page_cache" + ? (decodePrewarmDataResult as (value: unknown) => T) + : inner.jobType === "compact" + ? (decodeCompactionResult as (value: unknown) => T) + : undefined); } /** @@ -161,18 +209,64 @@ export class Job { * synchronous observer: its return value is ignored and not awaited. If it * throws, the error is logged with `console.warn` and waiting continues; a * callback exception does not reject `wait`. + * + * Pass an options object to set a client-side timeout. Expiry rejects with an + * error and stops this wait, including pending status requests and backoff. + * The operation continues; use the same handle to wait again. Registry jobs + * can also be reopened with `Connection.openJob`; query IDs cannot. + * + * @example + * ```ts + * const result = await job.wait({ timeoutMs: 60_000, onProgress: console.log }); + * ``` */ - async wait(progressCallback?: JobProgressCallback): Promise { - if (progressCallback === undefined) { - return this.inner.wait(); + async wait( + optionsOrProgress?: JobWaitOptions | JobProgressCallback, + ): Promise { + const options: JobWaitOptions = + typeof optionsOrProgress === "function" + ? { onProgress: optionsOrProgress } + : (optionsOrProgress ?? {}); + if (typeof options !== "object" || Array.isArray(options)) { + throw new TypeError( + "wait expects an options object or a progress callback", + ); } - return this.inner.wait((progress) => { - try { - progressCallback(this.enrichProgress(progress)); - } catch (error) { - console.warn("Job progress callback threw:", error); + for (const key of Object.keys(options)) { + if (key !== "timeoutMs" && key !== "onProgress") { + throw new TypeError(`Unknown job wait option: ${key}`); } - }); + } + const { timeoutMs, onProgress: progressCallback } = options; + if ( + timeoutMs !== undefined && + (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0) + ) { + throw new RangeError("timeoutMs must be a nonnegative safe integer"); + } + if ( + progressCallback !== undefined && + typeof progressCallback !== "function" + ) { + throw new TypeError("onProgress must be a function"); + } + const callback = + progressCallback === undefined + ? undefined + : (progress: Record) => { + try { + progressCallback(this.enrichProgress(progress)); + } catch (error) { + console.warn("Job progress callback threw:", error); + } + }; + if (this.resultDecoder !== undefined) { + return this.resultDecoder( + await this.inner.waitResult(callback, timeoutMs), + ); + } + await this.inner.wait(callback, timeoutMs); + return undefined as T; } /** Request cancellation. Cancelling a finished operation is a no-op. */ diff --git a/nodejs/lancedb/prewarm.ts b/nodejs/lancedb/prewarm.ts new file mode 100644 index 000000000..942e0a19f --- /dev/null +++ b/nodejs/lancedb/prewarm.ts @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/** Reported executor work for a pinned snapshot; unavailable measurements stay null. */ +export interface PrewarmDataResult { + /** The source snapshot captured by submission. */ + tableVersion: number; + /** Reported executors targeted, or null when unavailable. */ + executorsTargeted: number | null; + /** Executors that finished successfully or partially, or null when unavailable. */ + executorsCompleted: number | null; + /** Subset of completed executors reporting partial warming, or null when unavailable. */ + executorsPartial: number | null; + /** Reported fragments selected, or null when unavailable. */ + fragmentsSelected: number | null; + /** Reported ranges completed, or null when unavailable. */ + rangesCompleted: number | null; + /** Reported bytes read, or null when unavailable. */ + bytesRead: number | null; +} + +/** @internal */ +export function decodePrewarmDataResult(value: unknown): PrewarmDataResult { + // Rust validates the typed wire result before handing it to JavaScript. + const result = value as Record; + return { + tableVersion: result.table_version as number, + executorsTargeted: result.executors_targeted ?? null, + executorsCompleted: result.executors_completed ?? null, + executorsPartial: result.executors_partial ?? null, + fragmentsSelected: result.fragments_selected ?? null, + rangesCompleted: result.ranges_completed ?? null, + bytesRead: result.bytes_read ?? null, + }; +} diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index f949bd00a..2fff63108 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -1,6 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +import { CompactionResult, decodeCompactionResult } from "./compaction"; +import { PrewarmDataResult, decodePrewarmDataResult } from "./prewarm"; + import { Table as ArrowTable, Data, @@ -165,6 +168,16 @@ export interface UpdateOptions { where: string; } +/** Settings for submitting a durable remote data-cache prewarm job. */ +export interface PrewarmDataOptions { + /** Lance field paths to warm; omitted or empty means every column. */ + columns?: string[]; + /** A single SQL predicate for conservative metadata pruning. */ + filter?: string; + /** Positive per-executor concurrency, at most 4294967295. */ + concurrency?: number; +} + /** Per-invocation compaction settings. Values must be safe integers. */ export interface CompactionOptions { /** Positive target rows per output fragment; also affects candidate selection. */ @@ -562,22 +575,58 @@ export abstract class Table { /** * Prewarm one or more columns of data in the table. * - * @param columns The columns to prewarm. If undefined, all columns are prewarmed. - * * This will load the column data into the page cache so that future queries that * read those columns avoid the initial cold-start latency. This call initiates * prewarming and returns once the request is accepted; the warming itself may - * continue in the background. Calling it on already-prewarmed columns is a - * no-op on the server. + * continue in the background. Submission uses SQL PREWARM and needs Flight + * SQL connectivity. Use {@link prewarmDataAsync} to retain the job handle. * * Prewarming is generally useful for columns used in filters or projections. * Large columns (e.g. high-dimensional vectors or binary data) may not be * practical to prewarm. * * This feature is currently only supported in LanceDB Enterprise. + * + * @param options Columns, a metadata-pruning filter, and per-executor concurrency. + * Omitted or empty columns warm every column. + * + * @example + * await table.prewarmData({ + * columns: ["payload"], filter: "quality > 0.7", concurrency: 4, + * }); + */ + abstract prewarmData(options?: PrewarmDataOptions): Promise; + + /** + * Submit data prewarm using the columns-array form and return after acceptance. + * @param columns Columns to warm; omitted or empty means every column. */ abstract prewarmData(columns?: string[]): Promise; + /** + * Submit data prewarm through SQL and return its durable warming-job handle. + * + * The table handle supplies the branch and namespace. Requires a compatible + * SQL PREWARM server and Flight SQL connectivity. Standard authorization + * requires table Select and database/namespace Usage. Status/wait use generic + * HTTP job APIs; events and cancellation retain their own privileges. + * No REST fallback or option-dropping retry is performed. Historical-version + * handles are unsupported; call `checkoutLatest()` first. + * + * Submission returns after acceptance. Use `job.wait()` for completion, or + * save `job.id` and reopen it with `db.openJob(id)`. A timeout does not cancel + * the job. After `job.refresh()`, `job.spec.table_version` is the pinned version. + * + * @example + * const job = await table.prewarmDataAsync({ + * columns: ["video"], filter: "quality > 0.7", concurrency: 4, + * }); + * await job.wait(); + */ + abstract prewarmDataAsync( + options?: PrewarmDataOptions, + ): Promise>; + /** * Waits for asynchronous indexing to complete on the table. * @@ -1209,6 +1258,28 @@ export abstract class Table { * out state and the read_consistency_interval, if any, will apply. */ abstract restore(): Promise; + /** + * Submit remote compaction and return its durable job after acceptance. + * + * Uses SQL OPTIMIZE, inheriting branch and namespace from this table. Requires + * a compatible remote server and table Ownership plus parent Usage. Local and + * historical-version handles are unsupported. Existing optimize() behavior is unchanged. + * Waiting tracks the rewrite itself and returns actual row/file statistics. + * Missing result payloads are errors; older workers can omit file counts. + * Status, progress, events and cancellation reuse the generic HTTP job APIs. + * Reopen with db.openJob(job.id!). A wait timeout does not cancel work. + * + * @example + * const job = await table.compactAsync({ targetRowsPerFragment: 1000 }); + * const result = await job.wait(); + * console.log(result.rowsSucceeded, result.fragmentsRemoved); + */ + async compactAsync( + _options?: CompactionOptions, + ): Promise> { + throw new Error("compaction jobs are only supported on remote tables"); + } + /** * Optimize the on-disk data and indices for better performance. * @@ -1505,8 +1576,30 @@ export class LocalTable extends Table { await this.inner.prewarmIndex(name); } - async prewarmData(columns?: string[]): Promise { - await this.inner.prewarmData(columns); + async prewarmData(options?: PrewarmDataOptions): Promise; + async prewarmData(columns?: string[]): Promise; + async prewarmData( + columnsOrOptions?: string[] | PrewarmDataOptions, + ): Promise { + await this.prewarmDataAsync( + Array.isArray(columnsOrOptions) + ? { columns: columnsOrOptions } + : columnsOrOptions, + ); + } + + async prewarmDataAsync( + options?: PrewarmDataOptions, + ): Promise> { + for (const key of Object.keys(options ?? {})) { + if (!["columns", "filter", "concurrency"].includes(key)) { + throw new Error(`Unsupported data prewarm option: ${key}`); + } + } + return new Job( + await this.inner.prewarmDataAsync(options), + decodePrewarmDataResult, + ); } async waitForIndex( @@ -1884,20 +1977,18 @@ export class LocalTable extends Table { return this.inner.currentBranch() ?? null; } + async compactAsync( + options?: CompactionOptions, + ): Promise> { + validateCompactionOptions(options); + return new Job( + await this.inner.compactAsync(options), + decodeCompactionResult, + ); + } + async optimize(options?: Partial): Promise { - // JavaScript callers can supply extra keys that TypeScript would reject. - // Refuse them before the native binding can silently discard a work limit. - const supported = new Set([ - "targetRowsPerFragment", - "maxSourceRows", - "ioBufferSize", - "batchSize", - ]); - for (const key of Object.keys(options?.compactionOptions ?? {})) { - if (!supported.has(key)) { - throw new Error(`Unsupported compaction option: ${key}`); - } - } + validateCompactionOptions(options?.compactionOptions); return await this.inner.optimize( options?.cleanupOlderThan?.getTime(), options?.deleteUnverified, @@ -2197,3 +2288,19 @@ function rowIdsToBigInts(rowIds: readonly (bigint | number)[]): bigint[] { return BigInt(id); }); } + +function validateCompactionOptions(options?: CompactionOptions): void { + // JavaScript callers can supply extra keys that TypeScript would reject. + // Refuse them before the native binding can silently discard a work limit. + const supported = new Set([ + "targetRowsPerFragment", + "maxSourceRows", + "ioBufferSize", + "batchSize", + ]); + for (const key of Object.keys(options ?? {})) { + if (!supported.has(key)) { + throw new Error(`Unsupported compaction option: ${key}`); + } + } +} diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index 914f9e4c9..fa1c289b1 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -567,7 +567,19 @@ impl Connection { #[napi(catch_unwind)] pub async fn open_job(&self, job_id: String) -> napi::Result { let job = self.get_inner()?.open_job(&job_id).await.default_error()?; - Ok(crate::job::Job::new(job)) + if job.job_type().as_deref() == Some("prewarm_page_cache") { + Ok(crate::job::Job::new_typed( + job.into_typed::() + .default_error()?, + )) + } else if job.job_type().as_deref() == Some("compact") { + Ok(crate::job::Job::new_typed( + job.into_typed::() + .default_error()?, + )) + } else { + Ok(crate::job::Job::new(job)) + } } /// List server-side jobs across the database's tables. diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 09b245f97..15e95caad 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use std::sync::Arc; +use std::{sync::Arc, time::Duration}; use arrow_array::RecordBatch; -use lancedb::job::JobEventsRequest; +use lancedb::job::{JobEventsRequest, JobWaitOptions}; use napi::bindgen_prelude::Buffer; use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; @@ -17,7 +17,7 @@ type JobProgressFn = /// A handle to an operation that may still be running. #[napi] pub struct Job { - inner: Arc, + inner: Arc, String>>>, } impl Job { @@ -26,7 +26,19 @@ impl Job { T: Clone + Send + Sync + 'static, { Self { - inner: Arc::new(inner.map(|_| ())), + inner: Arc::new(inner.map(|_| Ok(None))), + } + } + pub(crate) fn new_typed(inner: lancedb::Job) -> Self + where + T: Clone + serde::Serialize + Send + Sync + 'static, + { + Self { + inner: Arc::new(inner.map(|result| { + serde_json::to_value(result) + .map(Some) + .map_err(|error| format!("failed to serialize typed job result: {error}")) + })), } } } @@ -67,22 +79,56 @@ impl Job { /// backend poller without starting another polling loop. #[napi( catch_unwind, - ts_args_type = "progressCallback?: (progress: Record) => void" + ts_args_type = "progressCallback?: (progress: Record) => void, timeoutMs?: number" )] - pub async fn wait(&self, progress_callback: Option) -> napi::Result<()> { - if let Some(progress_callback) = progress_callback { - self.inner - .wait_with_progress(move |description| { - progress_callback.call( - description.progress_snapshot(), - ThreadsafeFunctionCallMode::NonBlocking, - ); - }) - .await - .default_error() - } else { - self.inner.wait().await.default_error() + pub async fn wait( + &self, + progress_callback: Option, + timeout_ms: Option, + ) -> napi::Result<()> { + self.wait_result(progress_callback, timeout_ms) + .await + .map(|_| ()) + } + + /// The typed terminal value used by result-returning SDK operations. + #[napi( + catch_unwind, + ts_args_type = "progressCallback?: (progress: Record) => void, timeoutMs?: number" + )] + pub async fn wait_result( + &self, + progress_callback: Option, + timeout_ms: Option, + ) -> napi::Result> { + let mut options = JobWaitOptions::new(); + if let Some(timeout_ms) = timeout_ms { + const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; + if !timeout_ms.is_finite() + || timeout_ms.fract() != 0.0 + || !(0.0..=MAX_SAFE_INTEGER).contains(&timeout_ms) + { + return Err(napi::Error::new( + napi::Status::InvalidArg, + "timeoutMs must be a nonnegative safe integer", + )); + } + options = options.timeout(Duration::from_millis(timeout_ms as u64)); } + if let Some(progress_callback) = progress_callback { + options = options.progress(move |description| { + progress_callback.call( + description.progress_snapshot(), + ThreadsafeFunctionCallMode::NonBlocking, + ); + }); + } + let result = self + .inner + .wait_with_options(options) + .await + .default_error()?; + result.map_err(napi::Error::from_reason) } /// Request cancellation. Cancelling a finished operation is a no-op. diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index c9e03b2a3..3a9b8be72 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -27,6 +27,32 @@ use crate::merge::NativeMergeInsertBuilder; use crate::query::{Query, TakeQuery, VectorQuery}; use crate::util::schema_to_buffer; +/// Settings for durable data-cache prewarm submission. +#[napi(object)] +pub struct PrewarmDataOptions { + pub columns: Option>, + pub filter: Option, + pub concurrency: Option, +} + +impl PrewarmDataOptions { + fn into_options(self) -> napi::Result { + let mut options = + lancedb::table::PrewarmDataOptions::new().columns(self.columns.unwrap_or_default()); + options.filter = self.filter; + if let Some(value) = self.concurrency { + if !value.is_finite() || value.fract() != 0.0 || value < 1.0 || value > u32::MAX as f64 + { + return Err(napi::Error::from_reason( + "concurrency must be an integer between 1 and 4294967295", + )); + } + options.concurrency = Some(value as u32); + } + Ok(options) + } +} + /// Per-invocation file-compaction settings. All numbers must be safe integers. #[napi(object)] pub struct CompactionOptions { @@ -298,6 +324,23 @@ impl Table { .default_error() } + #[napi(catch_unwind)] + pub async fn prewarm_data_async( + &self, + options: Option, + ) -> napi::Result { + let options = options + .map(PrewarmDataOptions::into_options) + .transpose()? + .unwrap_or_default(); + let job = self + .inner_ref()? + .prewarm_data_async(options) + .await + .default_error()?; + Ok(crate::job::Job::new_typed(job)) + } + #[napi(catch_unwind)] pub async fn wait_for_index(&self, index_names: Vec, timeout_s: i64) -> Result<()> { let timeout = std::time::Duration::from_secs(timeout_s.try_into().unwrap()); @@ -894,6 +937,23 @@ impl Table { Ok(self.inner_ref()?.current_branch()) } + #[napi(catch_unwind)] + pub async fn compact_async( + &self, + options: Option, + ) -> napi::Result { + let options = options + .map(CompactionOptions::into_overrides) + .transpose()? + .unwrap_or_default(); + let job = self + .inner_ref()? + .compact_async(options) + .await + .default_error()?; + Ok(crate::job::Job::new_typed(job)) + } + #[napi(catch_unwind)] pub async fn optimize( &self, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 19454790a..b4b97ff38 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -645,6 +645,13 @@ class Table: async def restore(self, version: Optional[Union[int, str]] = None): ... async def prewarm_index(self, index_name: str) -> None: ... async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: ... + async def prewarm_data_async( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> Job: ... async def list_indices(self) -> list[IndexConfig]: ... async def tokenize( self, @@ -787,6 +794,9 @@ class Table: async def update_field_metadata( self, updates: list[dict[str, Any]] ) -> UpdateFieldMetadataResult: ... + async def compact_async( + self, compaction_options: Optional[Dict[str, Any]] = None + ) -> Job: ... async def optimize( self, *, diff --git a/python/python/lancedb/compaction.py b/python/python/lancedb/compaction.py new file mode 100644 index 000000000..823b0a281 --- /dev/null +++ b/python/python/lancedb/compaction.py @@ -0,0 +1,37 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Results of durable remote compaction jobs.""" + +from dataclasses import dataclass, fields +import json +from typing import Optional + + +@dataclass(frozen=True) +class CompactionResult: + """Actual committed outcome of one remote compaction invocation. + + ``rows_failed`` counts planned live rows that were not committed, including + partial progress. ``more_work`` means a bounded run left eligible work for + another invocation. File/fragment counts are None if an older worker did + not report them; they are never inferred from unrelated table versions. + File counts include deletion files as well as data files. + """ + + partial_commit: bool + rows_succeeded: int + rows_failed: int + completion_percentage: float + more_work: bool = False + files_added: Optional[int] = None + files_removed: Optional[int] = None + fragments_added: Optional[int] = None + fragments_removed: Optional[int] = None + + @classmethod + def from_json(cls, raw: str) -> "CompactionResult": + """Decode a server result, ignoring additive fields from newer servers.""" + value = json.loads(raw) + names = {field.name for field in fields(cls)} + return cls(**{key: item for key, item in value.items() if key in names}) diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index dab6d5903..9191bf497 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -21,6 +21,8 @@ from lancedb.background_loop import LOOP from . import _lancedb from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url from .functions import RefreshColumnResult +from .compaction import CompactionResult +from .prewarm import PrewarmDataResult from .remote.errors import HttpError, RetryError T = TypeVar("T") @@ -148,6 +150,19 @@ def _job_progress_callback(progress, enrich): planned = snapshot.get("rows_planned") remaining = snapshot.get("rows_remaining") computed = snapshot.get("rows_computed") + job_type = snapshot.get("job_type") + maintenance = job_type in ("compact", "prewarm_page_cache") + if job_type == "compact": + computed = snapshot.get("rows_rewritten") + remaining = None + if hasattr(progress, "unit"): + progress.unit = " rows" + elif job_type == "prewarm_page_cache": + planned = snapshot.get("executors_targeted") + computed = snapshot.get("executors_completed") + remaining = None + if hasattr(progress, "unit"): + progress.unit = " executors" if isinstance(planned, int): epoch = snapshot.get("execution_epoch") reset = (isinstance(last_planned, int) and planned < last_planned) or ( @@ -173,7 +188,7 @@ def _job_progress_callback(progress, enrich): if completed is not None: if isinstance(planned, int): completed = min(completed, planned) - if first_snapshot and completed < last_rows: + if (first_snapshot or maintenance) and completed < last_rows: # The server may have started a new execution while a # caller-owned bar retained its old position. last_rows = completed @@ -287,6 +302,10 @@ class AsyncJob(Generic[T]): a caller-owned bar with the server's current completed rows and total; later observations in a stable execution epoch use a high-water mark. A new execution epoch or smaller plan resets the bar to that plan. + Maintenance jobs display reported rewritten rows or completed executors; + revised maintenance counters replace earlier retry observations. Totals + remain unknown until the server reports them. Rewritten rows describe + execution work, not committed compaction results. ``False`` preserves the original wait behavior. For SQL-backed Function registration, progress shows the query's @@ -841,4 +860,8 @@ def _typed_job( def _opened_job(inner: "_lancedb.Job") -> AsyncJob: if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"): return _typed_job(inner, RefreshColumnResult.from_json) + if inner.job_type == "prewarm_page_cache": + return _typed_job(inner, PrewarmDataResult.from_json) + if inner.job_type == "compact": + return _typed_job(inner, CompactionResult.from_json) return AsyncJob(inner) diff --git a/python/python/lancedb/prewarm.py b/python/python/lancedb/prewarm.py new file mode 100644 index 000000000..c21bd6cfd --- /dev/null +++ b/python/python/lancedb/prewarm.py @@ -0,0 +1,32 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Results of remote data-cache prewarm jobs.""" + +from dataclasses import dataclass, fields +import json +from typing import Optional + + +@dataclass(frozen=True) +class PrewarmDataResult: + """Reported executor work for a pinned snapshot, not guaranteed cache residency. + + Counts omitted by older workers remain None. I/O counts are unknown when + executors do not report them. Partial completions are a subset of completed + executors and may reflect cache pressure. + """ + + table_version: int + executors_targeted: Optional[int] = None + executors_completed: Optional[int] = None + executors_partial: Optional[int] = None + fragments_selected: Optional[int] = None + ranges_completed: Optional[int] = None + bytes_read: Optional[int] = None + + @classmethod + def from_json(cls, raw: str) -> "PrewarmDataResult": + value = json.loads(raw) + names = {field.name for field in fields(cls)} + return cls(**{key: item for key, item in value.items() if key in names}) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 19e7ff454..ac936ebd9 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -48,6 +48,7 @@ from lancedb.index import ( Bitmap, LabelList, ) +from lancedb.prewarm import PrewarmDataResult from lancedb.job import Job from lancedb.functions import ( FunctionProvenance, @@ -78,6 +79,7 @@ from ..table import ( BlobMode, Branches, CompactionOptions, + CompactionResult, IndexStatistics, Query, Table, @@ -1105,6 +1107,13 @@ class RemoteTable(Table): ) pass + def compact_async( + self, *, compaction_options: Optional[CompactionOptions] = None + ) -> Job[CompactionResult]: + return Job( + LOOP.run(self._table.compact_async(compaction_options=compaction_options)) + ) + def optimize( self, *, @@ -1433,7 +1442,13 @@ class RemoteTable(Table): """ return LOOP.run(self._table.prewarm_index(name)) - def prewarm_data(self, columns: Optional[List[str]] = None) -> None: + def prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> None: """Prewarm data for the table. This is a hint to the database that the given columns will be accessed @@ -1441,7 +1456,8 @@ class RemoteTable(Table): Currently only supported in LanceDB Enterprise. This call initiates prewarming and returns once the request is accepted. - It is idempotent and safe to call from multiple clients concurrently. + Uses SQL PREWARM and requires Flight SQL connectivity. To track the + durable warming job, use ``prewarm_data_async()``. This operation has a large upfront cost but can speed up future queries that need to fetch the given columns. Large columns such as embeddings @@ -1452,8 +1468,34 @@ class RemoteTable(Table): ---------- columns: list of str, optional The columns to prewarm. If None, all columns are prewarmed. + filter: str, optional + A single SQL predicate for conservative metadata pruning. + concurrency: int, optional + Positive per-executor warming concurrency; omitted uses the server default. + + Examples + -------- + >>> table.prewarm_data( # doctest: +SKIP + ... ["payload"], filter="quality > 0.7", concurrency=4) """ - return LOOP.run(self._table.prewarm_data(columns)) + return LOOP.run( + self._table.prewarm_data(columns, filter=filter, concurrency=concurrency) + ) + + def prewarm_data_async( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> Job[PrewarmDataResult]: + return Job( + LOOP.run( + self._table.prewarm_data_async( + columns, filter=filter, concurrency=concurrency + ) + ) + ) def wait_for_index( self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 8d996d32e..8c3d30170 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -48,7 +48,9 @@ from ._blob import ( from .types import BlobMode from lancedb.arrow import peek_reader from lancedb.background_loop import LOOP, embedding_executor +from lancedb.prewarm import PrewarmDataResult from lancedb.job import AsyncJob, Job, _typed_job +from lancedb.compaction import CompactionResult from .dependencies import ( _check_for_hugging_face, _check_for_lance, @@ -2011,6 +2013,69 @@ class Table(ABC): """ raise NotImplementedError("create_index is not supported for this table type") + def prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> None: + """Submit remote data prewarm and return after acceptance. + + Omitted or empty ``columns`` warm all fields. ``filter`` is a single + SQL predicate for conservative metadata pruning; ``concurrency`` is + a positive per-executor integer, or omitted for the server default. + The table handle supplies the namespace and branch. Requires a + compatible SQL PREWARM server and Flight SQL connectivity. + + The operation continues in the background. Use + [prewarm_data_async][lancedb.table.Table.prewarm_data_async] to retain + the job handle and wait for completion. + + Examples + -------- + >>> table.prewarm_data( # doctest: +SKIP + ... ["payload"], filter="quality > 0.7", concurrency=4) + """ + self.prewarm_data_async(columns, filter=filter, concurrency=concurrency) + + def prewarm_data_async( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> Job[PrewarmDataResult]: + """Submit a remote data-cache prewarm and return its durable job. + + Requires a compatible SQL PREWARM server and Flight SQL connectivity. + The table handle supplies the branch and namespace. ``columns`` uses + Lance field paths; an omitted/empty list warms all columns. ``filter`` + is one SQL predicate for conservative metadata pruning, not a row scan. + ``concurrency`` is a positive per-executor integer. Historical-version + handles are unsupported; call ``checkout_latest()`` first. + + Submission requires table Select and database/namespace Usage under + Standard authorization. Status/wait use the generic HTTP job API; + events and cancellation have their own privileges. Unsupported servers + are not retried through REST or with settings removed. + + Returns once accepted. ``job.wait()`` waits for warming to finish and + returns [PrewarmDataResult][lancedb.prewarm.PrewarmDataResult]. + Save ``job.id`` to resume with ``db.open_job(id)``. A wait timeout does + not cancel the operation. After ``job.refresh()``, + ``job.spec["table_version"]`` identifies the pinned source version. + + Examples + -------- + >>> job = table.prewarm_data_async( # doctest: +SKIP + ... ["video"], filter="quality > 0.7", concurrency=4) + >>> job.wait() # doctest: +SKIP + """ + raise NotImplementedError( + "data prewarm jobs are only supported on remote tables" + ) + def create_index_async( self, column: str, @@ -3024,6 +3089,33 @@ class Table(ABC): compaction for you automatically. """ + def compact_async( + self, *, compaction_options: Optional[CompactionOptions] = None + ) -> Job[CompactionResult]: + """Submit remote compaction and return a durable job after acceptance. + + Uses SQL OPTIMIZE with the table handle's branch and namespace. Supports + the four per-job settings in + [CompactionOptions][lancedb.table.CompactionOptions]. + Requires a compatible remote server, table Ownership and parent Usage. + Local and historical-version handles are unsupported. Existing + ``optimize()`` retains its return-on-submission behavior remotely. + + ``job.wait()`` waits for the actual rewrite and returns + [CompactionResult][lancedb.compaction.CompactionResult]. Partial/bounded + runs report uncommitted rows and ``more_work``; unknown file statistics + are None. Servers without a result payload raise an error rather than + returning fabricated zero statistics. Wait timeouts do not cancel work. + Save ``job.id`` and reopen with ``db.open_job(id)``. Monitoring and + cancellation use generic HTTP job APIs and their existing permissions. + + >>> job = table.compact_async( # doctest: +SKIP + ... compaction_options={"target_rows_per_fragment": 1000}) + >>> result = job.wait() # doctest: +SKIP + >>> print(result.rows_succeeded) # doctest: +SKIP + """ + raise NotImplementedError("compaction jobs are only supported on remote tables") + @abstractmethod def optimize( self, @@ -4843,7 +4935,13 @@ class LanceTable(Table): """ return LOOP.run(self._table.prewarm_index(name)) - def prewarm_data(self, columns: Optional[List[str]] = None) -> None: + def prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> None: """ Prewarm data for the table. @@ -4852,7 +4950,8 @@ class LanceTable(Table): Currently only supported in LanceDB Enterprise. This call initiates prewarming and returns once the request is accepted. - It is idempotent and safe to call from multiple clients concurrently. + Uses SQL PREWARM and requires Flight SQL connectivity. To track the + durable warming job, use ``prewarm_data_async()``. This operation has a large upfront cost but can speed up future queries that need to fetch the given columns. Large columns such as embeddings @@ -4863,8 +4962,34 @@ class LanceTable(Table): ---------- columns: list of str, optional The columns to prewarm. If None, all columns are prewarmed. + filter: str, optional + A single SQL predicate for conservative metadata pruning. + concurrency: int, optional + Positive per-executor warming concurrency; omitted uses the server default. + + Examples + -------- + >>> table.prewarm_data( # doctest: +SKIP + ... ["payload"], filter="quality > 0.7", concurrency=4) """ - return LOOP.run(self._table.prewarm_data(columns)) + return LOOP.run( + self._table.prewarm_data(columns, filter=filter, concurrency=concurrency) + ) + + def prewarm_data_async( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> Job[PrewarmDataResult]: + return Job( + LOOP.run( + self._table.prewarm_data_async( + columns, filter=filter, concurrency=concurrency + ) + ) + ) def wait_for_index( self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300) @@ -5683,6 +5808,13 @@ class LanceTable(Table): self.checkout_latest() return stats + def compact_async( + self, *, compaction_options: Optional[CompactionOptions] = None + ) -> Job[CompactionResult]: + return Job( + LOOP.run(self._table.compact_async(compaction_options=compaction_options)) + ) + def optimize( self, *, @@ -7324,7 +7456,13 @@ class AsyncTable: """ await self._inner.prewarm_index(name) - async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: + async def prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> None: """ Prewarm data for the table. @@ -7333,7 +7471,8 @@ class AsyncTable: Currently only supported in LanceDB Enterprise. This call initiates prewarming and returns once the request is accepted. - It is idempotent and safe to call from multiple clients concurrently. + Uses SQL PREWARM and requires Flight SQL connectivity. To track the + durable warming job, use ``prewarm_data_async()``. This operation has a large upfront cost but can speed up future queries that need to fetch the given columns. Large columns such as embeddings @@ -7344,8 +7483,43 @@ class AsyncTable: ---------- columns: list of str, optional The columns to prewarm. If None, all columns are prewarmed. + filter: str, optional + A single SQL predicate for conservative metadata pruning. + concurrency: int, optional + Positive per-executor warming concurrency; omitted uses the server default. + + Examples + -------- + >>> await table.prewarm_data( # doctest: +SKIP + ... ["payload"], filter="quality > 0.7", concurrency=4) """ - await self._inner.prewarm_data(columns) + await self.prewarm_data_async(columns, filter=filter, concurrency=concurrency) + + async def prewarm_data_async( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> AsyncJob[PrewarmDataResult]: + """Submit data prewarm and return a durable handle after acceptance. + + See [Table.prewarm_data_async][lancedb.table.Table.prewarm_data_async] + for options, permissions, and compatibility. Awaiting this method does + not wait for warming; use ``await job.wait()`` for completion. + + Examples + -------- + >>> job = await table.prewarm_data_async( # doctest: +SKIP + ... ["video"], filter="quality > 0.7", concurrency=4) + >>> await job.wait() # doctest: +SKIP + """ + return _typed_job( + await self._inner.prewarm_data_async( + columns, filter=filter, concurrency=concurrency + ), + PrewarmDataResult.from_json, + ) async def wait_for_index( self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300) @@ -9273,6 +9447,19 @@ class AsyncTable: """The branch this table handle is scoped to, or ``None`` for ``main``.""" return self._inner.current_branch() + async def compact_async( + self, *, compaction_options: Optional[CompactionOptions] = None + ) -> AsyncJob[CompactionResult]: + """Submit remote compaction; await the returned job for actual results. + + See [Table.compact_async][lancedb.table.Table.compact_async] for options, + permissions, completion semantics and compatibility requirements. + """ + return _typed_job( + await self._inner.compact_async(compaction_options), + CompactionResult.from_json, + ) + async def optimize( self, *, diff --git a/python/python/tests/test_e2e_remote_db.py b/python/python/tests/test_e2e_remote_db.py index 8b06943da..f09581bff 100644 --- a/python/python/tests/test_e2e_remote_db.py +++ b/python/python/tests/test_e2e_remote_db.py @@ -11,11 +11,139 @@ import numpy as np import pyarrow as pa import pytest from lancedb import LanceDBConnection, function +from lancedb.compaction import CompactionResult from lancedb.index import FTS +from lancedb.prewarm import PrewarmDataResult # TODO: setup integ test mark and script +@pytest.fixture +def maintenance_connection_options(): + uri = os.environ.get("LANCEDB_URI") + if not uri: + pytest.skip( + "Set LANCEDB_URI to a server supporting SQL maintenance job results" + ) + assert uri.startswith("db://") + return { + "uri": uri, + "api_key": os.environ.get("LANCEDB_API_KEY"), + "region": os.environ.get("LANCEDB_REGION", "us-east-1"), + "host_override": os.environ.get("LANCEDB_HOST_OVERRIDE"), + "sql_host_override": os.environ.get("LANCEDB_SQL_HOST_OVERRIDE"), + } + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("operation", ["compact", "prewarm", "prewarm_legacy"]) +async def test_maintenance_job_result_and_reopen_against_server( + maintenance_connection_options, asynchronous, operation +): + """Exercise real SQL receipts, workers and HTTP job results with matching versions. + + Configure LANCEDB_URI, LANCEDB_API_KEY and the REST/Flight SQL endpoint + overrides for a writable database. Workers must publish maintenance results; + an unsupported server fails the contract rather than silently skipping it. + """ + if asynchronous: + connection = await lancedb.connect_async(**maintenance_connection_options) + else: + connection = lancedb.connect(**maintenance_connection_options) + + async def call(method, *args, **kwargs): + result = method(*args, **kwargs) + return await result if asynchronous else result + + name = f"maintenance_{uuid4().hex}" + created = False + expected = [{"id": i, "payload": i * 10} for i in range(16)] + timeout = timedelta(minutes=5) + try: + table = await call( + connection.create_table, name, pa.Table.from_pylist(expected[:4]) + ) + created = True + for start in (4, 8, 12): + await call(table.add, pa.Table.from_pylist(expected[start : start + 4])) + version = await table.version() if asynchronous else table.version + if operation == "compact": + job = await call( + table.compact_async, + compaction_options={ + "target_rows_per_fragment": 100, + "batch_size": 128, + "io_buffer_size": 0, + }, + ) + elif operation == "prewarm_legacy": + assert ( + await call( + table.prewarm_data, + ["payload"], + filter="id >= 8", + concurrency=2, + ) + is None + ) + reader = await call( + connection.execute_query, f'SHOW JOBS FOR TABLE "{name}"' + ) + batches = await call(reader.read_all) + jobs = pa.Table.from_batches(batches) if asynchronous else batches + ids = [ + row["job_id"] + for row in jobs.to_pylist() + if row["job_type"] == "prewarm_page_cache" + ] + assert len(ids) == 1, jobs.to_pylist() + job = await call(connection.open_job, ids[0]) + else: + job = await call( + table.prewarm_data_async, + ["payload"], + filter="id >= 8", + concurrency=2, + ) + assert job.id + progress = [] + result = await call(job.wait, timeout=timeout, progress=progress.append) + assert any(snapshot["state"] == "finished" for snapshot in progress) + await call(job.refresh) + assert await call(job.status) == "finished" + if operation == "compact": + assert isinstance(result, CompactionResult) + assert job.job_type == "compact" + assert not result.partial_commit and result.rows_failed == 0 + assert result.completion_percentage == 100 + assert 0 <= result.rows_succeeded <= len(expected) + assert result.files_added is not None and result.files_removed is not None + else: + assert isinstance(result, PrewarmDataResult) + assert job.job_type == "prewarm_page_cache" + assert result.table_version == version == job.spec["table_version"] + assert job.spec["columns"] == ["payload"] + assert job.spec["concurrency"] == 2 + assert result.fragments_selected > 0 + assert result.executors_completed == result.executors_targeted + assert result.executors_partial == 0 + assert result.bytes_read is None and result.ranges_completed is None + reopened = await call(connection.open_job, job.id) + assert await call(reopened.wait, timeout=timeout) == result + query = table.query() if asynchronous else table.search() + actual = await call( + query.select(["id", "payload"]).limit(len(expected) + 1).to_arrow + ) + assert sorted(actual.to_pylist(), key=lambda row: row["id"]) == expected + finally: + try: + if created: + await call(connection.drop_table, name) + finally: + connection.close() + + @pytest.mark.skipif( not os.environ.get("LANCEDB_URI"), reason="Set LANCEDB_URI to a JSON FTS server" ) diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index 59e2fc3a8..809105102 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -1072,3 +1072,95 @@ async def test_stack_propagates_errors_and_rejects_local_handles(sync): Job(None).stack("worker") else: await AsyncJob(None).stack("worker") + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "kind,planned_key,completed_key,unit", + [ + ("compact", "rows_planned", "rows_rewritten", " rows"), + ( + "prewarm_page_cache", + "executors_targeted", + "executors_completed", + " executors", + ), + ], +) +async def test_maintenance_progress_bar_uses_operation_counters_and_handles_retry( + monkeypatch, kind, planned_key, completed_key, unit +): + tqdm_module = pytest.importorskip("tqdm.auto") + + class Bar: + total = None + n = 0 + unit = " rows" + closed = False + + def update(self, delta): + self.n += delta + + def close(self): + self.closed = True + + bar = Bar() + monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar) + + class MaintenanceJob: + id = "maintenance-job" + job_type = kind + + async def wait(self, progress): + progress({"job_type": kind, "phase": "planning"}) + assert bar.total is None + progress({"job_type": kind, planned_key: 4, completed_key: 2}) + assert bar.n == 2 + # Older responses can omit an epoch; revised observations still + # replace the previous attempt's displayed work. + progress({"job_type": kind, planned_key: 4, completed_key: 1}) + assert bar.n == 1 + progress({"job_type": kind, planned_key: 4, completed_key: 4}) + + assert await AsyncJob(MaintenanceJob()).wait(progress=True) is None + assert bar.n == 4 + assert bar.total == 4 + assert bar.unit == unit + assert bar.closed + + +@pytest.mark.asyncio +@pytest.mark.parametrize("known_empty", [False, True]) +async def test_prewarm_progress_bar_preserves_unknown_and_zero_totals( + monkeypatch, known_empty +): + tqdm_module = pytest.importorskip("tqdm.auto") + + class Bar: + total = None + n = 0 + unit = " rows" + + def update(self, delta): + self.n += delta + + def close(self): + pass + + bar = Bar() + monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar) + + class PrewarmJob: + id = "prewarm-job" + job_type = "prewarm_page_cache" + + async def wait(self, progress): + snapshot = {"job_type": self.job_type, "phase": "succeeded"} + if known_empty: + snapshot.update(executors_targeted=0, executors_completed=0) + progress(snapshot) + + assert await AsyncJob(PrewarmJob()).wait(progress=True) is None + assert bar.n == 0 + assert bar.total == (0 if known_empty else None) + assert bar.unit == " executors" diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 2cacc4716..eff207230 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -7408,10 +7408,10 @@ def _create_table_handler(request): @contextlib.contextmanager -def _mock_remote_sql_connection(flight_server): +def _mock_remote_sql_connection(flight_server, handler=_create_table_handler): """Connection arguments for mock REST and Flight SQL servers.""" with http.server.ThreadingHTTPServer( - ("127.0.0.1", 0), make_mock_http_handler(_create_table_handler) + ("127.0.0.1", 0), make_mock_http_handler(handler) ) as rest_server: rest_port = rest_server.server_address[1] handle = start_server_thread(rest_server) @@ -8054,3 +8054,373 @@ def test_exact_function_retries_fail_before_writing_to_older_servers(): with pytest.raises(NotImplementedError, match="server does not support"): table.function_errors().summary() assert writes == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("mode", ["job", "columns", "filtered", "defaults"]) +async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mode): + flight = pytest.importorskip("pyarrow.flight") + polls = [] + + class PrewarmServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream( + pa.table( + { + "job_id": ["warming-job"], + "table_version": pa.array([42], pa.uint64()), + } + ) + ) + + def handler(request): + if request.path == "/v1/jobs/describe": + body = json.loads( + request.rfile.read(int(request.headers["Content-Length"])) + ) + assert body == {"job_id": "warming-job"} + polls.append(body) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "warming-job", + "job_type": "prewarm_page_cache", + "job_state": "DONE", + "creation_ms": 1, + "spec": {"table_version": 42}, + "result": { + "table_version": 42, + "executors_targeted": 2, + "executors_completed": 2, + "fragments_selected": 4, + }, + "operation_progress": { + "phase": "reading", + "executors_completed": 2, + "fragments_selected": 4, + }, + } + ).encode() + ) + else: + # No operation-specific REST prewarm endpoint is accepted. + _create_table_handler(request) + + server = PrewarmServer() + with _mock_remote_sql_connection(server, handler) as kwargs: + if asynchronous: + db = await lancedb.connect_async(**kwargs) + table = await db.create_table("test", [{"id": 1}]) + if mode == "columns": + assert await table.prewarm_data(["payload"]) is None + elif mode == "filtered": + assert ( + await table.prewarm_data( + columns=["attrs.score"], filter="id >= 8", concurrency=4 + ) + is None + ) + elif mode == "defaults": + assert await table.prewarm_data() is None + else: + job = await table.prewarm_data_async( + ["attrs.score"], filter="id >= 8", concurrency=4 + ) + assert job.id == "warming-job" + assert not polls + assert (await job.wait()).table_version == 42 + await job.refresh() + assert job.spec["table_version"] == 42 + reopened = await db.open_job(job.id) + assert (await reopened.wait()).executors_completed == 2 + assert (await job.progress())["executors_completed"] == 2 + assert (await job.wait()).bytes_read is None + else: + db = lancedb.connect(**kwargs) + table = db.create_table("test", [{"id": 1}]) + if mode == "columns": + assert table.prewarm_data(["payload"]) is None + elif mode == "filtered": + assert ( + table.prewarm_data( + columns=["attrs.score"], filter="id >= 8", concurrency=4 + ) + is None + ) + elif mode == "defaults": + assert table.prewarm_data() is None + else: + job = table.prewarm_data_async( + ["attrs.score"], filter="id >= 8", concurrency=4 + ) + assert job.id == "warming-job" + assert not polls + assert job.wait().table_version == 42 + job.refresh() + assert job.spec["table_version"] == 42 + assert db.open_job(job.id).wait().executors_completed == 2 + assert job.progress()["executors_completed"] == 2 + assert job.wait().bytes_read is None + assert len(server.tickets) == 1 + assert b"PREWARM" in server.tickets[0] + if mode != "job": + assert not polls + if mode == "columns": + assert b'"payload"' in server.tickets[0] + elif mode == "defaults": + assert b"SELECT *" in server.tickets[0] + else: + assert b'"attrs"."score"' in server.tickets[0] + assert b"concurrency = 4" in server.tickets[0] + assert b"id >= 8" in server.tickets[0] + + +@pytest.mark.parametrize( + "options", + [ + {"filter": ""}, + {"filter": "id > 0; DROP TABLE test"}, + {"filter": "id > 0 LIMIT 1"}, + {"concurrency": 0}, + {"concurrency": -1}, + {"concurrency": 2**32}, + {"concurrency": True}, + {"concurrency": 1.5}, + ], +) +@pytest.mark.parametrize("method", ["prewarm_data", "prewarm_data_async"]) +def test_remote_data_prewarm_validates_before_submission(options, method): + flight = pytest.importorskip("pyarrow.flight") + + class UnusedServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + raise AssertionError("invalid options must not submit SQL") + + server = UnusedServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(ValueError): + getattr(table, method)(**options) + assert not server.tickets + + +def test_remote_data_prewarm_malformed_receipt_is_not_retried(): + flight = pytest.importorskip("pyarrow.flight") + + class MalformedServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream(pa.table({"job_id": ["warming-job"]})) + + server = MalformedServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(Exception, match="inspect jobs before retrying"): + table.prewarm_data_async() + assert len(server.tickets) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "outcome", + [ + "counts", + "legacy", + "partial", + "bounded", + "no_op", + "missing", + "FAILED", + "CANCELLED", + ], +) +async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome): + flight = pytest.importorskip("pyarrow.flight") + polls = [] + result = { + "partial_commit": False, + "rows_succeeded": 12, + "rows_failed": 0, + "completion_percentage": 100.0, + } + if outcome == "counts": + result.update( + files_added=1, files_removed=3, fragments_added=1, fragments_removed=3 + ) + + if outcome == "partial": + result.update( + partial_commit=True, + rows_succeeded=8, + rows_failed=4, + completion_percentage=100 * 8 / 12, + ) + if outcome == "bounded": + result.update(more_work=True) + if outcome == "no_op": + result.update( + rows_succeeded=0, + files_added=0, + files_removed=0, + fragments_added=0, + fragments_removed=0, + ) + + class Server(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream(pa.table({"job_id": ["compacting-job"]})) + + def handler(request): + if request.path != "/v1/jobs/describe": + return _create_table_handler(request) + body = json.loads(request.rfile.read(int(request.headers["Content-Length"]))) + assert body == {"job_id": "compacting-job"} + polls.append(body) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "compacting-job", + "job_type": "compact", + "job_state": outcome + if outcome in ("FAILED", "CANCELLED") + else "DONE", + "result": None if outcome == "missing" else result, + } + ).encode() + ) + + server = Server() + with _mock_remote_sql_connection(server, handler) as kwargs: + if asynchronous: + db = await lancedb.connect_async(**kwargs) + table = await db.create_table("test", [{"id": 1}]) + job = await table.compact_async( + compaction_options={"target_rows_per_fragment": 100} + ) + assert job.id == "compacting-job" and not polls + if outcome in ("missing", "FAILED", "CANCELLED"): + with pytest.raises( + Exception, + match={ + "missing": "did not contain a result", + "FAILED": "failed", + "CANCELLED": "cancel", + }[outcome], + ): + await job.wait() + else: + stats = await job.wait() + reopened = await db.open_job(job.id) + assert await reopened.wait() == stats + else: + db = lancedb.connect(**kwargs) + table = db.create_table("test", [{"id": 1}]) + job = table.compact_async( + compaction_options={"target_rows_per_fragment": 100} + ) + assert job.id == "compacting-job" and not polls + if outcome in ("missing", "FAILED", "CANCELLED"): + with pytest.raises( + Exception, + match={ + "missing": "did not contain a result", + "FAILED": "failed", + "CANCELLED": "cancel", + }[outcome], + ): + job.wait() + else: + stats = job.wait() + assert db.open_job(job.id).wait() == stats + if outcome in ("counts", "legacy", "partial", "bounded", "no_op"): + from lancedb.compaction import CompactionResult + + assert isinstance(stats, CompactionResult) + assert stats.rows_succeeded == ( + 0 if outcome == "no_op" else 8 if outcome == "partial" else 12 + ) + assert stats.rows_failed == (4 if outcome == "partial" else 0) + assert stats.partial_commit == (outcome == "partial") + assert stats.more_work == (outcome == "bounded") + assert stats.fragments_removed == ( + 3 if outcome == "counts" else 0 if outcome == "no_op" else None + ) + assert len(server.tickets) == 1 + assert b"OPTIMIZE" in server.tickets[0] + assert b"target_rows_per_fragment = 100" in server.tickets[0] + + +@pytest.mark.parametrize("ids", [[], [None], [""], ["a", "b"]]) +def test_remote_compaction_rejects_ambiguous_receipt_without_resubmission(ids): + flight = pytest.importorskip("pyarrow.flight") + + class Server(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.calls = 0 + + def do_get(self, context, ticket): + self.calls += 1 + return flight.RecordBatchStream( + pa.table({"job_id": pa.array(ids, pa.string())}) + ) + + server = Server() + with _mock_remote_sql_connection(server) as kwargs: + db = lancedb.connect(**kwargs) + table = db.create_table("test", [{"id": 1}]) + with pytest.raises(Exception, match="inspect jobs before retrying"): + table.compact_async() + assert server.calls == 1 + + +@pytest.mark.parametrize("method", ["compact_async", "optimize"]) +@pytest.mark.parametrize( + "option", + ["target_rows_per_fragment", "max_source_rows", "io_buffer_size", "batch_size"], +) +@pytest.mark.parametrize("value", [False, True]) +def test_remote_compaction_rejects_boolean_budgets_without_submitting( + method, option, value +): + flight = pytest.importorskip("pyarrow.flight") + + class UnusedServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.calls = 0 + + def do_get(self, context, ticket): + self.calls += 1 + raise AssertionError("boolean compaction settings must not submit SQL") + + server = UnusedServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(ValueError, match="must be an integer, not a bool"): + getattr(table, method)(compaction_options={option: value}) + assert server.calls == 0 diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 4b26a9003..ebc3c3006 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -6414,3 +6414,22 @@ def test_fts_exist_ok_matches_quoted_default_name(mem_db): table.create_index("`body-text`", config=FTS(), exist_ok=True) assert table.version == before assert len(table.list_indices()) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("method", ["prewarm_data", "prewarm_data_async"]) +async def test_data_prewarm_job_is_unsupported_locally(tmp_path, asynchronous, method): + if asynchronous: + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("prewarm", [{"id": 1}]) + with pytest.raises( + NotImplementedError, match="only supported on remote tables" + ): + await getattr(table, method)(filter="id > 0", concurrency=2) + else: + table = lancedb.connect(tmp_path).create_table("prewarm", [{"id": 1}]) + with pytest.raises( + NotImplementedError, match="only supported on remote tables" + ): + getattr(table, method)(filter="id > 0", concurrency=2) diff --git a/python/src/connection.rs b/python/src/connection.rs index 2d65a0459..ce41589cc 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -902,6 +902,14 @@ impl Connection { job.into_typed::().infer_error()?, )) } + Some("prewarm_page_cache") => Ok(crate::job::Job::new_typed( + job.into_typed::() + .infer_error()?, + )), + Some("compact") => Ok(crate::job::Job::new_typed( + job.into_typed::() + .infer_error()?, + )), _ => Ok(crate::job::Job::new(job)), } }) diff --git a/python/src/table.rs b/python/src/table.rs index 3bc23ec95..e421c939d 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -495,6 +495,16 @@ fn parse_compaction_options(options: Option<&Bound<'_, PyDict>>) -> PyResult() + { + return Err(PyValueError::new_err(format!( + "{key} must be an integer, not a bool" + ))); + } match key.as_str() { "target_rows_per_fragment" => { parsed.target_rows_per_fragment = positive_u32(&value, &key)? @@ -1885,6 +1895,24 @@ impl Table { }) } + #[pyo3(signature = (columns=None, *, filter=None, concurrency=None))] + pub fn prewarm_data_async<'py>( + self_: PyRef<'py, Self>, + columns: Option>, + filter: Option, + concurrency: Option<&Bound<'py, PyAny>>, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let mut options = + lancedb::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()); + options.filter = filter; + options.concurrency = positive_u32_integer(concurrency, "concurrency")?; + future_into_py(self_.py(), async move { + let job = inner.prewarm_data_async(options).await.infer_error()?; + Ok(crate::job::Job::new_typed(job)) + }) + } + pub fn list_indices(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -2245,6 +2273,29 @@ impl Table { }) } + /// Submit remote compaction and retain its durable job and actual result. + #[pyo3(signature = (compaction_options=None))] + pub fn compact_async<'py>( + self_: PyRef<'py, Self>, + compaction_options: Option<&Bound<'py, PyDict>>, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let target_specified = compaction_options + .map(|options| options.contains("target_rows_per_fragment")) + .transpose()? + .unwrap_or(false); + let options = parse_compaction_options(compaction_options)?; + let mut overrides = + lancedb::table::optimize::CompactionOverrides::try_from(options).infer_error()?; + if !target_specified { + overrides.target_rows_per_fragment = None; + } + future_into_py(self_.py(), async move { + let job = inner.compact_async(overrides).await.infer_error()?; + Ok(crate::job::Job::new_typed(job)) + }) + } + /// Optimize the on-disk data by compacting and pruning old data, for better performance. #[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None, compaction_options=None))] pub fn optimize<'py>( diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 39fee38d6..14170d43c 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -6,6 +6,7 @@ use std::future::Future; use std::pin::Pin; use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard}; +use std::time::Duration; use arrow_array::RecordBatch; use async_trait::async_trait; @@ -24,6 +25,48 @@ use crate::error::{Error, JobFailure, Result}; /// retry loop just to render progress. pub type JobProgressCallback = Arc>; +/// Client-side controls for waiting on a job. A timeout stops this wait without +/// cancelling the operation; keep the handle to wait again. +#[derive(Clone, Default)] +#[non_exhaustive] +pub struct JobWaitOptions { + /// Maximum time to wait, including HTTP requests and polling backoff. + /// `None` waits indefinitely. Zero only permits an immediately ready result. + pub timeout: Option, + progress: Option, +} + +impl std::fmt::Debug for JobWaitOptions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("JobWaitOptions") + .field("timeout", &self.timeout) + .field("progress", &self.progress.is_some()) + .finish() + } +} + +impl JobWaitOptions { + /// Wait indefinitely without a progress callback. + pub fn new() -> Self { + Self::default() + } + + /// Bound this wait without cancelling the underlying job. + pub fn timeout(mut self, timeout: Duration) -> Self { + self.timeout = Some(timeout); + self + } + + /// Observe the backend's existing poller. The callback should return promptly. + pub fn progress(mut self, progress: F) -> Self + where + F: FnMut(&JobDescription) + Send + 'static, + { + self.progress = Some(Arc::new(Mutex::new(progress))); + self + } +} + /// Which of a job's events [`Job::events`] returns. /// /// The handle already knows which job to ask about, so this narrows the @@ -598,7 +641,7 @@ where /// Returns [`crate::Error::JobFailed`] if the operation failed and /// [`crate::Error::JobCancelled`] if it was cancelled. pub async fn wait(&self) -> Result { - self.wait_with_progress_opt(None).await + self.wait_with_options(JobWaitOptions::default()).await } /// Wait for the operation while observing progress from the backend's @@ -609,10 +652,58 @@ where where F: FnMut(&JobDescription) + Send + 'static, { - self.wait_with_progress_opt(Some(Arc::new(Mutex::new(progress)))) + self.wait_with_options(JobWaitOptions::new().progress(progress)) .await } + /// Wait with a client-side deadline and an optional progress callback. + /// + /// Returns [`Error::Timeout`] when the deadline expires, including while a + /// status request or polling backoff is pending. This drops the wait future; + /// it does not cancel the operation or mark it failed. The same handle can + /// wait again. Registry jobs can also be reopened by ID; query IDs remain + /// connection-scoped and cannot be reopened as registry jobs. + /// + /// ```no_run + /// # async fn example(job: &lancedb::Job) -> lancedb::Result<()> { + /// use std::time::Duration; + /// use lancedb::job::JobWaitOptions; + /// job.wait_with_options(JobWaitOptions::new() + /// .timeout(Duration::from_secs(60)) + /// .progress(|description| println!("{}", description.state))) + /// .await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn wait_with_options(&self, options: JobWaitOptions) -> Result { + let Some(timeout) = options.timeout else { + return self.wait_with_progress_opt(options.progress).await; + }; + let deadline = tokio::time::Instant::now() + .checked_add(timeout) + .ok_or_else(|| Error::InvalidInput { + message: "job wait timeout is too large".to_string(), + })?; + tokio::time::timeout_at(deadline, self.wait_with_progress_opt(options.progress)) + .await + .map_err(|_| { + let operation = self + .id() + .map(|id| format!("job {id:?}")) + .unwrap_or_else(|| "operation".to_string()); + let resume = if self.id().is_some() && self.job_type().as_deref() != Some("query") { + "continue waiting on this handle or reattach with Connection::open_job" + } else { + "keep this handle to continue waiting" + }; + Error::Timeout { + message: format!( + "{operation} still running after {timeout:?}; the operation continues; {resume}" + ), + } + })? + } + async fn wait_with_progress_opt(&self, progress: Option) -> Result { match &self.inner { JobInner::Handle { handle, decode } => { @@ -838,6 +929,92 @@ mod tests { use super::*; + #[tokio::test(start_paused = true)] + async fn wait_timeout_preserves_local_task_and_typed_result() { + let job = Job::spawned(tokio::spawn(async { + tokio::time::sleep(Duration::from_secs(1)).await; + Ok(41_u64) + })) + .map(|value| value + 1); + let error = job + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(10))) + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout { .. })); + assert!(error.to_string().contains("keep this handle")); + assert!(!error.to_string().contains("Connection::open_job")); + assert_eq!(job.state(), None); + assert_eq!(job.status().await.unwrap(), "running"); + assert_eq!( + job.wait_with_options(JobWaitOptions::new()).await.unwrap(), + 42 + ); + } + + #[tokio::test(start_paused = true)] + async fn wait_timeout_keeps_query_handle_without_requesting_cancellation() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let cancellations = Arc::new(AtomicUsize::new(0)); + let observed = cancellations.clone(); + let id = Uuid::new_v4(); + let job = Job::from_query_task( + id, + tokio::spawn(async { + tokio::time::sleep(Duration::from_secs(1)).await; + Ok(42_u64) + }), + move || { + observed.fetch_add(1, Ordering::SeqCst); + async { Ok(()) } + }, + ); + let error = job + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(10))) + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout { .. })); + assert!(error.to_string().contains(&id.to_string())); + assert!(!error.to_string().contains("Connection::open_job")); + assert_eq!(cancellations.load(Ordering::SeqCst), 0); + assert_eq!(job.wait().await.unwrap(), 42); + } + + #[tokio::test] + async fn wait_options_handle_zero_and_unrepresentable_deadlines() { + let job = Job::new_done(); + job.wait_with_options(JobWaitOptions::new().timeout(Duration::ZERO)) + .await + .unwrap(); + assert!(matches!( + job.wait_with_options(JobWaitOptions::new().timeout(Duration::MAX)) + .await, + Err(Error::InvalidInput { .. }) + )); + } + + #[tokio::test] + async fn wait_options_preserve_operation_errors() { + let failed = Job::::spawned(tokio::spawn(async { + Err(Error::Runtime { + message: "original failure".into(), + }) + })); + let error = failed + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1))) + .await + .unwrap_err(); + assert!(matches!(error, Error::JobFailed { .. })); + assert!(error.to_string().contains("original failure")); + let cancelled = Job::::spawned(tokio::spawn(pending())); + cancelled.cancel().await.unwrap(); + assert!(matches!( + cancelled + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1))) + .await, + Err(Error::JobCancelled { .. }) + )); + } + #[test] fn local_typed_result_decode_errors_are_runtime_errors() { assert!(matches!( diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 125930cb7..b36d3cd03 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -411,14 +411,6 @@ impl RemoteDatabase { read_consistency_interval: Option, parsed: super::client::ParsedDbUrl, ) -> Result { - let sql_client = SqlClient::new( - parsed.db_name.clone(), - parsed.db_prefix.clone(), - api_key.to_string(), - host_overrides.rest.clone(), - host_overrides.sql, - client_config.clone(), - ); let header_map = RestfulLanceDbClient::::default_headers( api_key, region, @@ -429,6 +421,27 @@ impl RemoteDatabase { &client_config, )?; + // Preserve the resolved source-account hint when table operations use SQL. + let mut sql_config = client_config.clone(); + if let Some(account) = header_map.get("x-azure-storage-account-name") { + sql_config.extra_headers.insert( + "x-azure-storage-account-name".into(), + account + .to_str() + .map_err(|error| Error::InvalidInput { + message: error.to_string(), + })? + .into(), + ); + } + let sql_client = SqlClient::new( + parsed.db_name.clone(), + parsed.db_prefix.clone(), + api_key.to_string(), + host_overrides.rest.clone(), + host_overrides.sql, + sql_config, + ); let namespace_headers: HashMap = header_map .iter() .filter_map(|(k, v)| { diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index f233d4026..c60fa46ec 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -116,6 +116,8 @@ pub(super) struct DescribeJobResponse { #[serde(default)] pub(super) progress: Option, #[serde(default)] + pub(super) operation_progress: Option, + #[serde(default)] pub(super) phase: Option, #[serde(default)] pub(super) queue_reason: Option, @@ -160,7 +162,7 @@ impl DescribeJobResponse { job_type: self.job_type, state: JobState::from(self.job_state.as_str()).client_label(), creation_ms: self.creation_ms, - progress: self.progress, + progress: self.operation_progress.or(self.progress), phase: self.phase, queue_reason: self.queue_reason, waiting_for_job_id: self.waiting_for_job_id, @@ -420,7 +422,7 @@ impl JobHandle for RemoteJob { #[cfg(test)] mod tests { - use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -428,7 +430,7 @@ mod tests { use crate::Result; use crate::function::{FunctionVersion, RefreshColumnResult}; - use crate::job::{Job, JobHandle, JobProgressCallback, TerminalResult}; + use crate::job::{Job, JobHandle, JobProgressCallback, JobWaitOptions, TerminalResult}; use crate::remote::client::test_utils::client_with_handler; use super::{DescribeJobResponse, RemoteJob}; @@ -441,6 +443,108 @@ mod tests { include_str!("../../tests/fixtures/first_class_functions/v1/remote_unit_job.json"); const MISSING_RESULT_JOB: &str = r#"{"job_state":"DONE"}"#; + #[tokio::test(start_paused = true)] + async fn timed_wait_stops_polling_and_can_resume_or_reopen_typed_maintenance_jobs() { + for job_type in ["compact", "prewarm_page_cache"] { + let done = Arc::new(AtomicBool::new(false)); + let describes = Arc::new(AtomicUsize::new(0)); + let complete = done.clone(); + let seen = describes.clone(); + let expected = if job_type == "compact" { + serde_json::json!({"partial_commit":false,"rows_succeeded":12,"rows_failed":0,"completion_percentage":100}) + } else { + serde_json::json!({"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4}) + }; + let payload = expected.clone(); + let client = + client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + seen.fetch_add(1, Ordering::SeqCst); + let finished = complete.load(Ordering::SeqCst); + http::Response::builder().status(200).body(serde_json::json!({ + "job_id":"bounded-job", "job_type":job_type, + "job_state":if finished {"DONE"} else {"IN_PROGRESS"}, + "result":if finished {payload.clone()} else {serde_json::Value::Null}, + }).to_string()).unwrap() + }); + let handle = RemoteJob::new(client.clone(), "bounded-job".into()); + let description = handle.describe().await.unwrap(); + let job = Job::opened(Box::new(handle), description) + .into_typed::() + .unwrap(); + let observations = Arc::new(Mutex::new(Vec::new())); + let updates = observations.clone(); + let options = JobWaitOptions::new() + .timeout(Duration::from_millis(50)) + .progress(move |description| { + updates.lock().unwrap().push(description.state.clone()) + }); + // Bound a regression that accidentally ignores the wait deadline. + let eventual_completion = done.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_secs(1)).await; + eventual_completion.store(true, Ordering::SeqCst); + }); + let error = job.wait_with_options(options.clone()).await.unwrap_err(); + assert!(matches!(error, crate::Error::Timeout { .. })); + assert!(error.to_string().contains("bounded-job")); + assert!(error.to_string().contains("Connection::open_job")); + assert_eq!(job.state().as_deref(), Some("running")); + assert_eq!(describes.load(Ordering::SeqCst), 2); + tokio::time::advance(Duration::from_secs(2)).await; + tokio::task::yield_now().await; + assert_eq!( + describes.load(Ordering::SeqCst), + 2, + "timed-out poller must stop" + ); + assert_eq!(*observations.lock().unwrap(), ["running"]); + done.store(true, Ordering::SeqCst); + let result = job + .wait_with_options(options.timeout(Duration::from_secs(1))) + .await + .unwrap(); + assert_eq!(result, expected); + assert_eq!(*observations.lock().unwrap(), ["running", "finished"]); + let handle = RemoteJob::new(client, "bounded-job".into()); + let description = handle.describe().await.unwrap(); + let reopened = Job::opened(Box::new(handle), description) + .into_typed::() + .unwrap(); + assert_eq!( + reopened + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1))) + .await + .unwrap(), + result + ); + } + } + + #[tokio::test(start_paused = true)] + async fn one_wait_timeout_does_not_interrupt_another_waiter() { + let done = Arc::new(AtomicBool::new(false)); + let complete = 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 complete.load(Ordering::SeqCst) {"DONE"} else {"IN_PROGRESS"}, + }).to_string()).unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "shared-job".into()))); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(100)).await; + done.store(true, Ordering::SeqCst); + }); + let (short, long) = tokio::join!( + job.wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(50))), + job.wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1))), + ); + assert!(matches!(short, Err(crate::Error::Timeout { .. }))); + long.unwrap(); + assert_eq!(job.state().as_deref(), Some("finished")); + } + #[tokio::test] async fn stack_preserves_availability_and_uses_the_selected_worker() { for status in ["captured", "unsupported", "unavailable"] { diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 9c34f8f90..f5e053f9f 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -12,7 +12,6 @@ use arrow_array::RecordBatch; use arrow_flight::decode::FlightRecordBatchStream; use arrow_flight::error::FlightError; use arrow_flight::flight_service_client::FlightServiceClient; -#[cfg(test)] use arrow_flight::sql::{CommandStatementQuery, ProstMessageExt}; use arrow_flight::{ Action, CancelFlightInfoRequest, CancelFlightInfoResult, CancelStatus, FlightClient, @@ -44,6 +43,8 @@ pub(super) use secret::SecretWriteOperation; mod stream; mod view; +const PREWARM_AZURE_HINT_CAPABILITY: &str = "lancedb.prewarm.azure_storage_account_name"; + use stream::{StreamingQuery, StreamingQueryHandle, Submission}; const DEFAULT_SQL_PORT: u16 = 10025; @@ -217,6 +218,55 @@ impl SqlClient { } } + /// Unknown headers are otherwise silently ignored by older SQL servers. + /// Probe only when a source-account hint is present, before submitting work. + pub(super) async fn execute_prewarm(&self, request: ExecuteQueryRequest) -> Result { + with_overall_timeout( + self.inner.overall_timeout()?, + "prewarm submission", + async { + validate_namespace_path(&request.default_namespace_path)?; + let request_id = Uuid::new_v4().to_string(); + let headers = self + .inner + .headers(&request.default_namespace_path, &request_id) + .await?; + if headers.contains_key("x-azure-storage-account-name") { + let connection = self.inner.connection(&request_id).await?; + let mut client = client_with_headers(connection.client.clone(), &headers)?; + let command = CommandStatementQuery { + query: request.query.clone(), + transaction_id: None, + }; + let descriptor = FlightDescriptor::new_cmd(command.as_any().encode_to_vec()); + let read_timeout = resolve_timeout( + self.inner.client_config.timeout_config.read_timeout, + "LANCE_CLIENT_READ_TIMEOUT", Some(DEFAULT_READ_TIMEOUT), + )?.unwrap(); + let info = tokio::time::timeout(read_timeout, client.get_flight_info(descriptor)) + .await.map_err(|_| Error::Runtime { message: format!("SQL PREWARM capability check timed out (request_id={request_id})") })? + .map_err(|error| sql_flight_error(&request_id, &error))?; + let supported = info.try_decode_schema().ok().is_some_and(|schema| { + schema + .metadata() + .get(PREWARM_AZURE_HINT_CAPABILITY) + .map(String::as_str) + == Some("true") + }); + if !supported { + return Err(Error::NotSupported { + message: format!( + "SQL PREWARM server cannot acknowledge the Azure storage-account hint (request_id={request_id}); upgrade the server. No execution request was sent." + ), + }); + } + } + self.execute(request).await + }, + ) + .await + } + pub(super) async fn execute(&self, request: ExecuteQueryRequest) -> Result { Ok(self .execute_with_materialized_view_job_handle(request, false) diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index d7249da9b..a80e26ad9 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -143,6 +143,8 @@ struct TestSqlService { result_overrides: Arc>>, materialized_view_job_handle_supported: bool, optimize_error: Option, + prewarm_error: Option, + prewarm_azure_supported: bool, /// How many exchange responses have been dropped, finished or not. exchange_drops: Arc, result: RecordBatch, @@ -318,6 +320,8 @@ impl Default for TestSqlService { result_overrides: Arc::new(std::sync::Mutex::new(HashMap::new())), materialized_view_job_handle_supported: false, optimize_error: None, + prewarm_error: None, + prewarm_azure_supported: false, exchange_drops: Arc::new(AtomicUsize::new(0)), result, large_result, @@ -352,9 +356,30 @@ impl FlightService for TestSqlService { async fn get_flight_info( &self, - _request: Request, + request: Request, ) -> std::result::Result, Status> { - Err(Status::unimplemented("get_flight_info")) + self.capture_headers(request.metadata()); + assert!( + request + .metadata() + .get("x-azure-storage-account-name") + .is_some() + ); + let schema = if self.prewarm_azure_supported { + self.result + .schema() + .as_ref() + .clone() + .with_metadata(HashMap::from([( + "lancedb.prewarm.azure_storage_account_name".into(), + "true".into(), + )])) + } else { + self.result.schema().as_ref().clone() + }; + Ok(Response::new( + FlightInfo::new().try_with_schema(&schema).unwrap(), + )) } async fn poll_flight_info( @@ -493,6 +518,11 @@ impl FlightService for TestSqlService { { return Err(error.clone()); } + if command.query.starts_with("PREWARM") + && let Some(error) = &self.prewarm_error + { + return Err(error.clone()); + } if command.query == "SELECT rejected" { return Err(Status::invalid_argument("invalid statement")); } @@ -4445,3 +4475,379 @@ async fn remote_optimize_branch_options_are_not_dropped() { ); shutdown.send(()).unwrap(); } + +fn prewarm_result() -> RecordBatch { + RecordBatch::try_from_iter([ + ( + "job_id", + Arc::new(StringArray::from(vec!["warming-job"])) as ArrayRef, + ), + ( + "table_version", + Arc::new(arrow_array::UInt64Array::from(vec![42])) as ArrayRef, + ), + ]) + .unwrap() +} + +#[tokio::test] +async fn remote_prewarm_data_returns_the_durable_job_without_polling() { + use crate::table::PrewarmDataOptions; + for branch in [None, Some("experiment"), Some("o'brien")] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let polls = Arc::new(AtomicUsize::new(0)); + let observed = polls.clone(); + let client = client_with_handler(move |request| -> http::Response { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + let value: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(value["job_id"], "warming-job"); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"warming-job", "job_type":"prewarm_page_cache", "job_state":"DONE", + "creation_ms":1,"spec":{"table_version":42}, + "result":{"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4}, + "operation_progress":{"phase":"reading","executors_completed":2}}) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "clip\"name".into(), + vec!["team".into(), "inner".into()], + "team$inner$clip\"name".into(), + Default::default(), + Some(sql), + ) + .with_branch(branch.map(str::to_string)); + let job = table + .prewarm_data_async( + PrewarmDataOptions::new() + .columns(["attrs.score", "`caption.text`", "attrs.score"]) + .filter("quality > 0.7") + .concurrency(4), + ) + .await + .unwrap(); + assert_eq!(job.id(), Some("warming-job")); + assert_eq!( + polls.load(Ordering::SeqCst), + 0, + "acceptance must not eagerly poll HTTP" + ); + let branch_sql = branch + .map(|b| format!("branch = '{}', ", b.replace('\'', "''"))) + .unwrap_or_default(); + assert_eq!( + *statements.lock().unwrap(), + [format!( + "PREWARM WITH ({branch_sql}concurrency = 4) AS SELECT \"attrs\".\"score\", \"caption.text\" FROM \"clip\"\"name\" WHERE quality > 0.7" + )] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.namespace_path == "team$inner" && h.database == "analytics") + ); + job.wait().await.unwrap(); + assert_eq!(polls.load(Ordering::SeqCst), 1); + job.refresh().await.unwrap(); + assert_eq!(job.spec().unwrap()["table_version"], 42); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_legacy_prewarm_data_submits_sql_and_returns_on_acceptance() { + for columns in [None, Some(vec![]), Some(vec!["payload".into()])] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!( + "legacy prewarm must neither submit nor poll REST: {}", + r.url() + ); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + table.prewarm_data(columns.clone()).await.unwrap(); + let projection = if columns.as_ref().is_some_and(|c| !c.is_empty()) { + "\"payload\"" + } else { + "*" + }; + assert_eq!( + *statements.lock().unwrap(), + [format!("PREWARM AS SELECT {projection} FROM \"clips\"")] + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_data_rejects_bad_receipts_without_resubmission() { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!("must not retry malformed receipt through REST: {}", r.url()); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let error = table.prewarm_data(None).await.unwrap_err(); + assert!(error.to_string().contains("inspect jobs before retrying")); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_prewarm_errors_preserve_diagnostics_and_never_fall_back() { + for (status, unsupported) in [ + ( + Status::invalid_argument("Unknown PREWARM option 'branch'"), + true, + ), + (Status::permission_denied("source Select denied"), false), + ( + Status::invalid_argument("ParserError: expected expression, found invalid_filter"), + false, + ), + ] { + let service = TestSqlService { + adaptive: true, + prewarm_error: Some(status), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!("must not retry through REST: {}", r.url()); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let error = table.prewarm_data(None).await.unwrap_err(); + assert_eq!( + matches!(error, Error::NotSupported { .. }), + unsupported, + "{error}" + ); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_requires_azure_ack_before_execution() { + for supported in [false, true] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + prewarm_azure_supported: supported, + ..Default::default() + }; + let statements = service.statements.clone(); + let mut config = ClientConfig::default(); + config.extra_headers.insert( + "x-azure-storage-account-name".into(), + "sourceaccount".into(), + ); + let (sql, shutdown) = start_sql_service(service, config).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!("must not use REST: {}", r.url()); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let result = table.prewarm_data(None).await; + assert_eq!(result.is_ok(), supported, "{result:?}"); + assert_eq!(statements.lock().unwrap().len(), usize::from(supported)); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_wait_surfaces_warming_job_failure_or_cancellation() { + for state in ["FAILED", "CANCELLED"] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(move |r| -> http::Response { + assert_eq!(r.url().path(), "/v1/jobs/describe"); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"warming-job","job_type":"prewarm_page_cache","job_state":state, + "creation_ms":1,"spec":{"table_version":42}, + "result":{"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4}, + "operation_progress":{"phase":"reading","executors_completed":2}}) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let job = table.prewarm_data_async(Default::default()).await.unwrap(); + assert_eq!(job.id(), Some("warming-job")); + let error = job.wait().await.unwrap_err(); + if state == "FAILED" { + assert!(matches!(error, Error::JobFailed { .. }), "{error}"); + } else { + assert!(matches!(error, Error::JobCancelled { .. }), "{error}"); + } + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_rejects_historical_checkout_without_submitting() { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + assert_eq!(r.url().path(), "/v1/table/clips/describe/"); + http::Response::builder() + .status(200) + .body(r#"{"version":7,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + table.checkout(7).await.unwrap(); + let error = table.prewarm_data(None).await.unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("historical version 7")); + assert!(statements.lock().unwrap().is_empty()); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_compaction_tracks_registry_job_and_real_result() { + use crate::table::optimize::CompactionOverrides; + let service = TestSqlService { + adaptive: true, + result: RecordBatch::try_from_iter([( + "job_id", + Arc::new(StringArray::from(vec!["compacting-job"])) as ArrayRef, + )]) + .unwrap(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let polls = Arc::new(AtomicUsize::new(0)); + let observed = polls.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["job_id"], "compacting-job"); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"compacting-job","job_type":"compact","job_state":"DONE", + "result":{"partial_commit":false,"rows_succeeded":12,"rows_failed":0, + "completion_percentage":100.0,"files_added":1,"files_removed":3, + "fragments_added":1,"fragments_removed":3}}) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into(), "inner".into()], + "team$inner$events".into(), + Default::default(), + Some(sql), + ) + .with_branch(Some("experiment".into())); + let job = table + .compact_async(CompactionOverrides { + target_rows_per_fragment: Some(100), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(job.id(), Some("compacting-job")); + assert_eq!(polls.load(Ordering::SeqCst), 0); + let result = job.wait().await.unwrap(); + assert_eq!(result.rows_succeeded, 12); + assert_eq!(result.fragments_removed, Some(3)); + assert!(!result.more_work); + assert_eq!( + *statements.lock().unwrap(), + [ + "OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'experiment', target_rows_per_fragment = 100)" + ] + ); + shutdown.send(()).unwrap(); +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 2ed46147d..2e116dd87 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -5,6 +5,7 @@ pub mod blobs; pub mod insert; mod ipc_stream; mod optimize; +mod prewarm; #[cfg(test)] mod write_tests; @@ -4098,19 +4099,10 @@ impl BaseTable for RemoteTable { options: crate::table::optimize::CompactionOverrides, ) -> Result { self.check_mutable().await?; - let compaction_options = optimize::compaction_sql_options(&options)?; + let statement = optimize::statement(&self.name, self.branch.as_deref(), &options)?; let sql_client = self.sql_client.clone().ok_or_else(|| Error::NotSupported { message: "SQL is unavailable for this remote table client".to_string(), })?; - let mut statement = format!("OPTIMIZE {} REWRITE DATA", quote_sql_identifier(&self.name)); - let mut sql_options = Vec::new(); - if let Some(branch) = &self.branch { - sql_options.push(format!("branch = {}", quote_sql_string(branch))); - } - sql_options.extend(compaction_options); - if !sql_options.is_empty() { - statement.push_str(&format!(" WITH ({})", sql_options.join(", "))); - } // `OptimizeStats` carries `lance::dataset::optimize` metric types that // are not `Serialize`/`Deserialize`/`Clone`, which `Job` requires, // so the job itself only signals completion; the real (placeholder) @@ -4127,6 +4119,42 @@ impl BaseTable for RemoteTable { prune: None, }) } + async fn compact_async( + &self, + options: crate::table::optimize::CompactionOverrides, + ) -> Result> { + self.check_mutable().await?; + let statement = optimize::statement(&self.name, self.branch.as_deref(), &options)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "compaction jobs require a Flight SQL endpoint".into(), + })?; + let query = client + .execute(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + }) + .await + .map_err(optimize::map_optimize_error)?; + let mut reader = query.reader().await.map_err(optimize::map_optimize_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader + .try_next() + .await + .map_err(optimize::map_optimize_error)? + { + batches.push(batch); + } + let job_id = optimize::receipt(&batches)?; + Ok(Job::new_typed(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) + } + async fn add_columns( &self, transforms: NewColumnTransform, @@ -4728,20 +4756,53 @@ impl BaseTable for RemoteTable { } async fn prewarm_data(&self, columns: Option>) -> Result<()> { - let mut request = self.client.post(&format!( - "/v1/table/{}/page_cache/prewarm/", - self.identifier - )); - let mut body = serde_json::json!({ - "columns": columns.unwrap_or_default(), - }); - self.apply_branch_body(&mut body); - request = request.json(&body); - let (request_id, response) = self.send(request, true).await?; - self.check_table_response(&request_id, response).await?; + self.prewarm_data_async( + crate::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()), + ) + .await?; Ok(()) } + async fn prewarm_data_async( + &self, + options: crate::table::PrewarmDataOptions, + ) -> Result> { + if let Some(version) = *self.version.read().await { + return Err(Error::NotSupported { + message: format!( + "SQL PREWARM does not support historical version {version}; use checkout_latest() to prewarm the current branch" + ), + }); + } + let statement = prewarm::statement(&self.name, self.branch.as_deref(), &options)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "data prewarm requires a Flight SQL endpoint and SQL PREWARM support" + .into(), + })?; + let query = client + .execute_prewarm(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + }) + .await + .map_err(prewarm::map_error)?; + let mut reader = query.reader().await.map_err(prewarm::map_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader.try_next().await.map_err(prewarm::map_error)? { + batches.push(batch); + } + let (job_id, _table_version) = prewarm::receipt(&batches)?; + // Construct lazily: submission must not require an HTTP status round trip. + Ok(Job::new_typed(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) + } + async fn table_definition(&self) -> Result { let schema = self.schema().await?; TableDefinition::try_from_rich_schema(schema) @@ -13718,67 +13779,16 @@ mod tests { } #[tokio::test] - async fn test_prewarm_data() { - let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.method(), "POST"); - assert_eq!( - request.url().path(), - "/v1/table/my_table/page_cache/prewarm/" + async fn test_prewarm_data_requires_sql_without_rest_fallback() { + let table = Table::new_with_handler("my_table", |request| -> http::Response { + panic!( + "data prewarm must not submit through REST: {}", + request.url() ); - http::Response::builder().status(200).body("{}").unwrap() }); - table.prewarm_data(None).await.unwrap(); - } - - #[tokio::test] - async fn test_prewarm_data_with_columns() { - let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.method(), "POST"); - assert_eq!( - request.url().path(), - "/v1/table/my_table/page_cache/prewarm/" - ); - let body = request.body().unwrap().as_bytes().unwrap(); - let body: serde_json::Value = serde_json::from_slice(body).unwrap(); - assert_eq!(body["columns"], serde_json::json!(["col_a", "col_b"])); - http::Response::builder().status(200).body("{}").unwrap() - }); - table - .prewarm_data(Some(vec!["col_a".into(), "col_b".into()])) - .await - .unwrap(); - } - - #[tokio::test] - async fn test_prewarm_data_sends_the_checked_out_branch() { - use lance::dataset::refs::Ref; - - let table = - Table::new_with_handler_version("my_table", semver::Version::new(0, 5, 0), |request| { - match request.url().path() { - "/v1/table/my_table/branches/create/" => { - http::Response::builder().status(200).body("{}").unwrap() - } - "/v1/table/my_table/page_cache/prewarm/" => { - let body = request_body_json(&request); - assert_eq!(body["branch"], "dev"); - assert_eq!(body["columns"], json!(["payload"])); - http::Response::builder() - .status(202) - .body(r#"{"job_id":"prewarm-job"}"#) - .unwrap() - } - path => panic!("unexpected request path: {path}"), - } - }); - let branch = table - .create_branch("dev", Ref::Version(None, None)) - .await - .unwrap(); - branch - .prewarm_data(Some(vec!["payload".into()])) - .await - .unwrap(); + let error = table.prewarm_data(None).await.unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("SQL")); } #[tokio::test] diff --git a/rust/lancedb/src/remote/table/optimize.rs b/rust/lancedb/src/remote/table/optimize.rs index 6f4b7f7e8..80d4d9639 100644 --- a/rust/lancedb/src/remote/table/optimize.rs +++ b/rust/lancedb/src/remote/table/optimize.rs @@ -4,6 +4,49 @@ //! Compaction options supported by the remote SQL submission protocol. use crate::error::{Error, Result}; +pub(super) fn statement( + table: &str, + branch: Option<&str>, + options: &crate::table::optimize::CompactionOverrides, +) -> Result { + let mut settings = compaction_sql_options(options)?; + if let Some(branch) = branch { + settings.insert(0, format!("branch = {}", super::quote_sql_string(branch))); + } + let mut sql = format!( + "OPTIMIZE {} REWRITE DATA", + super::quote_sql_identifier(table) + ); + if !settings.is_empty() { + sql.push_str(&format!(" WITH ({})", settings.join(", "))); + } + Ok(sql) +} + +/// Submission can already have created work: reject ambiguous receipts without +/// retrying or confusing the SQL query's identity with the compaction job. +pub(super) fn receipt(batches: &[arrow_array::RecordBatch]) -> Result { + use arrow_array::{Array, StringArray}; + let invalid = || { + Error::Runtime { message: "OPTIMIZE did not return a single nonempty job_id receipt; inspect jobs before retrying because compaction may already have been submitted".into() } + }; + if batches.iter().map(|batch| batch.num_rows()).sum::() != 1 { + return Err(invalid()); + } + let batch = batches + .iter() + .find(|batch| batch.num_rows() == 1) + .ok_or_else(invalid)?; + let ids = batch + .column_by_name("job_id") + .and_then(|a| a.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if ids.is_null(0) || ids.value(0).is_empty() { + return Err(invalid()); + } + Ok(ids.value(0).into()) +} + pub(super) fn compaction_sql_options( options: &crate::table::optimize::CompactionOverrides, ) -> Result> { @@ -258,3 +301,37 @@ mod tests { } } } + +#[cfg(test)] +mod receipt_tests { + use super::*; + use arrow_array::{ArrayRef, RecordBatch, StringArray}; + use std::sync::Arc; + + #[test] + fn compaction_receipt_requires_one_unambiguous_registry_id() { + let batch = |ids: Vec>| { + RecordBatch::try_from_iter([("job_id", Arc::new(StringArray::from(ids)) as ArrayRef)]) + .unwrap() + }; + assert_eq!( + receipt(&[batch(vec![Some("compacting-job")])]).unwrap(), + "compacting-job" + ); + for batches in [ + vec![], + vec![batch(vec![])], + vec![batch(vec![None])], + vec![batch(vec![Some("")])], + vec![batch(vec![Some("a"), Some("b")])], + vec![batch(vec![Some("a")]), batch(vec![Some("b")])], + ] { + assert!( + receipt(&batches) + .unwrap_err() + .to_string() + .contains("inspect jobs before retrying") + ); + } + } +} diff --git a/rust/lancedb/src/remote/table/prewarm.rs b/rust/lancedb/src/remote/table/prewarm.rs new file mode 100644 index 000000000..8388b6350 --- /dev/null +++ b/rust/lancedb/src/remote/table/prewarm.rs @@ -0,0 +1,248 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! SQL submission and receipt validation for data-cache prewarm jobs. + +use arrow_array::{Array, RecordBatch, StringArray, UInt64Array}; +use datafusion_sql::sqlparser::{dialect::GenericDialect, parser::Parser, tokenizer::Token}; + +use super::{quote_sql_identifier, quote_sql_string}; +use crate::{Error, Result, table::PrewarmDataOptions}; + +pub(super) fn statement( + table: &str, + branch: Option<&str>, + options: &PrewarmDataOptions, +) -> Result { + let invalid = |message: &str| Error::InvalidInput { + message: message.into(), + }; + if options.concurrency == Some(0) { + return Err(invalid("prewarm concurrency must be greater than 0")); + } + if let Some(filter) = &options.filter { + if filter.trim().is_empty() { + return Err(invalid("prewarm filter must not be empty")); + } + let dialect = GenericDialect {}; + let mut parser = Parser::new(&dialect) + .try_with_sql(filter) + .map_err(|error| invalid(&format!("invalid prewarm filter: {error}")))?; + parser + .parse_expr() + .map_err(|error| invalid(&format!("invalid prewarm filter: {error}")))?; + if parser.peek_token().token != Token::EOF { + return Err(invalid("prewarm filter must be a single SQL expression")); + } + } + let mut settings = Vec::new(); + if let Some(branch) = branch { + if branch.trim().is_empty() { + return Err(invalid("prewarm branch must not be empty")); + } + settings.push(format!("branch = {}", quote_sql_string(branch))); + } + if let Some(concurrency) = options.concurrency { + settings.push(format!("concurrency = {concurrency}")); + } + let mut sql = "PREWARM".to_string(); + if !settings.is_empty() { + sql.push_str(&format!(" WITH ({})", settings.join(", "))); + } + let mut columns = Vec::new(); + for column in &options.columns { + let parts = lance::datatypes::parse_field_path(column)?; + let column = parts + .iter() + .map(|part| quote_sql_identifier(part)) + .collect::>() + .join("."); + if !columns.contains(&column) { + columns.push(column); + } + } + let projection = if columns.is_empty() { + "*".into() + } else { + columns.join(", ") + }; + sql.push_str(&format!( + " AS SELECT {projection} FROM {}", + quote_sql_identifier(table) + )); + if let Some(filter) = &options.filter { + sql.push_str(&format!(" WHERE {filter}")); + } + Ok(sql) +} + +pub(super) fn receipt(batches: &[RecordBatch]) -> Result<(String, u64)> { + let invalid = || { + Error::Runtime { + message: "PREWARM did not return a single (job_id, table_version) receipt; inspect jobs before retrying because work may already have been submitted".into(), + } + }; + if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { + return Err(invalid()); + } + let batch = batches + .iter() + .find(|batch| batch.num_rows() == 1) + .ok_or_else(invalid)?; + let id = batch + .column_by_name("job_id") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + let version = batch + .column_by_name("table_version") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if id.is_null(0) || id.value(0).is_empty() || version.is_null(0) { + return Err(invalid()); + } + Ok((id.value(0).into(), version.value(0))) +} + +pub(super) fn map_error(error: Error) -> Error { + fn unsupported(error: &Error) -> Option<&Error> { + match error { + Error::Sql { + message, grpc_code, .. + } => { + let diagnostic = message.to_ascii_lowercase(); + (*grpc_code == tonic::Code::Unimplemented as i32 + || (*grpc_code == tonic::Code::InvalidArgument as i32 + && (diagnostic.contains("found: prewarm") + || diagnostic.contains("supported syntax: prewarm") + || diagnostic.contains("unknown prewarm option")))) + .then_some(error) + } + Error::JobFailed { failure, .. } => failure.source.as_deref().and_then(unsupported), + _ => None, + } + } + if let Some(source) = unsupported(&error) { + let diagnostic = if matches!(error, Error::Sql { .. }) { + error.to_string() + } else { + format!("{error}; {source}") + }; + Error::NotSupported { + message: format!( + "Data prewarm requires a compatible SQL PREWARM server; upgrade the server. Requested options will not be removed and submission will not fall back to REST. Server diagnostic: {diagnostic}" + ), + } + } else { + error + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + #[test] + fn quotes_paths_branch_and_filter_without_changing_options() { + let options = PrewarmDataOptions::new() + .columns(["attrs.score", "`caption.text`", "attrs.score"]) + .filter("quality > 0.7 AND caption = 'it''s ready'") + .concurrency(4); + assert_eq!( + statement("clip\"name", Some("o'brien"), &options).unwrap(), + "PREWARM WITH (branch = 'o''brien', concurrency = 4) AS SELECT \"attrs\".\"score\", \"caption.text\" FROM \"clip\"\"name\" WHERE quality > 0.7 AND caption = 'it''s ready'" + ); + assert_eq!( + statement("clips", None, &Default::default()).unwrap(), + "PREWARM AS SELECT * FROM \"clips\"" + ); + assert!(statement("clips", None, &PrewarmDataOptions::new().filter("-1 < id")).is_ok()); + } + + #[test] + fn rejects_invalid_inputs_before_submission() { + for options in [ + PrewarmDataOptions::new().filter(""), + PrewarmDataOptions::new().filter("id > 0; DROP TABLE clips"), + PrewarmDataOptions::new().filter("id > 0 LIMIT 1"), + PrewarmDataOptions::new().filter("id >"), + PrewarmDataOptions::new().columns(["attrs..score"]), + PrewarmDataOptions::new().concurrency(0), + ] { + assert!(statement("clips", None, &options).is_err(), "{options:?}"); + } + } + + fn batch(ids: Vec>, versions: Vec>) -> RecordBatch { + RecordBatch::try_from_iter([ + ( + "job_id", + Arc::new(StringArray::from(ids)) as arrow_array::ArrayRef, + ), + ( + "table_version", + Arc::new(UInt64Array::from(versions)) as arrow_array::ArrayRef, + ), + ]) + .unwrap() + } + + #[test] + fn receipt_requires_one_non_null_job_and_version() { + assert_eq!( + receipt(&[batch(vec![Some("job-1")], vec![Some(42)])]).unwrap(), + ("job-1".into(), 42) + ); + for batches in [ + vec![], + vec![batch(vec![], vec![])], + vec![batch(vec![None], vec![Some(42)])], + vec![batch(vec![Some("")], vec![Some(42)])], + vec![batch(vec![Some("job")], vec![None])], + vec![batch(vec![Some("a"), Some("b")], vec![Some(1), Some(2)])], + vec![ + batch(vec![Some("a")], vec![Some(1)]), + batch(vec![Some("b")], vec![Some(2)]), + ], + vec![RecordBatch::new_empty(Arc::new(Schema::new(vec![ + Field::new("wrong", DataType::Utf8, false), + ])))], + ] { + let error = receipt(&batches).unwrap_err().to_string(); + assert!(error.contains("inspect jobs before retrying"), "{error}"); + } + } + + #[test] + fn compatibility_errors_preserve_permission_and_predicate_diagnostics() { + for (code, message, unsupported) in [ + ( + tonic::Code::InvalidArgument, + "ParserError: found: PREWARM", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown PREWARM option 'branch'", + true, + ), + (tonic::Code::PermissionDenied, "permission denied", false), + ( + tonic::Code::InvalidArgument, + "ParserError: expected expression, found unsupported_filter", + false, + ), + ] { + let error = map_error(Error::Sql { + message: message.into(), + request_id: "prewarm-request".into(), + grpc_code: code as i32, + metadata: Default::default(), + }); + assert_eq!(matches!(error, Error::NotSupported { .. }), unsupported); + assert!(error.to_string().contains(message)); + assert!(error.to_string().contains("prewarm-request")); + } + } +} diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index f247a386f..e7f8062e4 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -86,6 +86,9 @@ pub mod freshness; pub mod function_column_status; pub mod merge; pub mod optimize; +pub use optimize::CompactionResult; +mod prewarm; +pub use prewarm::{PrewarmDataOptions, PrewarmDataResult}; pub(crate) mod primary_key; pub mod query; pub mod refresh; @@ -688,6 +691,16 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// Currently only supported in LanceDB Enterprise. /// If `columns` is `None`, all columns are prewarmed. async fn prewarm_data(&self, columns: Option>) -> Result<()>; + + /// Submit a data-cache prewarm and return its durable job handle. + async fn prewarm_data_async( + &self, + _options: PrewarmDataOptions, + ) -> Result> { + Err(Error::NotSupported { + message: "data prewarm jobs are only supported on remote tables".into(), + }) + } /// Get statistics about the index. async fn index_stats(&self, index_name: &str) -> Result>; /// Merge insert new records into the table. @@ -881,6 +894,15 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn tags(&self) -> Result>; /// Optimize the dataset. async fn optimize(&self, action: OptimizeAction) -> Result; + /// Submit remote compaction and retain its durable job and actual outcome. + async fn compact_async( + &self, + _options: optimize::CompactionOverrides, + ) -> Result> { + Err(Error::NotSupported { + message: "compaction jobs are only supported on remote tables".into(), + }) + } /// Compact with optional fields, preserving remote policy inheritance. async fn compact(&self, options: optimize::CompactionOverrides) -> Result { self.optimize(OptimizeAction::Compact { @@ -2065,6 +2087,37 @@ impl Table { self.inner.compact(options).await } + /// Submit remote compaction and return its durable job after acceptance. + /// + /// Uses SQL `OPTIMIZE ... REWRITE DATA` with the table handle's namespace + /// and branch. The four fields of [`optimize::CompactionOverrides`] retain + /// server defaults when omitted. Requires a compatible remote SQL server + /// and table Ownership plus database/namespace Usage under Standard authorization. + /// Historical-version and local handles are unsupported. + /// + /// Unlike [`Self::optimize`], waiting on this handle waits for compaction + /// itself and returns actual [`CompactionResult`] values. Status, progress, + /// events, and cancellation use the generic HTTP job APIs. A timeout or + /// dropping the handle does not cancel work. Missing result payloads are + /// errors, never placeholder zero statistics. An older worker may omit + /// file counts, represented as `None`. Reopen with + /// `connection.open_job(id).await?.into_typed::()?`. + /// + /// ```no_run + /// # async fn compact(table: &lancedb::Table) -> lancedb::Result<()> { + /// let job = table.compact_async(Default::default()).await?; + /// let result = job.wait().await?; + /// println!("Committed {} rows", result.rows_succeeded); + /// # Ok(()) + /// # } + /// ``` + pub async fn compact_async( + &self, + options: optimize::CompactionOverrides, + ) -> Result> { + self.inner.compact_async(options).await + } + /// Language-binding entry point retaining optional compaction fields. #[doc(hidden)] pub async fn optimize_full_with_overrides( @@ -3090,8 +3143,9 @@ impl Table { /// supported in LanceDB Enterprise. /// /// This call initiates prewarming and returns once the request is accepted. - /// It is idempotent and safe to call from multiple clients concurrently — - /// calling it on already-prewarmed columns is a no-op on the server. + /// Remote tables use SQL PREWARM and require Flight SQL connectivity. + /// Use [`Self::prewarm_data_async`] to retain the durable job handle. + /// Repeated submissions can create distinct jobs; warming cached data is safe. /// /// This operation has a large upfront cost but can speed up future queries /// that need to fetch the given columns. Large columns such as embeddings @@ -3103,6 +3157,41 @@ impl Table { self.inner.prewarm_data(columns).await } + /// Submit a durable data-cache prewarm job through SQL and return when accepted. + /// + /// The handle tracks the warming job, rather than the SQL submission. Use + /// [`Job::wait`] to wait for warming to finish, or save [`Job::id`] and + /// reopen it through [`crate::Connection::open_job`]. A wait timeout or + /// dropping the handle does not cancel the job. Waiting returns the reported + /// [`PrewarmDataResult`]; unavailable measurements remain `None`. + /// + /// Requires a compatible remote server with SQL PREWARM support and Flight + /// SQL connectivity. Under Standard authorization, submission requires + /// Select on the table and Usage on its database and namespace hierarchy. + /// Status and waiting use the generic HTTP job APIs; events and cancellation + /// retain their separate privileges. Unsupported servers are not retried + /// through REST or with requested settings removed. Local tables are unsupported. + /// Historical-version checkouts are unsupported; use `checkout_latest()` first. + /// After [`Job::refresh`], the pinned source version is in [`Job::spec`]. + /// + /// ```no_run + /// # async fn warm(table: &lancedb::Table) -> lancedb::Result<()> { + /// use lancedb::table::PrewarmDataOptions; + /// let job = table.prewarm_data_async(PrewarmDataOptions::new() + /// .columns(["video"]) + /// .filter("quality > 0.7") + /// .concurrency(4)).await?; + /// job.wait().await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn prewarm_data_async( + &self, + options: PrewarmDataOptions, + ) -> Result> { + self.inner.prewarm_data_async(options).await + } + /// Poll until the columns are fully indexed. Will return Error::Timeout if the columns /// are not fully indexed within the timeout. pub async fn wait_for_index( diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index ab34e05c6..0888ca4c4 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -32,6 +32,35 @@ pub use lance::dataset::optimize::{CompactionMode, CompactionOptions, IndexRemap const MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX: u64 = u32::MAX as u64; +/// Actual outcome of one remote compaction job, returned by its job handle. +/// +/// A successful bounded run can leave more work for another invocation. A +/// partial commit reports uncommitted rows rather than inventing file counts. +/// File/fragment counts are unknown (`None`) when an older worker omitted them. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct CompactionResult { + /// A complete bounded plan left eligible work for a later invocation. + #[serde(default)] + pub more_work: bool, + /// Some planned groups were not committed. + pub partial_commit: bool, + /// Live source rows in committed rewrite groups. + pub rows_succeeded: u64, + /// Planned live rows not committed by this job. + pub rows_failed: u64, + /// Percentage of planned live rows committed, from 0 to 100. + pub completion_percentage: f64, + /// Files added by committed rewrites, including deletion files, when reported. + pub files_added: Option, + /// Files removed by committed rewrites, including deletion files, when reported. + pub files_removed: Option, + /// Fragments added by committed rewrites, when reported by the server. + pub fragments_added: Option, + /// Fragments removed by committed rewrites, when reported by the server. + pub fragments_removed: Option, +} + struct PrecomputedCompactionPlanner { plan: Mutex>, } @@ -261,8 +290,11 @@ pub enum OptimizeAction { /// options and custom `remap_options` return [`crate::Error::NotSupported`] /// before submission. The server must support these SQL options; errors /// from older servers are returned without dropping the settings. - /// The source-row budget admits whole tasks and may perform no work when - /// the first task exceeds it. Zero I/O buffer size disables byte-based I/O + /// The source-row budget admits whole tasks. On current Enterprise servers, + /// worker planning fails if the budget cannot admit the first useful task, + /// reporting its required live rows and source fragment count. Older servers + /// may instead finish without rewriting data in this case. + /// Zero I/O buffer size disables byte-based I/O /// backpressure. Use a positive size to limit I/O read-ahead; this is not a /// total-memory limit. Row targets, source-row budgets, and batch sizes must /// be positive. @@ -298,10 +330,11 @@ pub enum OptimizeAction { /// # } /// ``` /// - /// A branch-scoped table handle compacts that branch. The branch is not - /// validated to exist before the job is submitted, so a nonexistent - /// branch fails the compaction job asynchronously rather than failing - /// this call. + /// A branch-scoped table handle compacts that branch. Current Enterprise + /// servers validate the table and branch through the service catalog before + /// creating the compaction job, so a nonexistent branch fails submission. + /// Older servers may accept submission and fail the compaction job + /// asynchronously instead. Compact { options: CompactionOptions, remap_options: Option>, diff --git a/rust/lancedb/src/table/prewarm.rs b/rust/lancedb/src/table/prewarm.rs new file mode 100644 index 000000000..1d0f8c002 --- /dev/null +++ b/rust/lancedb/src/table/prewarm.rs @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Options for submitting a durable data-cache prewarm job. + +/// Data prewarm settings for [`super::Table::prewarm_data_async`]. +/// +/// The table handle supplies the database, namespace, and branch. Omitted +/// columns warm all fields. The filter selects conservative metadata ranges; +/// it does not execute a row-filter scan or change the source data. +#[derive(Debug, Clone, Default)] +#[non_exhaustive] +pub struct PrewarmDataOptions { + /// Lance field paths, including nested paths such as `attrs.score`. + pub columns: Vec, + /// An optional SQL predicate for metadata pruning. + pub filter: Option, + /// Positive per-executor warming concurrency. Omit for the server default. + pub concurrency: Option, +} + +impl PrewarmDataOptions { + /// Use server defaults and warm every column. + pub fn new() -> Self { + Self::default() + } + + /// Select fields to warm. An empty collection selects all columns. + pub fn columns(mut self, columns: impl IntoIterator>) -> Self { + self.columns = columns.into_iter().map(Into::into).collect(); + self + } + + /// Restrict warming using a single SQL predicate for metadata pruning. + pub fn filter(mut self, filter: impl Into) -> Self { + self.filter = Some(filter.into()); + self + } + + /// Set positive per-executor warming concurrency. + pub fn concurrency(mut self, concurrency: u32) -> Self { + self.concurrency = Some(concurrency); + self + } +} + +/// Reported outcome of a remote data-prewarm job. Counts describe executor work; +/// absent measurements remain unknown rather than being inferred as zero. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct PrewarmDataResult { + /// Source snapshot captured by the submitted prewarm. + pub table_version: u64, + /// Reported executors targeted; unknown on older workers. + pub executors_targeted: Option, + /// Executors that reached a successful or partial terminal state. + pub executors_completed: Option, + /// Subset of completed executors that reported partial warming. + pub executors_partial: Option, + /// Reported fragments selected; unknown on older workers. + pub fragments_selected: Option, + /// Reported ranges completed; unknown on older workers. + pub ranges_completed: Option, + /// Reported bytes read; unknown on older workers. + pub bytes_read: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + #[test] + fn result_preserves_zero_partial_and_unknown_measurements() { + let result: PrewarmDataResult = serde_json::from_value(serde_json::json!({ + "table_version":42,"executors_targeted":2,"executors_completed":2, + "executors_partial":1,"ranges_completed":0,"extra":"ignored", + })) + .unwrap(); + assert_eq!(result.executors_partial, Some(1)); + assert_eq!(result.ranges_completed, Some(0)); + assert_eq!(result.bytes_read, None); + assert!(serde_json::from_value::(serde_json::json!({})).is_err()); + assert!( + serde_json::from_value::( + serde_json::json!({"table_version":42,"bytes_read":-1}) + ) + .is_err() + ); + } + + #[tokio::test] + async fn local_table_rejects_durable_data_prewarm() { + let db = crate::connect(&format!("memory://prewarm-{}", uuid::Uuid::new_v4())) + .execute() + .await + .unwrap(); + let table = db + .create_empty_table( + "items", + Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])), + ) + .execute() + .await + .unwrap(); + let error = table + .prewarm_data_async(PrewarmDataOptions::new().filter("id > 0")) + .await + .unwrap_err(); + assert!(matches!(error, crate::Error::NotSupported { .. })); + assert!( + error + .to_string() + .contains("only supported on remote tables") + ); + } +} From e29ec0e0847b696b8ebb83a6cc0027c316a257b0 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Tue, 17 Nov 2026 13:58:48 -0800 Subject: [PATCH 07/78] docs: publish the CLI page (#5079) The compaction guide links to `/tools/cli#install`, but `tools/cli.mdx` was listed in `docs/web/.mintignore`, so the link had no target and failed the broken-links check in the docs site build. This removes the page from `.mintignore` and restores its nav entry and the link from `basics/sql.mdx`, both dropped when the page was hidden in #4859. --- docs/web/.mintignore | 1 - docs/web/basics/sql.mdx | 2 +- docs/web/docs.json | 1 + 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/web/.mintignore b/docs/web/.mintignore index 8fea3d17d..b6f13bcdc 100644 --- a/docs/web/.mintignore +++ b/docs/web/.mintignore @@ -1,4 +1,3 @@ -tools/cli.mdx # Branching is Beta; not documented until early access. tables/branching.mdx # stays reachable (out of the nav only): SDK error messages link to it. # To restore: docs.json Tutorials > Feature Engineering, after tutorials/feature-engineering/materialized-views. diff --git a/docs/web/basics/sql.mdx b/docs/web/basics/sql.mdx index 31e3af1f3..89f465e65 100644 --- a/docs/web/basics/sql.mdx +++ b/docs/web/basics/sql.mdx @@ -80,7 +80,7 @@ endpoint, returning results as Arrow record batches: does not expose a SQL execution method, or from any tool with its own Flight SQL integration. A LanceDB-specific SDK is not required to submit SQL. -3. **The LanceDB CLI.** Open an interactive SQL shell, or run a +3. **The [LanceDB CLI](/tools/cli).** Open an interactive SQL shell, or run a statement or file, directly from the command line with no code at all. The [SQL reference](/sql#connecting) shows a query from Python. See diff --git a/docs/web/docs.json b/docs/web/docs.json index 0b26a7fc0..4f5d247b3 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -387,6 +387,7 @@ "quickstart", "basics/sdk", "basics/sql", + "tools/cli", "basics/agentic-skills", "deployment/support" ] From ee671533f9994504c46285f1940eb114f92df038 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Tue, 17 Nov 2026 19:06:45 -0800 Subject: [PATCH 08/78] docs: say the Tables page covers schema changes and field metadata (#5080) The docs index lists each page by its title and description. The Tables page holds the guide to field metadata, but its description only mentioned creating, renaming and dropping tables. In local runs of the agent evals, two of three docs-only agents searched the index for "metadata", landed on the REST reference, and never found the convention. This adds schema changes and field metadata to the description and keywords, so that search finds the guide. --- docs/web/management/table.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index ff56aff10..cfe363176 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -1,9 +1,9 @@ --- title: "Tables" sidebarTitle: "Table" -description: "The object most operations act on: creating, opening, renaming, cloning and dropping one." +description: "The object most operations act on: creating, opening, renaming, cloning and dropping one, changing its schema, and documenting its columns with field metadata." icon: table -keywords: ["table", "create_table", "open_table", "clone", "rename", "drop"] +keywords: ["table", "create_table", "open_table", "clone", "rename", "drop", "schema", "field metadata", "update_field_metadata", "column description", "tags"] availability: embedded: available enterprise: available From 13453ae5f83826bf0438ecc5a4a2f4918b69a6fe Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Tue, 17 Nov 2026 19:17:37 -0800 Subject: [PATCH 09/78] docs: serve Attach Database at ingestion/attach-database (#5078) The Attach Database page was renamed in the docs rework but kept its old URL, `ingestion/migrate-from-embedded`. That reads like the wrong page when we share the link. This renames the file to `ingestion/attach-database`, updates its nav entry and the two pages that link to it, and adds a redirect from the old URL so existing links keep working. --- docs/web/basics/embedded-vs-enterprise.mdx | 2 +- docs/web/docs.json | 6 +++++- .../{migrate-from-embedded.mdx => attach-database.mdx} | 0 docs/web/ingestion/define-storage-integration.mdx | 4 ++-- 4 files changed, 8 insertions(+), 4 deletions(-) rename docs/web/ingestion/{migrate-from-embedded.mdx => attach-database.mdx} (100%) diff --git a/docs/web/basics/embedded-vs-enterprise.mdx b/docs/web/basics/embedded-vs-enterprise.mdx index 7d30a0e92..430d26885 100644 --- a/docs/web/basics/embedded-vs-enterprise.mdx +++ b/docs/web/basics/embedded-vs-enterprise.mdx @@ -33,7 +33,7 @@ file format, so moving data from one edition to the other does not require a dat | **Data Ingestion** | [Insert data](/ingestion/insert) | ✅ | ✅ | | | [RTE Write (Upsert)](/ingestion/realtime-write) | ✅ | ✅ | | | [Distributed RTE Write](/enterprise/distributed-real-time-write) | ❌ | ✅ | -| | [Attach Database](/ingestion/migrate-from-embedded) | ❌ | ✅ | +| | [Attach Database](/ingestion/attach-database) | ❌ | ✅ | | | [Import Datasets](/ingestion/import) | ❌ | ✅ | | | [Distributed Write](/enterprise/distributed-write) | ❌ | ✅ | | **Search** | [Vector search](/search/vector-search) | ✅ | ✅ | diff --git a/docs/web/docs.json b/docs/web/docs.json index 4f5d247b3..4c800d65a 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -27,6 +27,10 @@ }, "favicon": "/static/favicon.ico", "redirects": [ + { + "source": "/ingestion/migrate-from-embedded", + "destination": "/ingestion/attach-database" + }, { "source": "/enterprise/expected-performance", "destination": "/search/vector-search#expected-performance" @@ -415,7 +419,7 @@ "ingestion/delete", "ingestion/realtime-write", "ingestion/define-storage-integration", - "ingestion/migrate-from-embedded", + "ingestion/attach-database", "ingestion/import", "enterprise/distributed-write", "enterprise/distributed-real-time-write" diff --git a/docs/web/ingestion/migrate-from-embedded.mdx b/docs/web/ingestion/attach-database.mdx similarity index 100% rename from docs/web/ingestion/migrate-from-embedded.mdx rename to docs/web/ingestion/attach-database.mdx diff --git a/docs/web/ingestion/define-storage-integration.mdx b/docs/web/ingestion/define-storage-integration.mdx index 446d47d22..96e137601 100644 --- a/docs/web/ingestion/define-storage-integration.mdx +++ b/docs/web/ingestion/define-storage-integration.mdx @@ -10,7 +10,7 @@ availability: --- Before you can [import data](/ingestion/import) from external storage or -[attach an existing database](/ingestion/migrate-from-embedded), define a +[attach an existing database](/ingestion/attach-database), define a storage integration once per location. It is a namespace-scoped catalog object that stores the credential -- neither operation names the integration directly, LanceDB matches the URI you read against whichever @@ -166,7 +166,7 @@ for the Python and SQL CRUD operations at a glance. Read or import through the integration once it exists. - + Attach an existing database at a location the integration covers. From 4cab7d0b6f5b9b8c5bd1034887ab3ba87d862389 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 18 Nov 2026 16:14:01 +0800 Subject: [PATCH 10/78] docs: show how to read and copy filtered blob rows (#5086) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The table guide starts with two tasks using the same `photos` table: read the bytes of filtered images with the LanceDB Python SDK and copy those images into another Enterprise table with `INSERT INTO … SELECT`. The examples distinguish SDK descriptors, independent row-ID fetches, Function readers and Enterprise 1.12.0 SQL results. The Enterprise support page covers SDK, server and proxy compatibility when query-bound reads fail. --- docs/web/deployment/support.mdx | 19 +++ docs/web/management/table.mdx | 231 ++++++++++---------------------- 2 files changed, 93 insertions(+), 157 deletions(-) diff --git a/docs/web/deployment/support.mdx b/docs/web/deployment/support.mdx index 09b2892c3..d97546932 100644 --- a/docs/web/deployment/support.mdx +++ b/docs/web/deployment/support.mdx @@ -38,3 +38,22 @@ post in Discord or email: Talk to your account executive, file a support ticket, or reach the LanceDB support and engineering team directly for dedicated assistance. + +### Python blob queries raise `NotImplementedError` {#blob-query-bytes} + +If a Blob v2 query works in `"descriptions"` mode but fails in `"bytes"` mode, +check that the Python SDK and every serving node support snapshot-bound reads. +Enterprise 1.12.0 supports separate row-ID fetches. For query-bound reads, +upgrade the serving path before enabling the feature in clients. + +- On the query response, the proxy must preserve `x-lancedb-query-version` + and `x-lancedb-query-snapshot`. The legacy `x-lancedb-version` watermark + or Arrow metadata alone cannot identify the snapshot that produced the rows. +- On each payload request, forward the selected version and the + `x-lancedb-query-snapshot` header. The server checks the identity against + the dataset it opens and echoes it in the response. The proxy must preserve + that echo so the SDK can verify it before returning bytes. + +If the version was deleted or the table was recreated, repeat the query to +select a current snapshot. To finish reading the original selection, retain +its table version until the last batch has been read. diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index cfe363176..c24b08b4a 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -384,8 +384,8 @@ file, up to 64 KiB by default, and larger values are stored outside it. Early access -A `blob` column keeps metadata separate from the payload bytes, so queries can -filter rows without loading the blobs. +Filter rows by their metadata first. Then read the matching blob bytes in +Python, or copy the matching rows to another table with Enterprise SQL. {/* Draft for Blob v2 GA. Confirm release status before removing Early access. @@ -393,15 +393,62 @@ Blob v2 GA supports standard tables. Tables with Realtime or MemWAL enabled are outside the GA support scope. */} -SDK queries return descriptors by default, which contain metadata about the -blob instead of its bytes. Enterprise SQL queries return payload bytes by -default; use `blob_descriptor(column)` to select metadata instead. With an SDK, -you can -[read the bytes in the query results](#multimodal-blob-query-results) or -[fetch them by row ID](#multimodal-read-blobs). +Suppose your Enterprise database has a `photos` table with an integer `id` and a +Blob v2 column named `image`. Set `LANCEDB_URI`, `LANCEDB_API_KEY`, and +`LANCEDB_HOST_OVERRIDE` to your database URI, API key, and HTTPS endpoint. +See [Connect to LanceDB Enterprise](/basics/catalog#enterprise). -In Python, plain `to_pandas()` scans can also return `BlobFile` handles when -`pylance` is installed. +An SDK query normally returns a descriptor with the blob's location and size. +Pass `blob_mode="bytes"` to get the actual image in the same query. Each result +contains Python `bytes`, or `None` for a null image. + +```python +import os +import lancedb + +db = lancedb.connect( + os.environ["LANCEDB_URI"], + api_key=os.environ["LANCEDB_API_KEY"], + host_override=os.environ["LANCEDB_HOST_OVERRIDE"], +) +rows = ( + db.open_table("photos").search() + .where("id < 100") + .select(["id", "image"]) + .limit(10) + .to_list(blob_mode="bytes") +) +for row in rows: + image = row["image"] + print(row["id"], len(image) if image is not None else None) +``` + +Use this mode with a Python SDK and Enterprise deployment that support +snapshot-bound blob reads. The bytes come from the same table version as the +filtered rows. Keep that version available until the read finishes. On +Enterprise 1.12.0, or when you already have row IDs, use `fetch_blobs()`. +Keep the source unchanged between selecting the IDs and fetching their bytes. +Inside a LanceDB Function, a parameter annotated with `lancedb.BlobReader` +lets the function seek and read the input on demand. +[Fetch blobs by row ID](#multimodal-read-blobs) · [Troubleshoot Enterprise blob reads](/deployment/support#blob-query-bytes) + +#### Copy a subset of blob rows {#multimodal-copy-subset} + +To copy images within the same Enterprise database, run the filter on the +server. This example appends matching rows to an existing `photo_subset` +table with the same `id` and blob `image` columns. + +```sql +INSERT INTO photo_subset (id, image) +SELECT id, image FROM photos WHERE id < 100; +``` + +In Enterprise 1.12.0, selecting a Blob v2 column directly in SQL returns the +payload as `large_binary`. Use `blob_descriptor(image)` when you want storage +metadata. For a copy, select `image` itself. +[SQL blob descriptors](/sql/dql/blob-descriptor) + +#### Blob storage layouts {#blob-storage-layouts} When you write raw bytes, Lance chooses a storage layout based on the payload size. A descriptor's `kind` tells you which one was used: @@ -500,141 +547,23 @@ methods `to_pandas()`, `to_arrow()`, `to_list()`, and `to_batches()` accept a | `blob_mode` | `to_pandas()` | `to_arrow()` and `to_list()` | | --- | --- | --- | -| `"lazy"` | Default. Plain scans return seekable `BlobFile` handles. Vector, full-text, hybrid, and ordered queries return descriptor dicts. | Default. Returns descriptors carrying `_lance_row_id` so the result table can be passed to `fetch_blobs` or `fetch_blob_files`. | +| `"lazy"` | Default. Local plain scans return seekable `BlobFile` handles; local vector, full-text, hybrid, and ordered queries return descriptor dicts. Enterprise queries raise `NotImplementedError`. | Default. Returns descriptors carrying `_lance_row_id` so the result table can be passed to `fetch_blobs` or `fetch_blob_files`. | | `"descriptions"` | Returns descriptor dicts with `kind`, `position`, `size`, `blob_id`, and `blob_uri`. | Returns the 5-field descriptor without `_lance_row_id`. | | `"bytes"` | Materializes each blob as `bytes` in the DataFrame. | Materializes each blob as `large_binary` in Arrow or `bytes` in Python dicts. | -For supported local v2 blob projections, `to_pandas(blob_mode="bytes")` and +For supported v2 blob projections, `to_pandas(blob_mode="bytes")` and `to_pandas(blob_mode="descriptions")` use native Arrow conversion without pylance. Eligible local plain scans also convert row-addressable legacy blob bytes without pylance. Pandas conversions that need the Lance scanner, -including plain-scan `"lazy"` handles and scanner-only options, still require -pylance. `to_arrow()`, `to_list()`, `to_batches()`, and the fetch methods do -not require pylance for supported local queries. +including local plain-scan `"lazy"` handles and scanner-only options, still +require pylance. `to_arrow()`, `to_list()`, `to_batches()`, and the fetch +methods do not require pylance for supported queries. -`blob_mode="bytes"` requires a LanceDB Embedded table snapshot, so Enterprise -and in-memory tables raise `NotImplementedError`. On an Enterprise table, -`Table.to_pandas()` and -`Table.to_arrow()` aren't supported, and a query's `to_pandas()` also raises in -the default `"lazy"` mode because it would open `BlobFile` handles. Query with -`blob_mode="descriptions"`, then read bytes with `fetch_blobs` or -`fetch_blob_files`. - -{/* Draft for the Enterprise Python bytes release. Replace the released instructions above only after SDK and serving-node rollout. - -`blob_mode="bytes"` also supports Enterprise queries. The SDK locks all blob -fetches, including streaming batches, to both the version in -`x-lancedb-query-version` and the incarnation/revision identity in -`x-lancedb-query-snapshot`, captured from the same query response. Every payload -request verifies that identity against the actual opened dataset before reading -rows. Concurrent writes therefore preserve the selected payloads. Dropping and -recreating a table, even at the same location and version, cannot substitute the -replacement's bytes: the original snapshot is served or the read fails explicitly. - -Upgrade the SDK and every serving node to support snapshot identities. A server -that reports only a numeric query version, a legacy `x-lancedb-version` watermark, -or Arrow schema metadata does not enable deferred bytes. Missing or unsupported -identities raise `NotImplementedError`; use `"descriptions"` until the upgrade is -complete. Ordinary queries, descriptors, and independent `fetch_blobs` calls keep -working. Old SDKs keep their existing behavior and do not gain this protection -from a server-only upgrade. Realtime/MemWAL and historical manifests without a -native transaction identity do not support deferred bytes. Snapshot identities -do not retain old versions; deleting the selected version still fails explicitly. -In-memory tables and namespace `QueryTable` pushdown do not support bytes mode. -On an Enterprise table, sync `Table.to_pandas()` and `Table.to_arrow()` are not -supported; use `table.search()` instead. A query's `to_pandas()` also raises in -the default `"lazy"` mode because remote lazy handles are not supported. -*/} - -###### Copy a subset of blob rows {#multimodal-copy-subset} - -SDK descriptors identify stored payloads; materialize the bytes before inserting -them into another table. These APIs return different values: - -| Read path | Value | -| --- | --- | -| Enterprise SQL | Raw payload bytes by default. | -| An SDK Arrow query in `"descriptions"` mode | Descriptor struct identifying the stored blob. Treat it as opaque. | -| `table.fetch_blobs(column, row_ids)` | Arrow `large_binary` array; `.to_pylist()` gives `bytes` or `None` in the requested order. | -| A Function parameter annotated `lancedb.BlobReader` | Lazy, seekable reader over the input blob, available inside the Function. | - -For an Enterprise source table, select the rows and fetch their bytes explicitly. -The following example copies up to 100 rows from an existing `images` table with -an integer `id` and a blob `image` column. Keep the source unchanged during this -operation: selection and fetching are separate requests. - -```python -import lancedb -import pyarrow as pa - -source = db.open_table("images") -hits = ( - source.search() - .where("id < 100") - .select(["id"]) - .with_row_id(True) - .limit(100) - .to_arrow() -) -payloads = source.fetch_blobs("image", hits["_rowid"]).to_pylist() -subset = db.create_table( - "image_subset", - schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), -) -if hits.num_rows: - subset.add([ - {"id": image_id, "image": payload} - for image_id, payload in zip(hits["id"].to_pylist(), payloads, strict=True) - ]) -``` - -Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches -for larger subsets; `fetch_blobs` materializes all requested bytes in memory. -For incremental decoding, use `fetch_blob_files` instead. - -{/* Draft for the Enterprise Python bytes release. Replace the copy example above when snapshot-bound remote bytes are released. - -For Enterprise tables, prefer server-side `CREATE TABLE AS SELECT` or -`INSERT INTO ... SELECT` to copy blobs without a client round trip: - -```sql -CREATE TABLE image_subset AS SELECT id, image FROM images WHERE id < 100; --- To append to an existing destination: -INSERT INTO image_subset SELECT id, image FROM images WHERE id >= 100 AND id < 200; -``` - -For SDK copies, query with `blob_mode="bytes"` to bind selection and payload -reads to one snapshot. The following example copies up to 100 rows from an -existing `images` table with an integer `id` and a blob `image` column. - -```python -import lancedb -import pyarrow as pa - -source = db.open_table("images") -hits = ( - source.search() - .where("id < 100") - .select(["id", "image"]) - .limit(100) - .to_arrow(blob_mode="bytes") -) -subset = db.create_table( - "image_subset", - schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), -) -if hits.num_rows: - subset.add(hits) -``` - -Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches -for larger subsets; `fetch_blobs` materializes all requested bytes in memory. -For incremental decoding, use `fetch_blob_files` instead. - -Remote bytes mode requires a server that supports snapshot-bound Blob reads. -Older servers and Realtime/MemWAL tables can still return descriptors, but -bytes mode raises an explicit unsupported-operation error before fetching payloads. -*/} +On Enterprise tables, call `table.search()` for `blob_mode="bytes"`. The sync +`Table.to_pandas()` and `Table.to_arrow()` conversions are unsupported. For +Realtime/MemWAL tables or historical versions without a native transaction +identity, request descriptors. In-memory tables and namespace `QueryTable` +pushdown do not support bytes mode. `blob_mode="bytes"` materializes top-level and struct-nested blob columns. It raises `ValueError` when the selected columns include blobs @@ -663,25 +592,13 @@ five-field descriptors. Both `"bytes"` and `"descriptions"` hide automatic row IDs; explicitly requested row IDs remain visible. Bytes mode has the same restrictions as `to_arrow(blob_mode="bytes")`, -including no blobs inside lists, Enterprise tables, namespace `QueryTable` -pushdown, or query shapes that cannot preserve their row results. Legacy v1 -bytes are limited to eligible local plain scans. If concurrent writers can -overwrite the table, use a separate reader checked out to a fixed version -before querying. Otherwise, an overwrite can invalidate the row IDs used to -fetch bytes and raise `ValueError`. - -{/* Draft for the Enterprise Python bytes release. Replace the streaming restrictions above after release. - -Bytes mode has the same restrictions as `to_arrow(blob_mode="bytes")`, -including no blobs inside lists, namespace `QueryTable` pushdown, or query -shapes that cannot preserve their row results. Enterprise queries require a -valid `x-lancedb-query-version` and `x-lancedb-query-snapshot` response headers. -Legacy v1 bytes are limited to -eligible local plain scans. For local queries, if concurrent writers can -overwrite the table, use a separate reader checked out to a fixed version -before querying. Otherwise, an overwrite can invalidate the row IDs used to -fetch bytes and raise `ValueError`. -*/} +including no blobs inside lists, in-memory tables, namespace `QueryTable` +pushdown, or query shapes that cannot preserve their row results. Each Enterprise +batch reads blob bytes from the snapshot that produced the rows. Legacy v1 +bytes are limited to eligible local plain scans. For +local queries, if concurrent writers can overwrite the table, use a separate +reader checked out to a fixed version before querying. Otherwise, an overwrite +can invalidate the row IDs used to fetch bytes and raise `ValueError`. ###### Optional pandas examples {#multimodal-blob-pandas} From a653d861ecb2cfa6d7ce37d5dab5e1e4fa213cb1 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 18 Nov 2026 16:15:42 +0800 Subject: [PATCH 11/78] fix(python): allow static diagnostic imports in Functions (#5084) Functions previously rejected every `sys` or `importlib` import even when the source only used a statically visible diagnostic. Allow exactly `sys.stderr`, `sys.version_info`, and `importlib.metadata.version`, with direct imports, `from` imports, and aliases treated identically whether they appear at module level or inside the function or class body. Every other use of a namespace-access module still fails at decoration. The error now names the rejected operation, such as `sys.modules`, and lists the supported diagnostic operations. Tests package and execute the artifact offline for each import form, and reject unsupported attributes, submodules, dynamic attribute access, and rebinding. ENT-3918. --- docs/src/python/python.md | 46 +++- docs/web/management/function.mdx | 19 ++ python/python/lancedb/functions.py | 247 +++++++++++++++--- .../python/tests/test_function_packaging.py | 142 +++++++++- 4 files changed, 407 insertions(+), 47 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index b7859c2f7..04f315e1c 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -481,19 +481,41 @@ scaler.close() ### Function packaging restrictions The decorator snapshots the Function's source and referenced globals into a new -module. It conservatively rejects imports of `sys`, `builtins`, `importlib`, -`inspect`, `gc`, `ctypes`, and `types`, including submodules such as `ctypes.util` -and `importlib.metadata`. This applies to imports inside function or class bodies -and references to module-level aliases. Even ordinary uses such as `sys.version` -and `ctypes.util.find_library` are blocked: these modules can reach names outside -the reconstructed Function namespace. References to `globals`, `locals`, `vars`, -`eval`, `exec`, `compile`, and `__import__` are rejected as dynamic namespace access. -These restrictions also apply to the deprecated `@udf` alias. +module. It supports three statically recognizable diagnostic operations: +`sys.stderr`, `sys.version_info`, and `importlib.metadata.version`. Direct +imports, `from` imports, and aliases are treated the same way, whether the +import appears inside a function or class body or at module level. -For legitimate uses, move the code into an importable helper module and ship it -with `code=`, or install its package with `pip=` or `conda=`. Imported helpers keep -their own namespace; the packager does not scan their bodies. Helpers defined in -`__main__` are copied by source and have the same restrictions as the Function. +Other imports of `sys`, `builtins`, `importlib`, `inspect`, `gc`, `ctypes`, and +`types`, including submodules such as `ctypes.util` and `importlib.resources`, +remain blocked. This applies to imports inside function or class bodies and +references to module-level aliases. Even ordinary uses such as `sys.version` +and `ctypes.util.find_library` are blocked: these modules can reach names +outside the reconstructed Function namespace. References to `globals`, `locals`, +`vars`, `eval`, `exec`, `compile`, and `__import__` are rejected as dynamic +namespace access. These restrictions also apply to the deprecated `@udf` alias. + +For example, a diagnostic Function can report its Python version and NumPy +version without a helper module: + +```python +import importlib.metadata +import sys + +from lancedb import function + + +@function(pip=["numpy"]) +def report(value: int) -> str: + print("diagnostic", file=sys.stderr) + return f"numpy {importlib.metadata.version('numpy')} on {sys.version_info}" +``` + +For other restricted uses, move the code into an importable helper module and +ship it with `code=`, or install its package with `pip=` or `conda=`. Imported +helpers keep their own namespace; the packager does not scan their bodies. +Helpers defined in `__main__` are copied by source and have the same +restrictions as the Function. For example, put this helper in `native_diagnostics/__init__.py`: diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 562de05c6..bc237d79e 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -767,6 +767,25 @@ seen and unsupported where it cannot: `globals()`, `eval`, `sys.modules`, `builtins`. Closures and a non-standard `__builtins__` are rejected outright. +Three statically recognizable diagnostic operations are supported: `sys.stderr`, +`sys.version_info`, and `importlib.metadata.version`. Direct imports, `from` +imports, and aliases work the same way. Any other use of `sys`, `builtins`, +`importlib`, `inspect`, `gc`, `ctypes`, or `types` is rejected; move it into an +importable helper module. + +```python +import importlib.metadata +import sys + +from lancedb import function + + +@function(pip=["numpy"]) +def report(value: int) -> str: + print("diagnostic", file=sys.stderr) + return f"numpy {importlib.metadata.version('numpy')} on {sys.version_info}" +``` + In practice this means a function should be self-contained: take its inputs as arguments, import what it needs at module level, and avoid capturing state from the surrounding scope. diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 5ea45a6a6..2d369e3ec 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -16,6 +16,7 @@ import builtins import base64 import functools import hashlib +import importlib.metadata import importlib.util import inspect import symtable @@ -2114,6 +2115,17 @@ def _python_extension_type(data_type: pa.DataType) -> Optional[pa.ExtensionType] _DYNAMIC_NAMESPACE_ACCESS = frozenset( {"globals", "locals", "vars", "eval", "exec", "compile", "__import__"} ) +# Static diagnostic operations the packager can reconstruct. Anything else that +# reaches through a namespace-access module remains unrepresentable. +_APPROVED_NAMESPACE_ATTRIBUTES = { + "sys": frozenset({"stderr", "version_info"}), + "importlib.metadata": frozenset({"version"}), +} +_APPROVED_NAMESPACE_OPERATIONS = ( + "sys.stderr", + "sys.version_info", + "importlib.metadata.version", +) # Modules that hand out namespaces (`sys.modules`, `builtins`, importers, # introspection). The artifact's module namespace holds only the names it was # packaged with, so reaching around it cannot be represented. @@ -2128,28 +2140,170 @@ _NAMESPACE_HELPER_HINT = ( ) +_APPROVED_NAMESPACE_HINT = ( + "The supported diagnostic operations are " + + ", ".join(_APPROVED_NAMESPACE_OPERATIONS) + + ". " +) + + +def _namespace_operation_error(operations: Sequence[str]) -> ValueError: + label = operations[0] if len(operations) == 1 else list(operations) + return ValueError( + f"@function cannot package namespace operation {label!r}. " + "The artifact's module namespace holds only the names it was packaged " + "with, so references that reach around it cannot be represented. " + + _APPROVED_NAMESPACE_HINT + + _NAMESPACE_HELPER_HINT + ) + + def _namespace_import_error(modules: Sequence[str]) -> ValueError: return ValueError( f"@function cannot package imports from namespace-access modules: {modules!r}. " f"Imports of {', '.join(sorted(_NAMESPACE_MODULES))} (including submodules) " "are blocked because they can access names outside the packaged " - "Function's reconstructed module namespace. " + _NAMESPACE_HELPER_HINT + "Function's reconstructed module namespace. " + + _APPROVED_NAMESPACE_HINT + + _NAMESPACE_HELPER_HINT ) -def _namespace_imports(definition: Union[ast.FunctionDef, ast.ClassDef]) -> list[str]: - found: set[str] = set() +def _namespace_import_bindings( + definition: Union[ast.FunctionDef, ast.ClassDef], +) -> tuple[dict[str, frozenset[str]], list[str], list[str]]: + """Return approved diagnostic bindings and rejected imports. + + A binding maps the local name an import creates to the attribute paths + that may be read through it. Rejected modules and operations are kept + separate so each error names the relevant rule. + """ + bindings: dict[str, frozenset[str]] = {} + blocked_modules: set[str] = set() + blocked_operations: set[str] = set() for node in ast.walk(definition): if isinstance(node, ast.Import): - found.update( - alias.name - for alias in node.names - if alias.name.split(".")[0] in _NAMESPACE_MODULES - ) - elif isinstance(node, ast.ImportFrom) and node.module: - if node.module.split(".")[0] in _NAMESPACE_MODULES: - found.add(node.module) - return sorted(found) + for alias in node.names: + root = alias.name.split(".")[0] + if root not in _NAMESPACE_MODULES: + continue + attributes = _APPROVED_NAMESPACE_ATTRIBUTES.get(alias.name) + if attributes is None: + blocked_modules.add(alias.name) + continue + if alias.asname: + name = alias.asname + bases = frozenset(f"{name}.{attribute}" for attribute in attributes) + else: + name = root + module = alias.name if "." in alias.name else name + bases = frozenset( + f"{module}.{attribute}" for attribute in attributes + ) + bindings[name] = bindings.get(name, frozenset()) | bases + elif ( + isinstance(node, ast.ImportFrom) + and node.level == 0 + and node.module + and node.module.split(".")[0] in _NAMESPACE_MODULES + ): + if node.module == "importlib": + for alias in node.names: + if alias.name == "metadata": + name = alias.asname or "metadata" + bindings[name] = bindings.get(name, frozenset()) | frozenset( + {f"{name}.version"} + ) + else: + blocked_modules.add("importlib") + continue + attributes = _APPROVED_NAMESPACE_ATTRIBUTES.get(node.module) + if attributes is None: + blocked_modules.add(node.module) + continue + for alias in node.names: + if alias.name in attributes: + name = alias.asname or alias.name + bindings[name] = bindings.get(name, frozenset()) | frozenset({name}) + else: + blocked_operations.add(f"{node.module}.{alias.name}") + return bindings, sorted(blocked_modules), sorted(blocked_operations) + + +def _namespace_binding_errors( + definition: Union[ast.FunctionDef, ast.ClassDef], + bindings: Mapping[str, frozenset[str]], +) -> list[str]: + """Operations that read a diagnostic binding outside its approved paths.""" + if not bindings: + return [] + parents: dict[ast.AST, ast.AST] = {} + for node in ast.walk(definition): + for child in ast.iter_child_nodes(node): + parents[child] = node + invalid: set[str] = set() + for node in ast.walk(definition): + if not isinstance(node, ast.Name): + continue + allowed = bindings.get(node.id) + if allowed is None: + continue + if not isinstance(node.ctx, ast.Load): + invalid.add(node.id) + continue + path = node.id + current: ast.AST = node + while True: + parent = parents.get(current) + if isinstance(parent, ast.Attribute) and parent.value is current: + path = f"{path}.{parent.attr}" + current = parent + continue + break + if not any(path == base or path.startswith(f"{base}.") for base in allowed): + invalid.add(path) + continue + if any(part.startswith("__") for part in path.split(".")[1:]): + invalid.add(path) + return sorted(invalid) + + +def _approved_global_namespace_binding( + definition: Optional[Union[ast.FunctionDef, ast.ClassDef]], + name: str, + value: Any, +) -> Optional[str]: + """The artifact import for an approved diagnostic global, if any.""" + if definition is None: + return None + if isinstance(value, types.ModuleType): + if value is sys: + bases = frozenset({f"{name}.stderr", f"{name}.version_info"}) + line = f"import sys as {name}" + elif value is importlib.metadata: + bases = frozenset({f"{name}.version"}) + line = f"import importlib.metadata as {name}" + elif value is importlib and name == "importlib": + # ``import importlib.metadata`` binds the top-level package name. + bases = frozenset({"importlib.metadata.version"}) + line = "import importlib.metadata" + else: + return None + elif value is sys.stderr: + bases = frozenset({name}) + line = f"from sys import stderr as {name}" + elif value is sys.version_info: + bases = frozenset({name}) + line = f"from sys import version_info as {name}" + elif value is importlib.metadata.version: + bases = frozenset({name}) + line = f"from importlib.metadata import version as {name}" + else: + return None + invalid = _namespace_binding_errors(definition, {name: bases}) + if invalid: + raise _namespace_operation_error(invalid) + return line def _module_references(module_source: str) -> set[str]: @@ -2462,14 +2616,21 @@ class _SourcePackager: "Function's reconstructed module namespace. Reference dependencies " "explicitly. " + _NAMESPACE_HELPER_HINT ) - namespace_imports = _namespace_imports(definition) - if namespace_imports: - raise _namespace_import_error(namespace_imports) + namespace_bindings, blocked_modules, blocked_operations = ( + _namespace_import_bindings(definition) + ) + if blocked_modules: + raise _namespace_import_error(blocked_modules) + if blocked_operations: + raise _namespace_operation_error(blocked_operations) + invalid_operations = _namespace_binding_errors(definition, namespace_bindings) + if invalid_operations: + raise _namespace_operation_error(invalid_operations) self._warn_unshipped_direct_imports(definition) self._packaged.add(id(target)) self._claim(target.__name__, ("definition", id(target))) if reader_name is not None: - self._bind(reader_name, BlobReader) + self._bind(reader_name, BlobReader, definition=definition) unresolved = [] for name in sorted(references): if name == target.__name__: @@ -2481,7 +2642,7 @@ class _SourcePackager: ) continue if name in namespace: - self._bind(name, namespace[name]) + self._bind(name, namespace[name], definition=definition) elif not hasattr(builtins, name): unresolved.append(name) if unresolved: @@ -2536,7 +2697,13 @@ class _SourcePackager: "name to different values" ) - def _bind(self, name: str, value: Any) -> None: + def _bind( + self, + name: str, + value: Any, + *, + definition: Optional[Union[ast.FunctionDef, ast.ClassDef]] = None, + ) -> None: if _packaged_by_source(value): if value.__name__ != name: raise ValueError( @@ -2547,14 +2714,23 @@ class _SourcePackager: self._definitions.append(self._definition(value, entry=False)) self._claim(name, ("definition", id(value))) return - line = self._global_source(name, value) + line = self._global_source(name, value, definition=definition) self._claim(name, line) self._imports[name] = line - def _global_source(self, name: str, value: Any) -> str: + def _global_source( + self, + name: str, + value: Any, + *, + definition: Optional[Union[ast.FunctionDef, ast.ClassDef]] = None, + ) -> str: """One module-level line that rebinds `name` to `value` in the artifact: an import for modules and importable classes/functions, a captured copy otherwise.""" + approved = _approved_global_namespace_binding(definition, name, value) + if approved is not None: + return approved if value is BlobReader: return f"from lance_blob import BlobReader as {name}" if isinstance(value, types.ModuleType): @@ -3440,20 +3616,25 @@ def function( values, such as instances of your own classes, inside the function or class body as well. - **Namespace restrictions.** The packaged source cannot import ``sys``, + **Namespace restrictions.** The packaged source may use three static + diagnostic operations: ``sys.stderr``, ``sys.version_info``, and + ``importlib.metadata.version``. Direct imports, ``from`` imports, and + aliases are treated the same way, whether the import appears inside the + function or class body or at module level. Any other import of ``sys``, ``builtins``, ``importlib``, ``inspect``, ``gc``, ``ctypes``, or ``types``, - including submodules such as ``ctypes.util`` and ``importlib.metadata``. - Referencing a module-level alias for one of these modules is also rejected. - References to ``globals``, ``locals``, ``vars``, ``eval``, ``exec``, - ``compile``, or ``__import__`` are rejected as dynamic namespace access. - These restrictions are conservative: even ordinary uses such as - ``ctypes.util.find_library`` or ``sys.version`` are blocked because these - modules can reach names outside the reconstructed Function namespace. - Move such code into an importable helper module supplied with ``code=``, - ``pip=``, or ``conda=``, then import and call the helper from the Function. - Helpers imported normally keep their own module namespace; these checks do - not scan their bodies. A helper defined in ``__main__`` is packaged by source - and is subject to the same checks. + including submodules such as ``ctypes.util``, ``importlib.resources``, and + ``importlib.import_module``, is rejected. Referencing a module-level alias + for an unapproved module or operation is also rejected. References to + ``globals``, ``locals``, ``vars``, ``eval``, ``exec``, ``compile``, or + ``__import__`` are rejected as dynamic namespace access. These + restrictions are conservative: even ordinary uses such as + ``ctypes.util.find_library`` or ``sys.version`` remain blocked because + these modules can reach names outside the reconstructed Function + namespace. Move such code into an importable helper module supplied with + ``code=``, ``pip=``, or ``conda=``, then import and call the helper from + the Function. Helpers imported normally keep their own module namespace; + these checks do not scan their bodies. A helper defined in ``__main__`` is + packaged by source and is subject to the same checks. Changing any packaged source, including a module in ``code``, produces a new Function version; the environment built from ``pip`` or ``conda`` is diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index ae74cc8cd..874dd809f 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -727,7 +727,6 @@ def test_nested_class_and_closure_are_rejected_with_the_reason(): @pytest.mark.parametrize( "module_name", [ - "sys", "builtins", "importlib", "inspect", @@ -735,7 +734,6 @@ def test_nested_class_and_closure_are_rejected_with_the_reason(): "ctypes", "types", "ctypes.util", - "importlib.metadata", ], ) @pytest.mark.parametrize("import_style", ["import", "from", "global"]) @@ -772,6 +770,146 @@ def test_namespace_module_errors_explain_the_rule_and_remedy( assert "dynamic namespace access" not in message +@pytest.mark.parametrize("module_level", [False, True], ids=["body", "module"]) +@pytest.mark.parametrize( + ("import_statement", "expression"), + [ + ("import sys", "sys.stderr"), + ("import sys as diagnostic", "diagnostic.stderr"), + ("from sys import stderr", "stderr"), + ("from sys import stderr as error_stream", "error_stream"), + ("import sys", "sys.version_info"), + ("import sys as diagnostic", "diagnostic.version_info"), + ("from sys import version_info", "version_info"), + ("from sys import version_info as python_version", "python_version"), + ("import importlib.metadata", "importlib.metadata.version('pytest')"), + ("import importlib.metadata as diagnostic", "diagnostic.version('pytest')"), + ("from importlib import metadata", "metadata.version('pytest')"), + ( + "from importlib import metadata as diagnostic", + "diagnostic.version('pytest')", + ), + ("from importlib.metadata import version", "version('pytest')"), + ( + "from importlib.metadata import version as diagnostic", + "diagnostic('pytest')", + ), + ], +) +def test_diagnostic_namespace_operations_package_and_run( + helper_package, module_level, import_statement, expression +): + if module_level: + source = ( + f"{import_statement}\n\n" + "def probe(value: str) -> str:\n" + f" return str({expression}) + value\n" + ) + else: + source = ( + "def probe(value: str) -> str:\n" + f" {import_statement}\n" + f" return str({expression}) + value\n" + ) + module = helper_package("fx_diagnostic_operation", {"__init__.py": source}) + + packaged = artifact(function(module.probe)).decode() + namespace = {} + exec(compile(packaged, "user_function.py", "exec"), namespace) + assert namespace["probe"]("!").endswith("!") + + +@pytest.mark.parametrize( + ("body", "operation"), + [ + ("import sys\nreturn str(sys.modules)", "sys.modules"), + ("import sys as s\nreturn str(s.path)", "s.path"), + ("import sys\nreturn str(sys.version)", "sys.version"), + ("import sys\nreturn str(sys.stdout)", "sys.stdout"), + ("import sys\nreturn str(getattr(sys, 'stderr'))", "sys"), + ("import sys\nstream = sys\nreturn str(stream)", "sys"), + ("import sys\nsys = object()\nreturn str(sys)", "sys"), + ("from sys import path\nreturn str(path)", "sys.path"), + ( + "import importlib.metadata\n" + "return importlib.metadata.distribution('pytest').version", + "importlib.metadata.distribution", + ), + ( + "import importlib.metadata as m\nreturn m.distribution('pytest').version", + "m.distribution", + ), + ( + "from importlib.metadata import distribution\n" + "return distribution('pytest').version", + "importlib.metadata.distribution", + ), + ( + "from importlib.metadata import version\nreturn str(version.__globals__)", + "version.__globals__", + ), + ( + "import importlib\nreturn str(importlib.import_module('os'))", + "importlib", + ), + ( + "from importlib import import_module\nreturn str(import_module('os'))", + "importlib", + ), + ( + "import importlib.resources\nreturn str(importlib.resources.files('x'))", + "importlib.resources", + ), + ("import inspect\nreturn str(inspect.currentframe())", "inspect"), + ( + "from ctypes import util\nreturn str(util.find_library('c'))", + "ctypes", + ), + ("import gc\nreturn str(gc.get_objects())", "gc"), + ("import builtins\nreturn str(builtins)", "builtins"), + ("import types\nreturn str(types.SimpleNamespace())", "types"), + ], +) +def test_unsupported_namespace_operations_are_rejected(helper_package, body, operation): + source = "def blocked(value: str) -> str:\n" + textwrap.indent(body, " ") + module = helper_package( + "fx_unsupported_namespace_operation", {"__init__.py": source} + ) + + with pytest.raises(ValueError) as error: + function(module.blocked) + message = str(error.value) + assert repr(operation) in message + assert "supported diagnostic operations" in message + + +@pytest.mark.parametrize( + ("preamble", "body", "operation"), + [ + ( + "import sys as diagnostic", + "return str(diagnostic.modules)", + "diagnostic.modules", + ), + ( + "import importlib.metadata as diagnostic", + "return diagnostic.distribution('pytest').version", + "diagnostic.distribution", + ), + ("from sys import stderr", "return str(stderr.__class__)", "stderr.__class__"), + ], +) +def test_module_level_diagnostic_alias_rejects_unsupported_use( + helper_package, preamble, body, operation +): + source = f"{preamble}\n\ndef blocked(value: str) -> str:\n {body}\n" + module = helper_package("fx_diagnostic_alias", {"__init__.py": source}) + + with pytest.raises(ValueError) as error: + function(module.blocked) + assert repr(operation) in str(error.value) + + @pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning") def test_udf_namespace_import_error_explains_the_helper_alternative(): with pytest.raises(ValueError, match="ctypes.util.*importable helper module"): From a98cffda4bc16e310bd8497bb138c58da651ab2d Mon Sep 17 00:00:00 2001 From: Lance Release Date: Wed, 18 Nov 2026 08:16:29 +0000 Subject: [PATCH 12/78] =?UTF-8?q?Bump=20version:=200.42.0-beta.19=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 6efd2bf48..ba0d4ebaf 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.19" +current_version = "0.42.0-beta.20" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 923b7e94e..44405cdf0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6005,7 +6005,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" dependencies = [ "ahash", "anyhow", @@ -6116,7 +6116,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" dependencies = [ "anyhow", "arrow-array", @@ -6159,7 +6159,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" dependencies = [ "arrow-array", "arrow-buffer", @@ -6185,7 +6185,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index f6e7497d0..bf733dd23 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.19 + 0.42.0-beta.20 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 5a49a1a60..e8b214d9f 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.19 + 0.42.0-beta.20 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 46d5fac54..06bfe4687 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.19 + 0.42.0-beta.20 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index d0d000e10..6de370ef1 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 4f6851519..572858a82 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.19", + "version": "0.42.0-beta.20", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index a4027033a..18bd9e1c4 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.19", + "version": "0.42.0-beta.20", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 49a50f33f..79671f79e 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.19", + "version": "0.42.0-beta.20", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 8f9f3ec18..6048d5def 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.19", + "version": "0.42.0-beta.20", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index bc32a415f..7c6e7d4a4 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.19", + "version": "0.42.0-beta.20", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 7e7db948b..917f779fb 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.19", + "version": "0.42.0-beta.20", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index e1cd2879e..97d3aec62 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.19", + "version": "0.42.0-beta.20", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index e040cb2b8..ae6debdd1 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.19", + "version": "0.42.0-beta.20", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 1b9c44290..8604daabf 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 97d2e732b..1d83c0cd4 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 8e0348a2b..11f1c9512 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" edition = "2021" license.workspace = true repository.workspace = true From 9f58d8aab62eaa053289a5abb0a9f9deff4b62d4 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 18 Nov 2026 17:19:02 +0800 Subject: [PATCH 13/78] docs: add an ordinary Blob v2 photo tutorial (#5087) The quickstart links to a Blob example that assumes both tables already exist. Replace that gap with a from-empty photo tutorial: generate real PNG files with the standard library, ingest an ordinary Blob v2 table, filter metadata, save and compare exact image bytes, then create and verify a filtered destination through Enterprise SQL or an Embedded materialized copy. Keep Early access and distinguish Enterprise 1.12.0 row-ID fetches from deployment-dependent snapshot-bound reads. Cover source stability, range reads and Function readers for large media, ambiguous write recovery, and the absence of a SQL constructor for uploading client-side files. The executable Embedded workflow passed on Python SDK 0.42.0b17 using disposable local storage. Generated snippets, MDX compilation, combined-site `mint validate`, and `mint broken-links --check-anchors --check-redirects` passed. Enterprise connection/SQL examples were checked against the public API and existing 1.12 documentation but were not executed against an Enterprise deployment; this does not establish SQL copy behavior after source cleanup. No saved editions or publication state change. Fixes [OSS-3102](https://linear.app/lancedb/issue/OSS-3102/walk-users-from-image-files-to-a-filtered-blob-v2-table-copy). --- .../blob-v2/py/test_photo_tutorial.py | 149 ++++++++++++ docs/web/management/table.mdx | 226 ++++++++++++++---- docs/web/quickstart.mdx | 6 +- docs/web/snippets/photo_tutorial.mdx | 21 ++ 4 files changed, 356 insertions(+), 46 deletions(-) create mode 100644 docs/web-tests/blob-v2/py/test_photo_tutorial.py create mode 100644 docs/web/snippets/photo_tutorial.mdx diff --git a/docs/web-tests/blob-v2/py/test_photo_tutorial.py b/docs/web-tests/blob-v2/py/test_photo_tutorial.py new file mode 100644 index 000000000..0a33db8a1 --- /dev/null +++ b/docs/web-tests/blob-v2/py/test_photo_tutorial.py @@ -0,0 +1,149 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + + +def test_photo_tutorial(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + # --8<-- [start:photo_files] + import struct + import zlib + from pathlib import Path + + def solid_png(rgb): + def chunk(kind, data): + checksum = zlib.crc32(kind + data) & 0xFFFFFFFF + return ( + struct.pack(">I", len(data)) + kind + data + struct.pack(">I", checksum) + ) + + header = struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0) + pixels = (b"\x00" + bytes(rgb) * 8) * 8 + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", header) + + chunk(b"IDAT", zlib.compress(pixels)) + + chunk(b"IEND", b"") + ) + + inputs = Path("photo-inputs") + inputs.mkdir() + for label, rgb in [("red", (255, 0, 0)), ("blue", (0, 0, 255))]: + (inputs / f"{label}.png").write_bytes(solid_png(rgb)) + # --8<-- [end:photo_files] + + # --8<-- [start:photo_connect_embedded] + import lancedb + + db = lancedb.connect("./photo-db") + # --8<-- [end:photo_connect_embedded] + + # --8<-- [start:photo_ingest] + import pyarrow as pa + + schema = pa.schema( + [ + pa.field("id", pa.int64(), nullable=False), + pa.field("label", pa.string(), nullable=False), + lancedb.blob("image", nullable=False), + ], + metadata={"lance.blob.managed": "false"}, + ) + photos = db.create_table("photos", schema=schema) + photos.add( + [ + {"id": 1, "label": "red", "image": (inputs / "red.png").read_bytes()}, + {"id": 2, "label": "blue", "image": (inputs / "blue.png").read_bytes()}, + ] + ) + assert photos.count_rows() == 2 + # --8<-- [end:photo_ingest] + + # --8<-- [start:photo_fetch] + hits = ( + photos.search() + .where("label = 'red'") + .select(["id", "label"]) + .with_row_id(True) + .limit(10) + .to_list() + ) + assert [row["id"] for row in hits] == [1] + payloads = photos.fetch_blobs("image", [row["_rowid"] for row in hits]).to_pylist() + assert payloads == [(inputs / "red.png").read_bytes()] + saved = Path("selected-red.png") + saved.write_bytes(payloads[0]) + assert saved.read_bytes() == (inputs / "red.png").read_bytes() + # --8<-- [end:photo_fetch] + + # --8<-- [start:photo_bytes] + rows = ( + photos.search() + .where("label = 'red'") + .select(["id", "image"]) + .limit(10) + .to_list(blob_mode="bytes") + ) + assert rows == [{"id": 1, "image": (inputs / "red.png").read_bytes()}] + # --8<-- [end:photo_bytes] + + # --8<-- [start:photo_ranges] + with photos.fetch_blob_files("image", [hits[0]["_rowid"]])[0] as reader: + assert reader.read_range(0, 8) == b"\x89PNG\r\n\x1a\n" + # --8<-- [end:photo_ranges] + + # --8<-- [start:photo_copy_embedded] + selected = ( + photos.search() + .where("label = 'red'") + .select(["id", "label", "image"]) + .limit(10) + .to_arrow(blob_mode="bytes") + ) + db.create_table("photo_subset", data=selected, schema=schema) + # --8<-- [end:photo_copy_embedded] + + # --8<-- [start:photo_verify] + photo_subset = db.open_table("photo_subset") + assert photo_subset.count_rows() == 1 + copied = ( + photo_subset.search() + .select(["id", "label"]) + .with_row_id(True) + .limit(10) + .to_list() + ) + assert [(row["id"], row["label"]) for row in copied] == [(1, "red")] + copied_bytes = photo_subset.fetch_blobs( + "image", [row["_rowid"] for row in copied] + ).to_pylist() + assert copied_bytes == [(inputs / "red.png").read_bytes()] + # --8<-- [end:photo_verify] + + +def enterprise_connection(): + # --8<-- [start:photo_connect_enterprise] + import os + + import lancedb + + db = lancedb.connect( + os.environ["LANCEDB_URI"], + api_key=os.environ["LANCEDB_API_KEY"], + region=os.environ["LANCEDB_REGION"], + host_override=os.environ["LANCEDB_HOST_OVERRIDE"], + sql_host_override=os.environ["LANCEDB_SQL_HOST_OVERRIDE"], + ) + # --8<-- [end:photo_connect_enterprise] + return db + + +def copy_with_enterprise_sql(db): + # --8<-- [start:photo_copy_sql] + db.execute_query( + "CREATE TABLE photo_subset (id BIGINT, label VARCHAR, image BLOB)" + ).read_all() + db.execute_query( + "INSERT INTO photo_subset (id, label, image) " + "SELECT id, label, image FROM photos WHERE label = 'red'" + ).read_all() + # --8<-- [end:photo_copy_sql] diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index c24b08b4a..dba741c2b 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -141,6 +141,19 @@ import { PyQueryToPandasKwargs as QueryToPandasKwargs, } from '/snippets/blob_pylance.mdx'; +import { + PyPhotoFiles, + PyPhotoConnectEmbedded, + PyPhotoConnectEnterprise, + PyPhotoIngest, + PyPhotoFetch, + PyPhotoBytes, + PyPhotoRanges, + PyPhotoCopyEmbedded, + PyPhotoCopySql, + PyPhotoVerify, +} from '/snippets/photo_tutorial.mdx'; + A table stores data in rows and columns and keeps a history of committed versions. Queries read table data, writes update it, and indexes accelerate searches over its columns.{/* Draft until branching reaches early access: restore "Branches let you make changes separately from the @@ -393,60 +406,183 @@ Blob v2 GA supports standard tables. Tables with Realtime or MemWAL enabled are outside the GA support scope. */} -Suppose your Enterprise database has a `photos` table with an integer `id` and a -Blob v2 column named `image`. Set `LANCEDB_URI`, `LANCEDB_API_KEY`, and -`LANCEDB_HOST_OVERRIDE` to your database URI, API key, and HTTPS endpoint. -See [Connect to LanceDB Enterprise](/basics/catalog#enterprise). +#### From image files to a filtered table {#photo-tutorial} -An SDK query normally returns a descriptor with the blob's location and size. -Pass `blob_mode="bytes"` to get the actual image in the same query. Each result -contains Python `bytes`, or `None` for a null image. +Start in an empty working directory and an empty database. This Python tutorial +creates `photos` with `id`, `label`, and Blob v2 `image` columns, saves one +matching image, and copies that row into a fresh `photo_subset` table. It uses +ordinary tables, with Realtime Engine disabled. Avoid other writers while +running the examples. -```python -import os -import lancedb +Install a Python SDK that provides `lancedb.blob`. For preview builds, use the +[installation instructions](/quickstart#python-pre-release-builds). The examples +need `lancedb` and `pyarrow`; generating the images uses only Python's standard +library. -db = lancedb.connect( - os.environ["LANCEDB_URI"], - api_key=os.environ["LANCEDB_API_KEY"], - host_override=os.environ["LANCEDB_HOST_OVERRIDE"], -) -rows = ( - db.open_table("photos").search() - .where("id < 100") - .select(["id", "image"]) - .limit(10) - .to_list(blob_mode="bytes") -) -for row in rows: - image = row["image"] - print(row["id"], len(image) if image is not None else None) -``` +##### 1. Create two image files {#photo-files} -Use this mode with a Python SDK and Enterprise deployment that support -snapshot-bound blob reads. The bytes come from the same table version as the -filtered rows. Keep that version available until the read finishes. On -Enterprise 1.12.0, or when you already have row IDs, use `fetch_blobs()`. -Keep the source unchanged between selecting the IDs and fetching their bytes. -Inside a LanceDB Function, a parameter annotated with `lancedb.BlobReader` -lets the function seek and read the input on demand. -[Fetch blobs by row ID](#multimodal-read-blobs) · [Troubleshoot Enterprise blob reads](/deployment/support#blob-query-bytes) +Generate tiny red and blue PNG images with known pixel contents. Open these +files in an image viewer. To use your own photos later, replace the file paths +and the expected bytes in the checks. + + + + {PyPhotoFiles} + + + +##### 2. Choose a connection {#photo-connection} + +For LanceDB Embedded, create a local database: + + + + {PyPhotoConnectEmbedded} + + + +For LanceDB Enterprise, use an empty development database where you can create +ordinary tables. Get the API and Flight SQL endpoints from your administrator; +set these environment variables using the +[Enterprise connection instructions](/basics/catalog#enterprise) and +[SQL connection settings](/basics/sql#sql-is-remote). Choose this connection +instead of the Embedded connection to run the SQL copy later: + + + + {PyPhotoConnectEnterprise} + + + +##### 3. Define the schema and insert the images {#photo-ingest} + +The explicit schema makes `image` a Blob v2 field. The table metadata opts into +ordinary Blob storage. Table creation fails if `photos` already exists; use a +new database for another run. + + + + {PyPhotoIngest} + + + + +If table creation or ingestion loses its response, check whether `photos` +exists and inspect its IDs and image bytes before repeating the write. An +ambiguous result can mean the write committed. Repeating `add` can duplicate +rows. See [write recovery](/ingestion/insert#performance) and +[large upload recovery](/ingestion/insert#bulk-ingests-into-a-remote-table). + + +##### 4. Filter metadata, save an image, and check its contents {#photo-read} + +First select at most ten matching rows without loading their images. Fetch only +those rows' bytes, save the red image, and compare the complete saved file with +the original. This row-ID path works with Enterprise 1.12.0: + + + + {PyPhotoFetch} + + + +`id` is the application's photo ID; `_rowid` is the table's row identifier used +by `fetch_blobs`. Keep the source unchanged between the metadata query and the +fetch. Row IDs alone do not bind the fetch to the query's snapshot. Stable row +IDs across compaction do not protect against an overwrite or a same-name table +replacement. + +With a Python SDK and Enterprise deployment that support **snapshot-bound blob +reads**, request the bytes in the query instead: + + + + {PyPhotoBytes} + + + +The bytes then come from the same table version as the filtered rows. Keep that +version available until the read finishes. Enterprise 1.12.0 users should use +the row-ID example above; support for snapshot-bound reads depends on both the +SDK and the serving deployment. See +[troubleshoot Enterprise blob reads](/deployment/support#blob-query-bytes). +LanceDB Embedded also supports this query mode; use a reader checked out to a +fixed version if concurrent writers can overwrite the source. + +##### Choose a read method for larger media {#photo-read-method} + +| Task | Method | +| --- | --- | +| Save a small, bounded set of complete images | `fetch_blobs`, or query with `blob_mode="bytes"` on a supporting deployment | +| Read a header or part of a large video | `fetch_blob_files`, then `read_range` or `read_ranges` | +| Seek through a video in server-side processing | A LanceDB Function parameter annotated with `lancedb.BlobReader` | +| Copy rows inside Enterprise | SQL `INSERT INTO ... SELECT`, without downloading images to the client | + +A row limit bounds the number of images, not their total size. Avoid fetching +whole videos just to inspect their headers. Here is a range read against the +same red PNG; it verifies the eight-byte PNG signature: + + + + {PyPhotoRanges} + + + +For multiple slices, see [range reads](#multimodal-read-blobs). For a seekable +video reader inside a Function, see +[read a blob incrementally](/curation/create-function#incremental). #### Copy a subset of blob rows {#multimodal-copy-subset} -To copy images within the same Enterprise database, run the filter on the -server. This example appends matching rows to an existing `photo_subset` -table with the same `id` and blob `image` columns. +Continue with the same `photos`, selecting the same red image. Choose one copy +path below, then run the shared verification. Neither path overwrites an +existing `photo_subset`. -```sql -INSERT INTO photo_subset (id, image) -SELECT id, image FROM photos WHERE id < 100; -``` +##### Enterprise SQL {#photo-copy-sql} -In Enterprise 1.12.0, selecting a Blob v2 column directly in SQL returns the -payload as `large_binary`. Use `blob_descriptor(image)` when you want storage -metadata. For a copy, select `image` itself. -[SQL blob descriptors](/sql/dql/blob-descriptor) +On the Enterprise connection, create a fresh destination with a Blob column, +then copy matching rows on the server. `execute_query` submits one statement +per call; consume each result before continuing: + + + + {PyPhotoCopySql} + + + +Enterprise 1.12.0 supports this SQL copy. Selecting a Blob v2 column directly +in SQL returns the payload as `large_binary`. Select `image` itself for the +copy; use [`blob_descriptor(image)`](/sql/dql/blob-descriptor) to inspect storage +metadata instead. + +`lancedb.blob("image")` is a Python schema helper, not a SQL value constructor. +SQL has no `blob(local_path)` constructor to upload a client-side image file. +Ingest file bytes with the SDK as above, then use SQL to copy stored rows. +If the copy response is lost, inspect `photo_subset` before repeating the +`INSERT`; the same [write recovery rules](/ingestion/insert#performance) apply. + +##### LanceDB Embedded {#photo-copy-embedded} + +SQL requires Enterprise. With the Embedded connection, materialize this small +selection and give the destination the explicit Blob schema: + + + + {PyPhotoCopyEmbedded} + + + +##### Verify the destination {#photo-copy-verify} + +Reopen `photo_subset`, check its row count and application ID, and compare its +image bytes with the original local file. The destination has its own row IDs, +so query them again instead of reusing the source's `_rowid` values: + + + + {PyPhotoVerify} + + #### Blob storage layouts {#blob-storage-layouts} diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index 12c9f87ca..dda4d9acc 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -367,7 +367,11 @@ Store images, audio, or other binary data alongside vectors and metadata, in a c -See [Multimodal data types](/management/table#multimodal) for larger payloads and the Blob v2 column type, which avoids loading binary data on every scan. +For image files and larger payloads, follow the +[Blob photo tutorial](/management/table#photo-tutorial) to create an ordinary +Blob table, filter its metadata, save and check an image, and copy matching rows. +It includes an Embedded path and an Enterprise SQL path. Blob columns are in +Early access. ## 8\. Train on your data {#8-train} diff --git a/docs/web/snippets/photo_tutorial.mdx b/docs/web/snippets/photo_tutorial.mdx new file mode 100644 index 000000000..9c68d6c67 --- /dev/null +++ b/docs/web/snippets/photo_tutorial.mdx @@ -0,0 +1,21 @@ +{/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} + +export const PyPhotoBytes = "rows = (\n photos.search()\n .where(\"label = 'red'\")\n .select([\"id\", \"image\"])\n .limit(10)\n .to_list(blob_mode=\"bytes\")\n)\nassert rows == [{\"id\": 1, \"image\": (inputs / \"red.png\").read_bytes()}]\n"; + +export const PyPhotoConnectEmbedded = "import lancedb\n\ndb = lancedb.connect(\"./photo-db\")\n"; + +export const PyPhotoConnectEnterprise = "import os\n\nimport lancedb\n\ndb = lancedb.connect(\n os.environ[\"LANCEDB_URI\"],\n api_key=os.environ[\"LANCEDB_API_KEY\"],\n region=os.environ[\"LANCEDB_REGION\"],\n host_override=os.environ[\"LANCEDB_HOST_OVERRIDE\"],\n sql_host_override=os.environ[\"LANCEDB_SQL_HOST_OVERRIDE\"],\n)\n"; + +export const PyPhotoCopyEmbedded = "selected = (\n photos.search()\n .where(\"label = 'red'\")\n .select([\"id\", \"label\", \"image\"])\n .limit(10)\n .to_arrow(blob_mode=\"bytes\")\n)\ndb.create_table(\"photo_subset\", data=selected, schema=schema)\n"; + +export const PyPhotoCopySql = "db.execute_query(\n \"CREATE TABLE photo_subset (id BIGINT, label VARCHAR, image BLOB)\"\n).read_all()\ndb.execute_query(\n \"INSERT INTO photo_subset (id, label, image) \"\n \"SELECT id, label, image FROM photos WHERE label = 'red'\"\n).read_all()\n"; + +export const PyPhotoFetch = "hits = (\n photos.search()\n .where(\"label = 'red'\")\n .select([\"id\", \"label\"])\n .with_row_id(True)\n .limit(10)\n .to_list()\n)\nassert [row[\"id\"] for row in hits] == [1]\npayloads = photos.fetch_blobs(\"image\", [row[\"_rowid\"] for row in hits]).to_pylist()\nassert payloads == [(inputs / \"red.png\").read_bytes()]\nsaved = Path(\"selected-red.png\")\nsaved.write_bytes(payloads[0])\nassert saved.read_bytes() == (inputs / \"red.png\").read_bytes()\n"; + +export const PyPhotoFiles = "import struct\nimport zlib\nfrom pathlib import Path\n\ndef solid_png(rgb):\n def chunk(kind, data):\n checksum = zlib.crc32(kind + data) & 0xFFFFFFFF\n return (\n struct.pack(\">I\", len(data)) + kind + data + struct.pack(\">I\", checksum)\n )\n\n header = struct.pack(\">IIBBBBB\", 8, 8, 8, 2, 0, 0, 0)\n pixels = (b\"\\x00\" + bytes(rgb) * 8) * 8\n return (\n b\"\\x89PNG\\r\\n\\x1a\\n\"\n + chunk(b\"IHDR\", header)\n + chunk(b\"IDAT\", zlib.compress(pixels))\n + chunk(b\"IEND\", b\"\")\n )\n\ninputs = Path(\"photo-inputs\")\ninputs.mkdir()\nfor label, rgb in [(\"red\", (255, 0, 0)), (\"blue\", (0, 0, 255))]:\n (inputs / f\"{label}.png\").write_bytes(solid_png(rgb))\n"; + +export const PyPhotoIngest = "import pyarrow as pa\n\nschema = pa.schema(\n [\n pa.field(\"id\", pa.int64(), nullable=False),\n pa.field(\"label\", pa.string(), nullable=False),\n lancedb.blob(\"image\", nullable=False),\n ],\n metadata={\"lance.blob.managed\": \"false\"},\n)\nphotos = db.create_table(\"photos\", schema=schema)\nphotos.add(\n [\n {\"id\": 1, \"label\": \"red\", \"image\": (inputs / \"red.png\").read_bytes()},\n {\"id\": 2, \"label\": \"blue\", \"image\": (inputs / \"blue.png\").read_bytes()},\n ]\n)\nassert photos.count_rows() == 2\n"; + +export const PyPhotoRanges = "with photos.fetch_blob_files(\"image\", [hits[0][\"_rowid\"]])[0] as reader:\n assert reader.read_range(0, 8) == b\"\\x89PNG\\r\\n\\x1a\\n\"\n"; + +export const PyPhotoVerify = "photo_subset = db.open_table(\"photo_subset\")\nassert photo_subset.count_rows() == 1\ncopied = (\n photo_subset.search()\n .select([\"id\", \"label\"])\n .with_row_id(True)\n .limit(10)\n .to_list()\n)\nassert [(row[\"id\"], row[\"label\"]) for row in copied] == [(1, \"red\")]\ncopied_bytes = photo_subset.fetch_blobs(\n \"image\", [row[\"_rowid\"] for row in copied]\n).to_pylist()\nassert copied_bytes == [(inputs / \"red.png\").read_bytes()]\n"; From a6d7d02f71fe76654d4f403d814effb44175d9ba Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 18 Nov 2026 01:19:59 -0800 Subject: [PATCH 14/78] docs: add semantic sampling guide (#5085) Add a standalone Semantic Sampling guide immediately below Statistical Sampling in Data Curation, with links from the curation overview and SQL sampling reference. Explain per-partition row quotas, repeatability, filtering order, and index requirements. ```sql SELECT id, caption FROM documents TABLESAMPLE IVF (embedding, 100 ROWS) REPEATABLE (42); ``` --- docs/web/curation/index.mdx | 1 + docs/web/curation/semantic-sampling.mdx | 121 +++++++++++++++++++++ docs/web/curation/statistical-sampling.mdx | 2 + docs/web/docs.json | 1 + docs/web/sql/dql/sampling.mdx | 3 + 5 files changed, 128 insertions(+) create mode 100644 docs/web/curation/semantic-sampling.mdx diff --git a/docs/web/curation/index.mdx b/docs/web/curation/index.mdx index 59b993100..290eb19fe 100644 --- a/docs/web/curation/index.mdx +++ b/docs/web/curation/index.mdx @@ -24,6 +24,7 @@ records belong, and save the selected data or the rules used to produce it. | [Scope to what changed](/curation/changes) | How to process only the rows added since your last run. | | [Profile a dataset](/curation/aggregate) | Whether coverage, missing values and class balance suit the task. | | [Statistical Sampling](/curation/statistical-sampling) | Which random fraction to inspect or use for an experiment. | +| [Semantic Sampling](/curation/semantic-sampling) | How to draw rows from every cluster in an existing IVF vector index. | | [Selective Sampling](/curation/selective-sampling) | How to re-fetch specific rows by ID, address or offset. | | [Join datasets](/curation/join) | How to attach labels, metadata or scores stored elsewhere. | | [Rank and deduplicate](/curation/windowing) | Which records to keep when several share an explicit key. | diff --git a/docs/web/curation/semantic-sampling.mdx b/docs/web/curation/semantic-sampling.mdx new file mode 100644 index 000000000..f51f68d6b --- /dev/null +++ b/docs/web/curation/semantic-sampling.mdx @@ -0,0 +1,121 @@ +--- +title: "Semantic Sampling" +sidebarTitle: "Semantic Sampling" +description: "Sample rows from every cluster in an existing IVF vector index with SQL TABLESAMPLE IVF." +icon: circle-nodes +keywords: ["semantic sampling", "sampling", "tablesample", "ivf", "clusters", "embeddings", "repeatable"] +availability: + embedded: unavailable + enterprise: available +--- + +Semantic sampling draws rows from every partition of an existing IVF vector +index. Each partition acts as a cluster of similar embeddings. Use it to +inspect examples across your embedding space, build a dataset with broader +topic coverage, or try an expensive operation on examples from each cluster. +The clusters reflect your embeddings and index; they do not guarantee +coverage of every label or topic. + +## Sample rows from every cluster {#sample} + +Connect with an [Enterprise SQL client](/basics/sql). The examples assume a +`documents` table with `id`, `caption`, and `embedding` columns. The +`embedding` column must have an up-to-date, single-segment +[IVF vector index](/indexing/vector-index) that includes every live row. +Wait for the index build to finish before sampling. + + +```sql SQL icon="database" +SELECT id, caption +FROM documents +TABLESAMPLE IVF (embedding, 100 ROWS) +REPEATABLE (42); +``` + + +This selects up to **100 rows from each IVF partition**, without replacement. +A partition with fewer than 100 rows contributes all its rows; empty +partitions contribute none. The result contains the table's existing columns, +so you can project the fields you need without returning `embedding`. + +The count is per partition, not a limit on the whole result. For example: + +| Rows in a partition | Rows selected with `100 ROWS` | +| --- | --- | +| 5 | 5 | +| 100 | 100 | +| 1,000 | 100 | + +With 1,024 populated partitions, the query returns at most 102,400 rows. +Choose the quota with the number of partitions and your output budget in mind. + +Equal quotas give sparse clusters more weight relative to their size. +This makes semantic sampling useful for cluster coverage, but the resulting +sample does not preserve the table's overall distribution. Use +[Statistical Sampling](/curation/statistical-sampling) for uniform row +sampling or account for the different sampling probabilities when estimating +whole-table statistics. + +To group records by partition or select a subset of whole partitions, use +[`ivf_partition()`](/sql/dql/ivf-partition) instead. Its `count` argument +selects the number of partitions; `TABLESAMPLE IVF` selects rows within +every partition. + +## Repeat a sample {#repeatable} + +`REPEATABLE (42)` fixes the seed. With the same table snapshot, index, and +seed, repeated queries select the same rows. Output order is unspecified. +Omit `REPEATABLE` to draw a new sample each time. + +Changes to the source data or rebuilding the index can change the selected +rows even with the same seed. Save a sample when you need a fixed dataset +for evaluation or comparison: + + +```sql SQL icon="database" +CREATE TABLE semantic_eval AS +SELECT id, caption, embedding +FROM documents +TABLESAMPLE IVF (embedding, 100 ROWS) +REPEATABLE (42); +``` + + +Create the output once with a fresh name and keep it unchanged. Record the +source version and sampling policy alongside the result. + +## Filter sampled rows {#filters} + +Sampling happens before `WHERE`, joins, aggregation, and an outer `LIMIT`. +For example, this draws up to 100 rows per partition and then removes rows +with missing captions: + + +```sql SQL icon="database" +SELECT id, caption +FROM documents +TABLESAMPLE IVF (embedding, 100 ROWS) +REPEATABLE (42) +WHERE caption IS NOT NULL; +``` + + +The result can contain fewer than 100 rows from a partition after filtering. +If you need a quota from an eligible subset, first save that subset as a +base table and build its IVF index before sampling it. + +## Requirements and limits {#requirements} + +| Requirement | Behavior | +| --- | --- | +| Source | Sample a base table directly. Views, derived relations, WAL-backed tables, and `CHANGES` relations are unsupported. | +| Vector column | Name the indexed vector column directly, rather than an expression. | +| Index | Exactly one eligible IVF index segment must cover every current fragment and assign every live row exactly once. Missing, ambiguous, or stale indexes are rejected. | +| New or unindexed rows | Rebuild the index so all live rows are covered by a single segment. Null vectors omitted by the index also prevent complete coverage. | +| Deleted rows | Tables with deletion vectors are rejected. Compact deleted rows and rebuild the IVF index before sampling. | +| Row count and seed | Use nonnegative integer literals. A count of zero returns no rows. This mode accepts row counts, not percentages. | + +Sampling examines the membership of every partition and fetches projected +data for the selected rows. A small quota limits the result size, but does +not limit index reads to that many entries. Large partitions can still +require substantial index reads and memory. diff --git a/docs/web/curation/statistical-sampling.mdx b/docs/web/curation/statistical-sampling.mdx index fc43bff12..2d37cefe1 100644 --- a/docs/web/curation/statistical-sampling.mdx +++ b/docs/web/curation/statistical-sampling.mdx @@ -16,6 +16,8 @@ statistics without reading every row. For a random subset through the Python SDK instead -- in Embedded or Enterprise -- see [Permutation](/training/permutation). To select specific, known rows rather than a random fraction, see [Selective Sampling](/curation/selective-sampling). +To draw rows from every cluster of an existing vector index, use +[Semantic Sampling](/curation/semantic-sampling). ## Example data {#example-data} diff --git a/docs/web/docs.json b/docs/web/docs.json index 4c800d65a..b561346cd 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -450,6 +450,7 @@ "curation/create-function", "curation/chunking", "curation/statistical-sampling", + "curation/semantic-sampling", "curation/selective-sampling", "curation/aggregate", "curation/join", diff --git a/docs/web/sql/dql/sampling.mdx b/docs/web/sql/dql/sampling.mdx index b6b24f8eb..c84caccc1 100644 --- a/docs/web/sql/dql/sampling.mdx +++ b/docs/web/sql/dql/sampling.mdx @@ -22,6 +22,9 @@ SELECT * FROM documents TABLESAMPLE (500 ROWS) -- 500 rows A bare number is a **percentage**. Add `ROWS` for a count instead. +To sample rows independently from every partition of an IVF vector index, +use [`TABLESAMPLE IVF`](/curation/semantic-sampling). + ## Rows or fragments {#methods} The standard calls these two methods of one clause. They are different From dd69a2c5350b6f097bfb9493b3926962ae0b5889 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Wed, 18 Nov 2026 08:40:53 -0800 Subject: [PATCH 15/78] feat(cli): install release binaries with a shell script (#5082) Install the public CLI from GitHub Releases with `sh scripts/install.sh`. The script selects the macOS Apple Silicon or Linux ARM64/x86-64 archive, verifies its SHA-256 and reported version, and installs it under the user's home directory. Set `LANCEDB_VERSION` to pin a release, including a beta. The default resolves GitHub's latest stable tag, which must have CLI assets. If an Enterprise or other `lancedb` is already on PATH, the installer asks for a separate install directory. An existing destination (including a symlink) is always preserved. The installer workflow exercises that same release on all three native targets and checks checksum failures and existing executable handling. --- .github/workflows/cli-installer.yml | 32 ++++++++++ ci/tests/test_cli_installer.sh | 42 +++++++++++++ docs/web/tools/cli.mdx | 15 +++++ scripts/install.sh | 98 +++++++++++++++++++++++++++++ 4 files changed, 187 insertions(+) create mode 100644 .github/workflows/cli-installer.yml create mode 100644 ci/tests/test_cli_installer.sh create mode 100755 scripts/install.sh diff --git a/.github/workflows/cli-installer.yml b/.github/workflows/cli-installer.yml new file mode 100644 index 000000000..92dbfe9a7 --- /dev/null +++ b/.github/workflows/cli-installer.yml @@ -0,0 +1,32 @@ +name: CLI shell installer +on: + pull_request: + paths: + - 'scripts/install.sh' + - 'ci/tests/test_cli_installer.sh' + - '.github/workflows/cli-installer.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + install: + strategy: + fail-fast: false + matrix: + os: [ubuntu-24.04, ubuntu-24.04-arm, macos-15] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - run: sh ci/tests/test_cli_installer.sh + - name: Install a pinned public release and run it + env: + LANCEDB_VERSION: v0.42.0-beta.19 + run: | + export LANCEDB_INSTALL_DIR="$RUNNER_TEMP/cli bin" + sh scripts/install.sh + test "$("$LANCEDB_INSTALL_DIR/lancedb" --version)" = "lancedb ${LANCEDB_VERSION#v}" + "$LANCEDB_INSTALL_DIR/lancedb" profile list diff --git a/ci/tests/test_cli_installer.sh b/ci/tests/test_cli_installer.sh new file mode 100644 index 000000000..5298530a9 --- /dev/null +++ b/ci/tests/test_cli_installer.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# Run from repository root. The fake transport serves a deliberately corrupt archive. +set -eu +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +export HOME="$work/home" LANCEDB_VERSION=v0.42.0-beta.19 +unset LANCEDB_INSTALL_DIR +mkdir -p "$work/bin" "$HOME" +export PATH="$work/bin:$PATH" +cat > "$work/bin/curl" <<'MOCK' +#!/bin/sh +while [ "$1" != -o ]; do shift; done +case "$3" in + */SHA256SUMS) + for target in x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu aarch64-apple-darwin; do + printf '%064d lancedb-%s-%s.tar.gz\n' 0 "$LANCEDB_VERSION" "$target" + done > "$2" ;; + *) printf 'corrupt archive' > "$2" ;; +esac +MOCK +chmod +x "$work/bin/curl" +reject() { + if sh scripts/install.sh > "$work/log" 2>&1; then + echo "Unexpected install success" >&2 + exit 1 + fi + grep -F "$1" "$work/log" +} + +printf 'existing admin CLI\n' > "$work/bin/lancedb" +chmod +x "$work/bin/lancedb" +reject 'on PATH' +test ! -e "$HOME/.local/bin/lancedb" +export LANCEDB_INSTALL_DIR="$work/separate bin" +mkdir -p "$LANCEDB_INSTALL_DIR" +ln -s "$work/bin/lancedb" "$LANCEDB_INSTALL_DIR/lancedb" +reject 'already exists' +test -L "$LANCEDB_INSTALL_DIR/lancedb" +rm "$LANCEDB_INSTALL_DIR/lancedb" +reject 'Checksum mismatch' +test -z "$(ls -A "$LANCEDB_INSTALL_DIR")" +test "$(cat "$work/bin/lancedb")" = 'existing admin CLI' diff --git a/docs/web/tools/cli.mdx b/docs/web/tools/cli.mdx index 0259bf9fb..a225287b9 100644 --- a/docs/web/tools/cli.mdx +++ b/docs/web/tools/cli.mdx @@ -18,6 +18,21 @@ statements supported by your deployment. ## Install +From a repository checkout, use the shell installer to select the archive for +your machine. For example, to install a specific published beta: + +```sh +LANCEDB_VERSION=v0.42.0-beta.19 sh scripts/install.sh +``` + +Omit `LANCEDB_VERSION` to select the latest stable GitHub release. The selected +release must include CLI archives. The installer verifies the archive checksum +and installs to `$HOME/.local/bin/lancedb`. If you already use an Enterprise CLI, +set `LANCEDB_INSTALL_DIR` to a separate absolute directory and invoke the public +client by its full path. To upgrade, move the existing executable first. + +### Manual download + Download a CLI archive and `SHA256SUMS` from the [LanceDB releases page](https://github.com/lancedb/lancedb/releases). The CLI shares the SDK release version, including beta versions. diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100755 index 000000000..5bd7130a5 --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,98 @@ +#!/bin/sh +# Install the public LanceDB command-line client from GitHub Releases. +set -eu + +fail() { + printf 'lancedb installer: %s\n' "$*" >&2 + exit 1 +} + +download() { + curl -q --proto '=https' --proto-redir '=https' -fsSL "$@" +} + +main() { + [ "$#" -eq 0 ] || fail 'Set LANCEDB_VERSION and LANCEDB_INSTALL_DIR via the environment.' + releases=https://github.com/lancedb/lancedb/releases + platform=$(uname -s)-$(uname -m) + case "$platform" in + Darwin-arm64) target=aarch64-apple-darwin ;; + Linux-aarch64|Linux-arm64) target=aarch64-unknown-linux-gnu ;; + Linux-x86_64) target=x86_64-unknown-linux-gnu ;; + *) fail "No CLI archive for $platform. Supported: Apple Silicon macOS, Linux ARM64 and Linux x86-64." ;; + esac + + case "$target" in + *-linux-gnu) + libc=$(getconf GNU_LIBC_VERSION 2>/dev/null) || fail 'Linux requires glibc 2.28 or newer.' + printf '%s\n' "$libc" | awk -F '[ .]' '$1 == "glibc" && ($2 > 2 || ($2 == 2 && $3 >= 28)) { ok=1 } END { exit !ok }' || + fail 'Linux requires glibc 2.28 or newer.' + if [ "$target" = x86_64-unknown-linux-gnu ]; then + for feature in avx2 fma f16c; do + grep -qw "$feature" /proc/cpuinfo || fail "The Linux x86-64 binary requires CPU feature $feature." + done + fi ;; + *-apple-darwin) + os_version=$(sw_vers -productVersion) + [ "${os_version%%.*}" -ge 14 ] || fail 'Apple Silicon requires macOS 14 or newer.' ;; + esac + + dir=${LANCEDB_INSTALL_DIR:-"$HOME/.local/bin"} + case "$dir" in /*) ;; *) fail 'LANCEDB_INSTALL_DIR must be an absolute path.' ;; esac + dest=$dir/lancedb + if [ -e "$dest" ] || [ -L "$dest" ]; then + fail "$dest already exists. Move it first or choose a separate LANCEDB_INSTALL_DIR." + fi + if existing=$(command -v lancedb); then + if [ -z "${LANCEDB_INSTALL_DIR:-}" ]; then + fail "Found $existing on PATH. To install alongside it, set LANCEDB_INSTALL_DIR to a separate directory." + fi + fi + + tag=${LANCEDB_VERSION:-} + if [ -z "$tag" ]; then + latest=$(download --head --output /dev/null --write-out '%{url_effective}' "$releases/latest") + tag=${latest##*/} + fi + version=${tag#v} + # Match the stable and beta tag formats supported by ci/package_cli.py. + case "$version" in *[!0-9a-z.-]*|'') fail "Invalid release version: $tag" ;; esac + printf '%s\n' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-beta\.[0-9]+)?$' || + fail "Invalid release version: $tag" + + stem=lancedb-v$version-$target + archive=$stem.tar.gz + url=$releases/download/v$version + mkdir -p "$dir" + # Stage on the destination filesystem so the final hard link is atomic and cannot overwrite a file. + stage=$(mktemp -d "$dir/.lancedb-install.XXXXXXXX") + trap 'rm -rf "$stage"' EXIT + trap 'exit 1' HUP INT TERM + + download -o "$stage/SHA256SUMS" "$url/SHA256SUMS" || + fail "Could not fetch CLI checksums for v$version. Choose a release with CLI assets using LANCEDB_VERSION." + expected=$(awk -v name="$archive" '$2 == name { count++; hash=$1 } END { if (count != 1) exit 1; print hash }' "$stage/SHA256SUMS") || + fail "Expected exactly one checksum for $archive." + download -o "$stage/$archive" "$url/$archive" + if command -v sha256sum >/dev/null 2>&1; then + actual=$(sha256sum < "$stage/$archive") + else + actual=$(shasum -a 256 < "$stage/$archive") + fi + [ "${actual%% *}" = "$expected" ] || fail "Checksum mismatch for $archive." + + tar -xzOf "$stage/$archive" "$stem/lancedb" > "$stage/lancedb" + chmod 755 "$stage/lancedb" + reported=$("$stage/lancedb" --version) || + fail "Cannot run $target on this machine. Check the CPU and OS requirements in the CLI install guide." + [ "$reported" = "lancedb $version" ] || fail "Unexpected CLI version: $reported" + ln "$stage/lancedb" "$dest" + printf 'Installed %s at %s\n' "$reported" "$dest" + case ":${PATH:-}:" in + *:"$dir":*) ;; + *) printf 'Add %s to PATH or invoke the full path above.\n' "$dir" ;; + esac +} + +# Keep the entry point last so a truncated download cannot start installation. +main "$@" From 96c25bd6b9516c1c15919a9541635c99b2b5be0e Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Wed, 18 Nov 2026 09:02:45 -0800 Subject: [PATCH 16/78] feat(nodejs): add Enterprise table override APIs (#5077) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add TypeScript `getTableOverrides`, `updateTableOverrides`, and `resetTableOverrides` for LanceDB Enterprise tables, delegating to the shared Rust implementation used by Python. Document that updates perform GET → recursive local merge → full PUT. Unrelated fields are preserved from the read snapshot, but concurrent edits can be overwritten. CLI `set` and REST PUT retain replacement semantics. Fix an empty SDK update to return the current snapshot without a PUT. Live testing found that the previous implementation submitted an empty replacement and failed when no overrides were configured. The fix applies to Python, Rust, and TypeScript. Add mock HTTP/local coverage and an opt-in Enterprise integration suite for namespaces, branch isolation, REST replacement, validation failures, historical handles, and empty updates. --- docs/src/js/classes/Table.md | 74 ++++++ docs/web/maintenance/compaction.mdx | 53 +++++ nodejs/__test__/remote.test.ts | 213 ++++++++++++++++++ nodejs/__test__/table.test.ts | 46 ++++ .../table_overrides_integration.test.ts | 166 ++++++++++++++ nodejs/lancedb/table.ts | 64 ++++++ nodejs/src/table.rs | 31 +++ python/python/lancedb/remote/table.py | 6 +- python/python/lancedb/table.py | 36 ++- python/python/tests/test_remote_db.py | 17 ++ rust/lancedb/src/remote/table.rs | 28 +++ rust/lancedb/src/table.rs | 13 +- 12 files changed, 737 insertions(+), 10 deletions(-) create mode 100644 nodejs/__test__/table_overrides_integration.test.ts diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 0a230ac94..966580451 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -901,6 +901,26 @@ Resolves to `undefined` only when the RTE write path is not enabled. *** +### getTableOverrides() + +```ts +getTableOverrides(): Promise> +``` + +Read the stored overrides for a remote Enterprise table. + +Overrides configure background behavior such as automatic compaction, +cleanup, and reindex execution. Keys use the server's snake_case names. +Returns an empty object when no overrides are set. Local tables are unsupported. +Custom table implementations inherit a default rejection unless they override +this method. + +#### Returns + +`Promise`<`Record`<`string`, `unknown`>> + +*** + ### indexStats() ```ts @@ -1379,6 +1399,22 @@ console.log(await job.status()); // "finished" *** +### resetTableOverrides() + +```ts +resetTableOverrides(): Promise> +``` + +Clear a remote Enterprise table's overrides and return an empty object. +Local tables and custom table implementations without override support reject +this operation. + +#### Returns + +`Promise`<`Record`<`string`, `unknown`>> + +*** + ### restore() ```ts @@ -1736,6 +1772,44 @@ resolves to the new table version. *** +### updateTableOverrides() + +```ts +updateTableOverrides(overrides): Promise> +``` + +Recursively merge overrides into a remote Enterprise table's stored overrides. + +Fetches the current overrides, merges nested objects locally, then sends the +complete replacement using REST PUT. Other values replace existing values; +unrelated fields from the read snapshot are preserved. This read-modify-write +is not atomic: concurrent edits can be overwritten, even to unrelated fields. +Coordinate writers when concurrent edits must be preserved. An empty update +only reads and returns the current overrides. + +Unlike this SDK method, CLI `set` and REST PUT replace the overrides object +without merging. Use [Table.resetTableOverrides](Table.md#resettableoverrides) to clear all overrides. +Local tables and custom table implementations without override support reject +this operation. + +#### Parameters + +* **overrides**: `Record`<`string`, `unknown`> + +#### Returns + +`Promise`<`Record`<`string`, `unknown`>> + +#### Example + +```ts +await table.updateTableOverrides({ + job_types: { compaction: { enabled: false } }, +}); +``` + +*** + ### vectorSearch() ```ts diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index d8638419e..ad3fe636d 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -282,6 +282,59 @@ need preserving; read the current object and retain unrelated fields when editing an existing policy. Use the same namespace and branch for policy reads, writes, and compaction submission. +The Python, TypeScript, and Rust SDKs can update selected fields while retaining +unrelated overrides from the current read snapshot. For an existing Enterprise +`table` handle: + + +```python Python +table.update_table_overrides( + job_types={ + "compaction": { + "target_rows_per_fragment": 100000, + "max_source_rows": 1000000, + } + } +) +``` +```typescript TypeScript +await table.updateTableOverrides({ + job_types: { + compaction: { + target_rows_per_fragment: 100000, + max_source_rows: 1000000, + }, + }, +}); +``` +```rust Rust +table + .update_table_overrides(serde_json::json!({ + "job_types": { + "compaction": { + "target_rows_per_fragment": 100000, + "max_source_rows": 1000000 + } + } + })) + .await?; +``` + + +Override keys use the server's `snake_case` names in every SDK. These examples +retain other compaction settings, such as `enabled`, and settings for other job +types from the read snapshot. An empty update only reads the current overrides; +use `reset_table_overrides()` / `resetTableOverrides()` to clear all overrides. + +SDK updates perform **GET → recursive merge in the client → full PUT**. This +read–modify–write is not atomic: concurrent edits can be overwritten, even to +unrelated fields. Coordinate override writers when concurrent edits must be +preserved. CLI `set` and REST PUT replace the object without merging. + +These methods require a compatible Enterprise deployment. For namespaced tables, +confirm that the deployment supports table-override reads and resets within +namespaces before relying on these APIs. + Each manual field resolves as **invocation option → table tuning → deployment/built-in default**. Automatic jobs resolve **table tuning → deployment/built-in default**. The fragment target has a shared deployment diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index c5f81391a..18bf0f1ce 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -2929,3 +2929,216 @@ describe("job wait deadlines", () => { }, ); }); + +describe("table overrides", () => { + it.each([[], ["analytics", "features"]])( + "reads, recursively merges, and resets in namespace %j", + async (...namespacePath: string[]) => { + const requests: { method?: string; url: string; body?: unknown }[] = []; + const current = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { + compaction: { + enabled: true, + // biome-ignore lint/style/useNamingConvention: server wire format + target_rows_per_fragment: 1000, + }, + cleanup: { enabled: false }, + }, + custom: { keep: true, replace: [1, 2], clear: "value" }, + }; + const patch = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { compaction: { enabled: false } }, + custom: { replace: [3], clear: null, label: "測試" }, + }; + const merged = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { + compaction: { + enabled: false, + // biome-ignore lint/style/useNamingConvention: server wire format + target_rows_per_fragment: 1000, + }, + cleanup: { enabled: false }, + }, + custom: { keep: true, replace: [3], clear: null, label: "測試" }, + }; + await withMockDatabase( + (req, res) => { + const url = req.url ?? ""; + if (url.includes("/describe/")) { + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + return; + } + const chunks: Buffer[] = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + const body = chunks.length + ? JSON.parse(Buffer.concat(chunks).toString()) + : undefined; + requests.push({ method: req.method, url, body }); + res + .writeHead(200) + .end( + JSON.stringify( + req.method === "GET" + ? current + : req.method === "PUT" + ? body.overrides + : {}, + ), + ); + }); + }, + async (db) => { + const table = await db.openTable("test", namespacePath); + await expect(table.getTableOverrides()).resolves.toEqual(current); + await expect(table.updateTableOverrides(patch)).resolves.toEqual( + merged, + ); + // The native conversion and merge must not mutate the caller's object. + expect(patch.job_types.compaction).toEqual({ enabled: false }); + expect(patch.custom.replace).toEqual([3]); + await expect(table.resetTableOverrides()).resolves.toEqual({}); + }, + ); + expect(requests.map((request) => request.method)).toEqual([ + "GET", + "GET", + "PUT", + "POST", + ]); + for (const request of requests) { + const url = new URL(request.url, "http://localhost"); + expect(url.pathname).toBe( + request.method === "POST" + ? "/admin/table/overrides/reset" + : "/admin/table/overrides", + ); + if (request.method === "PUT") { + expect(request.body).toEqual({ + db: "dev", + namespace: namespacePath, + table: "test", + overrides: merged, + }); + } else { + expect(url.searchParams.get("db")).toBe("dev"); + expect(url.searchParams.get("table")).toBe("test"); + expect(url.searchParams.getAll("namespace")).toEqual(namespacePath); + } + } + }, + ); + + it.each([{}, { custom: { keep: true } }])( + "only reads the snapshot %j for an empty update", + async (current) => { + const methods: string[] = []; + await withMockDatabase( + (req, res) => { + if (req.url?.includes("/describe/")) { + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + return; + } + methods.push(req.method ?? ""); + res + .writeHead(req.method === "GET" ? 200 : 400) + .end(JSON.stringify(current)); + }, + async (db) => { + const table = await db.openTable("test"); + await expect(table.updateTableOverrides({})).resolves.toEqual( + current, + ); + }, + ); + expect(methods).toEqual(["GET"]); + }, + ); + + it.each([null, [], true, 1, "bad"])( + "rejects a non-object update %j before reading overrides", + async (value) => { + const requests: string[] = []; + await withMockDatabase( + (req, res) => { + requests.push(req.url ?? ""); + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + }, + async (db) => { + const table = await db.openTable("test"); + await expect( + table.updateTableOverrides( + value as unknown as Record, + ), + ).rejects.toThrow(/must be a JSON object/); + }, + ); + expect(requests).toEqual(["/v1/table/test/describe/"]); + }, + ); + + it.each([403, 404])( + "propagates GET failure %i without a PUT", + async (status) => { + const methods: string[] = []; + await withMockDatabase( + (req, res) => { + if (req.url?.includes("/describe/")) { + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + } else { + methods.push(req.method ?? ""); + res.writeHead(status).end("overrides unavailable"); + } + }, + async (db) => { + const table = await db.openTable("test"); + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/overrides unavailable/); + }, + ); + expect(methods).toEqual(["GET"]); + }, + ); + + it("rejects writes on historical and closed handles before HTTP", async () => { + const requests: string[] = []; + await withMockDatabase( + (req, res) => { + requests.push(req.url ?? ""); + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + }, + async (db) => { + const table = await db.openTable("test"); + await table.checkout(1); + requests.length = 0; + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/fixed at version 1/); + await expect(table.resetTableOverrides()).rejects.toThrow( + /fixed at version 1/, + ); + table.close(); + await expect(table.getTableOverrides()).rejects.toThrow(/closed/); + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/closed/); + await expect(table.resetTableOverrides()).rejects.toThrow(/closed/); + }, + ); + expect(requests).toEqual([]); + }); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 7a103d2c9..a93aadde7 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -5886,3 +5886,49 @@ describe("durable compaction validation", () => { ).rejects.toThrow("safe integer"); }); }); + +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. + // biome-ignore lint/correctness/noUnusedVariables: declaration merging supplies the legacy members + interface LegacyTable + extends Omit< + Table, + "getTableOverrides" | "updateTableOverrides" | "resetTableOverrides" + > {} + class LegacyTable extends Table {} + + const table = new LegacyTable(); + await expect(table.getTableOverrides()).rejects.toThrow( + "getTableOverrides is not supported on this table type", + ); + await expect(table.updateTableOverrides({ custom: true })).rejects.toThrow( + "updateTableOverrides is not supported on this table type", + ); + await expect(table.resetTableOverrides()).rejects.toThrow( + "resetTableOverrides is not supported on this table type", + ); + }); + + it("rejects get, update, and reset on local tables", async () => { + const tmpDir = tmp.dirSync({ unsafeCleanup: true }); + const db = await connect(tmpDir.name); + const table = await db.createTable("items", [{ id: 1 }]); + try { + await expect(table.getTableOverrides()).rejects.toThrow( + /only on remote Enterprise tables/, + ); + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/only on remote Enterprise tables/); + await expect(table.resetTableOverrides()).rejects.toThrow( + /only on remote Enterprise tables/, + ); + } finally { + table.close(); + db.close(); + tmpDir.removeCallback(); + } + }); +}); diff --git a/nodejs/__test__/table_overrides_integration.test.ts b/nodejs/__test__/table_overrides_integration.test.ts new file mode 100644 index 000000000..ee6e0c493 --- /dev/null +++ b/nodejs/__test__/table_overrides_integration.test.ts @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { randomUUID } from "node:crypto"; +import { Connection, Table, connect } from "../lancedb"; + +// Run against an isolated Enterprise deployment: +// LANCEDB_TABLE_OVERRIDES_E2E=1 LANCEDB_URI=db://test \ +// LANCEDB_HOST_OVERRIDE=http://localhost:10024 LANCEDB_API_KEY=... \ +// pnpm test __test__/table_overrides_integration.test.ts --runInBand +const maybeDescribe = process.env.LANCEDB_TABLE_OVERRIDES_E2E + ? describe + : describe.skip; + +maybeDescribe("table overrides live integration", () => { + let db: Connection; + const namespace = [`overrides_${randomUUID().replaceAll("-", "_")}`]; + const nested = [...namespace, "nested"]; + const uri = process.env.LANCEDB_URI ?? "db://test"; + const host = process.env.LANCEDB_HOST_OVERRIDE; + const apiKey = process.env.LANCEDB_API_KEY; + + beforeAll(async () => { + if (!host || !apiKey) { + throw new Error( + "Set LANCEDB_HOST_OVERRIDE and LANCEDB_API_KEY for live tests", + ); + } + db = await connect(uri, { apiKey, hostOverride: host }); + await db.createNamespace(namespace); + await db.createNamespace(nested); + }); + + afterAll(async () => { + if (db) { + try { + await db.dropNamespace(nested); + await db.dropNamespace(namespace); + } finally { + db.close(); + } + } + }); + + async function withTable( + namespacePath: string[], + run: (table: Table, name: string) => Promise, + ) { + const name = `items_${randomUUID().replaceAll("-", "_")}`; + const table = await db.createTable(name, [{ id: 1 }], namespacePath); + try { + await run(table, name); + } finally { + table.close(); + await db.dropTable(name, namespacePath); + } + } + + it.each([ + { label: "root", path: [] }, + { label: "nested", path: nested }, + ])( + "merges, replaces via REST, and resets in $label namespace", + async ({ path }) => { + await withTable(path, async (table, name) => { + await expect(table.getTableOverrides()).resolves.toEqual({}); + await expect(table.updateTableOverrides({})).resolves.toEqual({}); + const initial = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { + compaction: { enabled: false }, + cleanup: { enabled: false }, + }, + custom: { keep: "測試", values: [1, 2], nullable: "old" }, + }; + await expect(table.updateTableOverrides(initial)).resolves.toEqual( + initial, + ); + const patch = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { compaction: { enabled: true } }, + custom: { values: [3], nullable: null }, + }; + const expected = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { + compaction: { enabled: true }, + cleanup: { enabled: false }, + }, + custom: { keep: "測試", values: [3], nullable: null }, + }; + await expect(table.updateTableOverrides(patch)).resolves.toEqual( + expected, + ); + await expect(table.getTableOverrides()).resolves.toEqual(expected); + await expect(table.updateTableOverrides({})).resolves.toEqual(expected); + + const replacement = { custom: { replacement: true } }; + const response = await fetch(`${host}/admin/table/overrides`, { + method: "PUT", + headers: { "x-api-key": apiKey!, "Content-Type": "application/json" }, + body: JSON.stringify({ + db: new URL(uri).hostname, + namespace: path, + table: name, + overrides: replacement, + }), + }); + expect(response.status).toBe(200); + expect(await response.json()).toEqual(replacement); + await expect(table.getTableOverrides()).resolves.toEqual(replacement); + await expect(table.resetTableOverrides()).resolves.toEqual({}); + await expect(table.getTableOverrides()).resolves.toEqual({}); + await expect(table.countRows()).resolves.toBe(1); + }); + }, + ); + + it("isolates branch updates and resets from main", async () => { + await withTable(nested, async (table) => { + const initial = { custom: { main: true } }; + await table.updateTableOverrides(initial); + const branch = await (await table.branches()).create("experiment"); + try { + const expected = { custom: { main: true, branch: true } }; + await expect( + branch.updateTableOverrides({ custom: { branch: true } }), + ).resolves.toEqual(expected); + await expect(table.getTableOverrides()).resolves.toEqual(initial); + await expect(branch.resetTableOverrides()).resolves.toEqual({}); + await expect(branch.getTableOverrides()).resolves.toEqual({}); + await expect(table.getTableOverrides()).resolves.toEqual(initial); + } finally { + branch.close(); + } + }); + }); + + it("propagates server validation errors without changing stored overrides", async () => { + await withTable(nested, async (table) => { + const initial = { custom: { keep: true } }; + await table.updateTableOverrides(initial); + await expect( + table.updateTableOverrides({ + // biome-ignore lint/style/useNamingConvention: server wire format + auto_refresh_interval_seconds: -1, + }), + ).rejects.toThrow(); + await expect(table.getTableOverrides()).resolves.toEqual(initial); + }); + }); + + it("rejects writes at a fixed version", async () => { + await withTable(nested, async (table) => { + await table.checkout(1); + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/fixed at version/); + await expect(table.resetTableOverrides()).rejects.toThrow( + /fixed at version/, + ); + await table.checkoutLatest(); + await expect(table.getTableOverrides()).resolves.toEqual({}); + }); + }); +}); diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 2fff63108..9f0760264 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -1106,6 +1106,56 @@ export abstract class Table { * @returns {Promise} */ abstract getRTESpec(): Promise; + /** + * Read the stored overrides for a remote Enterprise table. + * + * Overrides configure background behavior such as automatic compaction, + * cleanup, and reindex execution. Keys use the server's snake_case names. + * Returns an empty object when no overrides are set. Local tables are unsupported. + * Custom table implementations inherit a default rejection unless they override + * this method. + */ + async getTableOverrides(): Promise> { + throw new Error("getTableOverrides is not supported on this table type"); + } + + /** + * Recursively merge overrides into a remote Enterprise table's stored overrides. + * + * Fetches the current overrides, merges nested objects locally, then sends the + * complete replacement using REST PUT. Other values replace existing values; + * unrelated fields from the read snapshot are preserved. This read-modify-write + * is not atomic: concurrent edits can be overwritten, even to unrelated fields. + * Coordinate writers when concurrent edits must be preserved. An empty update + * only reads and returns the current overrides. + * + * Unlike this SDK method, CLI `set` and REST PUT replace the overrides object + * without merging. Use {@link Table.resetTableOverrides} to clear all overrides. + * Local tables and custom table implementations without override support reject + * this operation. + * + * @example + * ```ts + * await table.updateTableOverrides({ + * job_types: { compaction: { enabled: false } }, + * }); + * ``` + */ + async updateTableOverrides( + // biome-ignore lint/correctness/noUnusedVariables: retain the public parameter name in generated docs + overrides: Record, + ): Promise> { + throw new Error("updateTableOverrides is not supported on this table type"); + } + + /** + * Clear a remote Enterprise table's overrides and return an empty object. + * Local tables and custom table implementations without override support reject + * this operation. + */ + async resetTableOverrides(): Promise> { + throw new Error("resetTableOverrides is not supported on this table type"); + } /** * Drain and close any cached RTE shard writers held for this table. * @@ -1916,6 +1966,20 @@ export class LocalTable extends Table { | undefined; } + async getTableOverrides(): Promise> { + return await this.inner.getTableOverrides(); + } + + async updateTableOverrides( + overrides: Record, + ): Promise> { + return await this.inner.updateTableOverrides(overrides); + } + + async resetTableOverrides(): Promise> { + return await this.inner.resetTableOverrides(); + } + async closeRTEWriters(): Promise { return await this.inner.closeRTEWriters(); } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 3a9b8be72..617822171 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -821,6 +821,37 @@ impl Table { Ok(spec.map(RTEWriteSpec::from)) } + #[napi(catch_unwind, ts_return_type = "Promise>")] + pub async fn get_table_overrides(&self) -> napi::Result { + self.inner_ref()? + .get_table_overrides() + .await + .default_error() + } + + #[napi( + catch_unwind, + ts_args_type = "overrides: Record", + ts_return_type = "Promise>" + )] + pub async fn update_table_overrides( + &self, + overrides: serde_json::Value, + ) -> napi::Result { + self.inner_ref()? + .update_table_overrides(overrides) + .await + .default_error() + } + + #[napi(catch_unwind, ts_return_type = "Promise>")] + pub async fn reset_table_overrides(&self) -> napi::Result { + self.inner_ref()? + .reset_table_overrides() + .await + .default_error() + } + #[napi(catch_unwind, js_name = "closeRTEWriters")] pub async fn close_rte_writers(&self) -> napi::Result<()> { self.inner_ref()?.close_rte_writers().await.default_error() diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index ac936ebd9..2b7d3847d 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1380,7 +1380,11 @@ class RemoteTable(Table): return LOOP.run(self._table.get_table_overrides()) def update_table_overrides(self, **overrides: Any) -> dict[str, Any]: - """Merge Enterprise table overrides into the current table overrides.""" + """Merge Enterprise table overrides using a non-atomic read-modify-write. + + See [the async method][lancedb.AsyncTable.update_table_overrides] + for merge behavior and concurrency limitations. + """ return LOOP.run(self._table.update_table_overrides(**overrides)) def reset_table_overrides(self) -> dict[str, Any]: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 8c3d30170..1dab667df 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2115,8 +2115,16 @@ class Table(ABC): def update_table_overrides(self, **overrides: Any) -> dict[str, Any]: """Merge Enterprise table overrides into the current table overrides. - Only fields supplied in ``overrides`` are changed; unrelated existing - overrides are preserved by the remote service update flow. + Fetches the current overrides, recursively merges nested objects locally, + then sends the complete replacement using REST PUT. Other values replace + existing values; unrelated fields from the read snapshot are preserved. + This read-modify-write is not atomic: concurrent edits can be overwritten, + even to unrelated fields. Coordinate writers when concurrent edits must + be preserved. An empty update only reads and returns the current overrides. + + Unlike this SDK method, CLI ``set`` and REST PUT replace the overrides + object without merging. Use ``reset_table_overrides()`` to clear all + overrides. Supported only on remote Enterprise tables. """ raise NotImplementedError @@ -6183,8 +6191,16 @@ class LanceTable(Table): def update_table_overrides(self, **overrides: Any) -> dict[str, Any]: """Merge Enterprise table overrides into the current table overrides. - Only fields supplied in ``overrides`` are changed; unrelated overrides - from the current read snapshot are preserved. + Fetches the current overrides, recursively merges nested objects locally, + then sends the complete replacement using REST PUT. Other values replace + existing values; unrelated fields from the read snapshot are preserved. + This read-modify-write is not atomic: concurrent edits can be overwritten, + even to unrelated fields. Coordinate writers when concurrent edits must + be preserved. An empty update only reads and returns the current overrides. + + Unlike this SDK method, CLI ``set`` and REST PUT replace the overrides + object without merging. Use ``reset_table_overrides()`` to clear all + overrides. Supported only on remote Enterprise tables. Examples -------- @@ -6962,8 +6978,16 @@ class AsyncTable: async def update_table_overrides(self, **overrides: Any) -> dict[str, Any]: """Merge Enterprise table overrides into the current table overrides. - Only fields supplied in ``overrides`` are changed; unrelated overrides - from the current read snapshot are preserved. + Fetches the current overrides, recursively merges nested objects locally, + then sends the complete replacement using REST PUT. Other values replace + existing values; unrelated fields from the read snapshot are preserved. + This read-modify-write is not atomic: concurrent edits can be overwritten, + even to unrelated fields. Coordinate writers when concurrent edits must + be preserved. An empty update only reads and returns the current overrides. + + Unlike this SDK method, CLI ``set`` and REST PUT replace the overrides + object without merging. Use ``reset_table_overrides()`` to clear all + overrides. Supported only on remote Enterprise tables. Examples -------- diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index eff207230..b74450553 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -4016,6 +4016,23 @@ def test_update_table_overrides_sync_remote_table_merges_existing_fields(): assert calls == ["GET", "PUT"] +@pytest.mark.parametrize("current", [{}, {"custom": {"keep": True}}]) +def test_empty_update_table_overrides_only_reads(current): + calls = [] + + def overrides_handler(request, parsed): + calls.append(request.command) + assert request.command == "GET" + assert parsed.path == "/admin/table/overrides" + assert_table_overrides_query(parsed) + send_json(request, current) + + with table_overrides_test_table(overrides_handler) as table: + assert table.update_table_overrides() == current + + assert calls == ["GET"] + + def test_reset_table_overrides_sync_remote_table(): def overrides_handler(request, parsed): assert request.command == "POST" diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 2e116dd87..790f21961 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3984,6 +3984,9 @@ impl BaseTable for RemoteTable { }); } }; + if patch.is_empty() { + return Ok(serde_json::Value::Object(current)); + } Self::merge_table_overrides(&mut current, patch); let merged = serde_json::Value::Object(current); let body = self.table_overrides_set_body(merged); @@ -14158,6 +14161,31 @@ mod tests { assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 2); } + #[tokio::test] + async fn test_update_table_overrides_empty_patch_only_reads() { + for current in [ + serde_json::json!({}), + serde_json::json!({"job_types": {"compaction": {"enabled": false}}}), + ] { + let snapshot = current.clone(); + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.method(), "GET"); + assert_eq!(request.url().path(), "/admin/table/overrides"); + http::Response::builder() + .status(200) + .body(snapshot.to_string()) + .unwrap() + }); + assert_eq!( + table + .update_table_overrides(serde_json::json!({})) + .await + .unwrap(), + current + ); + } + } + #[tokio::test] async fn test_reset_table_overrides() { let table = Table::new_with_handler("my_table", |request| { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index e7f8062e4..156474f23 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -2736,9 +2736,16 @@ impl Table { /// Merge Enterprise table overrides into the current stored overrides. /// - /// This method uses patch semantics: fields present in `overrides` are - /// recursively merged into the existing table overrides and unrelated fields - /// are preserved. + /// Fetches the current overrides, recursively merges nested objects locally, + /// then sends the complete replacement using REST PUT. Other values replace + /// existing values; unrelated fields from the read snapshot are preserved. + /// This read-modify-write is not atomic: concurrent edits can be overwritten, + /// even to unrelated fields. Coordinate writers when concurrent edits must + /// be preserved. An empty update only reads and returns the current overrides. + /// + /// Unlike this SDK method, CLI `set` and REST PUT replace the overrides object + /// without merging. Use [`Self::reset_table_overrides`] to clear all overrides. + /// Supported only on remote Enterprise tables. pub async fn update_table_overrides( &self, overrides: TableOverrides, From 3907a492c02332093db716dfc91561819499b8fb Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Wed, 18 Nov 2026 09:14:14 -0800 Subject: [PATCH 17/78] feat(sdk): add typed data prewarm previews (#5075) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LanceDB SDKs can submit data prewarm jobs, but callers have to issue SQL directly to inspect a plan before warming. The existing text response does not provide a typed pruning contract. This adds metadata-only preview helpers across Rust, Python sync/async, and TypeScript, using a compatible Enterprise server’s structured SQL response. This was accomplished with the following changes: - Add `explain_prewarm_data(PrewarmDataOptions)`, Python `explain_prewarm_data(...)`, and TypeScript `explainPrewarmData(options)`. - Expose `PrewarmDataPlan` and `PrewarmPruningSummary`, preserving zero versus unknown counts and future pruning-mode strings. - Reuse submission options, identifier/filter validation, namespace and branch context, and Azure source-account hint handling. - Validate the versioned JSON response without parsing display text, submitting a warming job, polling HTTP job APIs, or falling back to REST. - Add API documentation, Flight SQL transport tests, Python sync/async response tests, and an opt-in live-service integration test. ### Usage and behaviour ```python plan = table.explain_prewarm_data(["payload"], filter="quality > 0.7") print(plan.table_version, plan.pruning.selected_fragments) ``` The helper returns a plan directly. It requires table Select plus database/namespace Usage and a server supporting `EXPLAIN (FORMAT JSON) PREWARM`. It reads metadata without creating a warming job. Selected ranges are conservative physical candidates; unknown counts remain `None`/`null`. A later submission resolves and plans its own snapshot. Historical-version and Embedded table handles are unsupported. --- docs/src/js/classes/Table.md | 32 ++++ docs/src/js/globals.md | 2 + docs/src/js/interfaces/PrewarmDataOptions.md | 2 +- docs/src/js/interfaces/PrewarmDataPlan.md | 37 +++++ .../js/interfaces/PrewarmPruningSummary.md | 61 +++++++ docs/src/python/python.md | 4 + docs/web/enterprise/cache-prewarm.mdx | 71 +++++++++ nodejs/__test__/prewarm.test.ts | 33 ++++ nodejs/__test__/table.test.ts | 23 +++ nodejs/lancedb/index.ts | 6 +- nodejs/lancedb/prewarm.ts | 43 +++++ nodejs/lancedb/table.ts | 52 +++++- nodejs/src/table.rs | 17 ++ python/python/lancedb/_lancedb.pyi | 7 + python/python/lancedb/prewarm.py | 45 +++++- python/python/lancedb/remote/table.py | 20 ++- python/python/lancedb/table.py | 66 +++++++- python/python/tests/test_e2e_remote_db.py | 62 ++++++++ python/python/tests/test_remote_db.py | 126 ++++++++++++++- python/python/tests/test_table.py | 4 +- python/src/table.rs | 18 +++ rust/lancedb/src/remote/sql_test.rs | 96 ++++++++++- rust/lancedb/src/remote/table.rs | 38 +++++ rust/lancedb/src/remote/table/prewarm.rs | 150 ++++++++++++++++++ rust/lancedb/src/table.rs | 32 +++- rust/lancedb/src/table/prewarm.rs | 41 ++++- 26 files changed, 1070 insertions(+), 18 deletions(-) create mode 100644 docs/src/js/interfaces/PrewarmDataPlan.md create mode 100644 docs/src/js/interfaces/PrewarmPruningSummary.md create mode 100644 nodejs/__test__/prewarm.test.ts diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 966580451..63b6cffa0 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -653,6 +653,38 @@ await table.enableRTE({ *** +### explainPrewarmData() + +```ts +explainPrewarmData(_options?): Promise +``` + +Preview prewarm with the same options as [prewarmDataAsync](Table.md#prewarmdataasync), without +submitting a warming job. Requires LanceDB Enterprise with structured SQL +previews, table Select and database/namespace Usage. Reads metadata and +returns the source version, readable plan, and conservative pruning summary. +A later submission plans its own snapshot. Historical and Embedded handles +are unsupported. Unknown measurements remain null. +Custom table implementations can override this method; its default rejects +with an unsupported-operation error. + +#### Parameters + +* **\_options?**: [`PrewarmDataOptions`](../interfaces/PrewarmDataOptions.md) + +#### Returns + +`Promise`<[`PrewarmDataPlan`](../interfaces/PrewarmDataPlan.md)> + +#### Example + +```ts +const plan = await table.explainPrewarmData({columns: ["video"], filter: "quality > 0.7"}); +console.log(plan.pruning.selectedFragments); +``` + +*** + ### fetchBlobFiles() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 3893f9a7e..3c348faac 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -131,7 +131,9 @@ - [OptimizeOptions](interfaces/OptimizeOptions.md) - [OptimizeStats](interfaces/OptimizeStats.md) - [PrewarmDataOptions](interfaces/PrewarmDataOptions.md) +- [PrewarmDataPlan](interfaces/PrewarmDataPlan.md) - [PrewarmDataResult](interfaces/PrewarmDataResult.md) +- [PrewarmPruningSummary](interfaces/PrewarmPruningSummary.md) - [QueryExecutionOptions](interfaces/QueryExecutionOptions.md) - [RTEStats](interfaces/RTEStats.md) - [RTEWriteSpec](interfaces/RTEWriteSpec.md) diff --git a/docs/src/js/interfaces/PrewarmDataOptions.md b/docs/src/js/interfaces/PrewarmDataOptions.md index def1eb822..4815b84fb 100644 --- a/docs/src/js/interfaces/PrewarmDataOptions.md +++ b/docs/src/js/interfaces/PrewarmDataOptions.md @@ -6,7 +6,7 @@ # Interface: PrewarmDataOptions -Settings for submitting a durable remote data-cache prewarm job. +Settings for data-cache prewarm submissions and metadata previews. ## Properties diff --git a/docs/src/js/interfaces/PrewarmDataPlan.md b/docs/src/js/interfaces/PrewarmDataPlan.md new file mode 100644 index 000000000..c06a2ac0a --- /dev/null +++ b/docs/src/js/interfaces/PrewarmDataPlan.md @@ -0,0 +1,37 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / PrewarmDataPlan + +# Interface: PrewarmDataPlan + +Metadata-only snapshot preview; no warming job is submitted. + +## Properties + +### plan + +```ts +plan: string; +``` + +Readable display text. Use pruning for structured facts. + +*** + +### pruning + +```ts +pruning: PrewarmPruningSummary; +``` + +*** + +### tableVersion + +```ts +tableVersion: number; +``` + +Snapshot used for this preview. A later submission plans its own snapshot. diff --git a/docs/src/js/interfaces/PrewarmPruningSummary.md b/docs/src/js/interfaces/PrewarmPruningSummary.md new file mode 100644 index 000000000..78d1ba00a --- /dev/null +++ b/docs/src/js/interfaces/PrewarmPruningSummary.md @@ -0,0 +1,61 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / PrewarmPruningSummary + +# Interface: PrewarmPruningSummary + +Conservative metadata proof, rather than exact matching rows. + +## Properties + +### fallbackReason + +```ts +fallbackReason: null | string; +``` + +*** + +### inputFragments + +```ts +inputFragments: number; +``` + +*** + +### mode + +```ts +mode: string; +``` + +Server-reported proof mode; future servers may add modes. + +*** + +### prunedFragments + +```ts +prunedFragments: number; +``` + +*** + +### selectedFragments + +```ts +selectedFragments: number; +``` + +*** + +### selectedRowRanges + +```ts +selectedRowRanges: null | number; +``` + +Candidate physical intervals, or null when unknown. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 04f315e1c..752bf540f 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -1520,3 +1520,7 @@ Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or ::: lancedb.compaction.CompactionResult ::: lancedb.prewarm.PrewarmDataResult + +::: lancedb.prewarm.PrewarmDataPlan + +::: lancedb.prewarm.PrewarmPruningSummary diff --git a/docs/web/enterprise/cache-prewarm.mdx b/docs/web/enterprise/cache-prewarm.mdx index c2a5347f1..56a091364 100644 --- a/docs/web/enterprise/cache-prewarm.mdx +++ b/docs/web/enterprise/cache-prewarm.mdx @@ -181,9 +181,80 @@ and pinned source version; preview creates no job: ```sql PREWARM WITH (concurrency = 4) AS SELECT payload FROM events WHERE id >= 1000; EXPLAIN PREWARM WITH (concurrency = 4) AS SELECT payload FROM events WHERE id >= 1000; +EXPLAIN (FORMAT JSON) PREWARM WITH (concurrency = 4) AS SELECT payload FROM events WHERE id >= 1000; DESCRIBE JOB '' FORMAT JSON; ``` +The typed SDK preview helpers return a `PrewarmDataPlan` with the source table +version, readable plan, and structured pruning summary. They require an Enterprise +deployment supporting `EXPLAIN (FORMAT JSON) PREWARM` and Flight SQL connectivity. +Preview requires table Select plus Usage on the database and namespace hierarchy; +it creates no warming job and does not use the job-monitoring APIs. + + + +```python +from lancedb.prewarm import PrewarmDataPlan + +plan: PrewarmDataPlan = table.explain_prewarm_data( + ["payload"], filter="id >= 1000", concurrency=4 +) +print(plan.table_version) +print(plan.pruning.mode) +print(plan.pruning.selected_fragments, plan.pruning.input_fragments) +print(plan.pruning.selected_row_ranges, plan.pruning.fallback_reason) +``` + +With an `AsyncTable`, use `await table.explain_prewarm_data(...)` with the same +arguments. It returns the same plan type. + + +```typescript +import type { PrewarmDataPlan } from "@lancedb/lancedb"; + +const plan: PrewarmDataPlan = await table.explainPrewarmData({ + columns: ["payload"], + filter: "id >= 1000", + concurrency: 4, +}); +console.log(plan.tableVersion); +console.log(plan.pruning.mode); +console.log(plan.pruning.selectedFragments, plan.pruning.inputFragments); +console.log(plan.pruning.selectedRowRanges, plan.pruning.fallbackReason); +``` + + +```rust +use lancedb::table::{PrewarmDataOptions, PrewarmDataPlan}; + +let plan: PrewarmDataPlan = table + .explain_prewarm_data( + PrewarmDataOptions::new() + .columns(["payload"]) + .filter("id >= 1000") + .concurrency(4), + ) + .await?; +println!( + "Snapshot {}: {} of {} fragments selected", + plan.table_version, plan.pruning.selected_fragments, plan.pruning.input_fragments +); +println!( + "Mode: {}, candidate ranges: {:?}, fallback: {:?}", + plan.pruning.mode, plan.pruning.selected_row_ranges, plan.pruning.fallback_reason +); +``` + + + +The `plan` string is for display; use `pruning` for structured facts. Selected +row ranges are conservative physical candidate intervals, not exact matching +rows. Unavailable range counts remain None/null; a reported zero means no +candidate ranges. The fallback reason describes why pruning was unavailable, +when reported. Pruning modes may expand in future server versions. A preview does not reserve its snapshot: a later submission +resolves and plans its own source version. Unsupported servers fail explicitly +without falling back to text parsing or REST. + The filter is a single SQL predicate used for conservative metadata pruning. Unknown or unavailable metadata keeps data eligible for warming. Omitted columns warm all fields; concurrency must be a positive integer. Historical diff --git a/nodejs/__test__/prewarm.test.ts b/nodejs/__test__/prewarm.test.ts new file mode 100644 index 000000000..ac6c23c22 --- /dev/null +++ b/nodejs/__test__/prewarm.test.ts @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { decodePrewarmDataPlan } from "../lancedb/prewarm"; +import { Table } from "../lancedb/table"; + +test.each([null, 0, 2])( + "preview preserves unknown and zero range counts: %s", + (ranges) => { + const plan = decodePrewarmDataPlan( + JSON.parse(`{ + "table_version":42,"plan":"display text", + "pruning":{"mode":"future_mode","input_fragments":3,"selected_fragments":0, + "pruned_fragments":3,"selected_row_ranges":${ranges}} + }`), + ); + expect(plan.tableVersion).toBe(42); + expect(plan.pruning.mode).toBe("future_mode"); + expect(plan.pruning.selectedRowRanges).toBe(ranges); + expect(plan.pruning.fallbackReason).toBeNull(); + }, +); + +test("custom tables inherit an unsupported preview default", async () => { + // Only the inherited default is exercised; unrelated abstract operations + // do not need implementations in this fixture. + const table = Object.create(Table.prototype) as Table; + await expect( + table.explainPrewarmData({ columns: ["payload"], filter: "id > 0" }), + ).rejects.toThrow( + "data prewarm previews are not supported by this table implementation", + ); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index a93aadde7..04d80d5f9 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -4738,6 +4738,29 @@ describe.each(arrowVersions)( } }); + test("explainPrewarmData validates options and rejects Embedded tables", async () => { + const db = await connect(tmp.dirSync().name); + const table = await db.createTable("preview", [{ id: 1 }]); + await expect(table.explainPrewarmData()).rejects.toThrow( + "only supported on remote tables", + ); + await expect( + table.explainPrewarmData({ unsupported: true } as never), + ).rejects.toThrow("Unsupported data prewarm option"); + for (const concurrency of [ + 0, + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + 2 ** 32, + ]) { + await expect(table.explainPrewarmData({ concurrency })).rejects.toThrow( + "concurrency", + ); + } + }); + test("prewarmDataAsync validates options and rejects local tables", async () => { const db = await connect(tmpDir.name); const table = await db.createTable("prewarm_job", [{ id: 1 }]); diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 3f0aed61f..8a2607724 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -668,4 +668,8 @@ export { Listing, ListingOptions } from "./listing"; export type { CompactionResult } from "./compaction"; -export type { PrewarmDataResult } from "./prewarm"; +export type { + PrewarmDataPlan, + PrewarmDataResult, + PrewarmPruningSummary, +} from "./prewarm"; diff --git a/nodejs/lancedb/prewarm.ts b/nodejs/lancedb/prewarm.ts index 942e0a19f..3d40cd5c9 100644 --- a/nodejs/lancedb/prewarm.ts +++ b/nodejs/lancedb/prewarm.ts @@ -33,3 +33,46 @@ export function decodePrewarmDataResult(value: unknown): PrewarmDataResult { bytesRead: result.bytes_read ?? null, }; } + +/** Metadata-only snapshot preview; no warming job is submitted. */ +export interface PrewarmDataPlan { + /** Snapshot used for this preview. A later submission plans its own snapshot. */ + tableVersion: number; + /** Readable display text. Use pruning for structured facts. */ + plan: string; + pruning: PrewarmPruningSummary; +} + +/** Conservative metadata proof, rather than exact matching rows. */ +export interface PrewarmPruningSummary { + /** Server-reported proof mode; future servers may add modes. */ + mode: string; + inputFragments: number; + selectedFragments: number; + prunedFragments: number; + /** Candidate physical intervals, or null when unknown. */ + selectedRowRanges: number | null; + fallbackReason: string | null; +} + +/** @internal */ +export function decodePrewarmDataPlan(value: unknown): PrewarmDataPlan { + // Rust validates the versioned response before handing it to JavaScript. + const result = value as { + [key: string]: unknown; + pruning: Record; + }; + return { + tableVersion: result.table_version as number, + plan: result.plan as string, + pruning: { + mode: result.pruning.mode as string, + inputFragments: result.pruning.input_fragments as number, + selectedFragments: result.pruning.selected_fragments as number, + prunedFragments: result.pruning.pruned_fragments as number, + selectedRowRanges: + (result.pruning.selected_row_ranges as number | null) ?? null, + fallbackReason: (result.pruning.fallback_reason as string | null) ?? null, + }, + }; +} diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 9f0760264..3b3e7abe5 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -2,7 +2,12 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors import { CompactionResult, decodeCompactionResult } from "./compaction"; -import { PrewarmDataResult, decodePrewarmDataResult } from "./prewarm"; +import { + PrewarmDataPlan, + PrewarmDataResult, + decodePrewarmDataPlan, + decodePrewarmDataResult, +} from "./prewarm"; import { Table as ArrowTable, @@ -168,7 +173,7 @@ export interface UpdateOptions { where: string; } -/** Settings for submitting a durable remote data-cache prewarm job. */ +/** Settings for data-cache prewarm submissions and metadata previews. */ export interface PrewarmDataOptions { /** Lance field paths to warm; omitted or empty means every column. */ columns?: string[]; @@ -627,6 +632,28 @@ export abstract class Table { options?: PrewarmDataOptions, ): Promise>; + /** + * Preview prewarm with the same options as {@link prewarmDataAsync}, without + * submitting a warming job. Requires LanceDB Enterprise with structured SQL + * previews, table Select and database/namespace Usage. Reads metadata and + * returns the source version, readable plan, and conservative pruning summary. + * A later submission plans its own snapshot. Historical and Embedded handles + * are unsupported. Unknown measurements remain null. + * Custom table implementations can override this method; its default rejects + * with an unsupported-operation error. + * + * @example + * const plan = await table.explainPrewarmData({columns: ["video"], filter: "quality > 0.7"}); + * console.log(plan.pruning.selectedFragments); + */ + async explainPrewarmData( + _options?: PrewarmDataOptions, + ): Promise { + throw new Error( + "data prewarm previews are not supported by this table implementation", + ); + } + /** * Waits for asynchronous indexing to complete on the table. * @@ -1641,17 +1668,20 @@ export class LocalTable extends Table { async prewarmDataAsync( options?: PrewarmDataOptions, ): Promise> { - for (const key of Object.keys(options ?? {})) { - if (!["columns", "filter", "concurrency"].includes(key)) { - throw new Error(`Unsupported data prewarm option: ${key}`); - } - } + validatePrewarmDataOptions(options); return new Job( await this.inner.prewarmDataAsync(options), decodePrewarmDataResult, ); } + async explainPrewarmData( + options?: PrewarmDataOptions, + ): Promise { + validatePrewarmDataOptions(options); + return decodePrewarmDataPlan(await this.inner.explainPrewarmData(options)); + } + async waitForIndex( indexNames: string[], timeoutSeconds: number, @@ -2368,3 +2398,11 @@ function validateCompactionOptions(options?: CompactionOptions): void { } } } + +function validatePrewarmDataOptions(options?: PrewarmDataOptions): void { + for (const key of Object.keys(options ?? {})) { + if (!["columns", "filter", "concurrency"].includes(key)) { + throw new Error(`Unsupported data prewarm option: ${key}`); + } + } +} diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 617822171..6a0a8cb60 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -341,6 +341,23 @@ impl Table { Ok(crate::job::Job::new_typed(job)) } + #[napi(catch_unwind)] + pub async fn explain_prewarm_data( + &self, + options: Option, + ) -> napi::Result { + let options = options + .map(PrewarmDataOptions::into_options) + .transpose()? + .unwrap_or_default(); + let plan = self + .inner_ref()? + .explain_prewarm_data(options) + .await + .default_error()?; + serde_json::to_value(plan).map_err(|error| napi::Error::from_reason(error.to_string())) + } + #[napi(catch_unwind)] pub async fn wait_for_index(&self, index_names: Vec, timeout_s: i64) -> Result<()> { let timeout = std::time::Duration::from_secs(timeout_s.try_into().unwrap()); diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index b4b97ff38..cdeebf6ef 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -645,6 +645,13 @@ class Table: async def restore(self, version: Optional[Union[int, str]] = None): ... async def prewarm_index(self, index_name: str) -> None: ... async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: ... + async def explain_prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> str: ... async def prewarm_data_async( self, columns: Optional[List[str]] = None, diff --git a/python/python/lancedb/prewarm.py b/python/python/lancedb/prewarm.py index c21bd6cfd..441f40d6d 100644 --- a/python/python/lancedb/prewarm.py +++ b/python/python/lancedb/prewarm.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -"""Results of remote data-cache prewarm jobs.""" +"""Typed metadata previews and results of data-cache prewarm jobs.""" from dataclasses import dataclass, fields import json @@ -30,3 +30,46 @@ class PrewarmDataResult: value = json.loads(raw) names = {field.name for field in fields(cls)} return cls(**{key: item for key, item in value.items() if key in names}) + + +@dataclass(frozen=True) +class PrewarmPruningSummary: + """Conservative metadata pruning; selected ranges are not exact row matches. + + ``mode`` is a server-reported string, including future pruning modes. + Unknown interval counts and fallback reasons remain None. + """ + + mode: str + input_fragments: int + selected_fragments: int + pruned_fragments: int + selected_row_ranges: Optional[int] = None + fallback_reason: Optional[str] = None + + +@dataclass(frozen=True) +class PrewarmDataPlan: + """Metadata-only preview for a snapshot, without a warming job. + + A later submission chooses its own snapshot and can produce a different + plan. ``plan`` is readable display text; use ``pruning`` for structured facts. + """ + + table_version: int + plan: str + pruning: PrewarmPruningSummary + + @classmethod + def from_json(cls, raw: str) -> "PrewarmDataPlan": + # The native SDK validates the wire format before returning this value. + value = json.loads(raw) + summary = value["pruning"] + names = {field.name for field in fields(PrewarmPruningSummary)} + return cls( + table_version=value["table_version"], + plan=value["plan"], + pruning=PrewarmPruningSummary( + **{key: item for key, item in summary.items() if key in names} + ), + ) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 2b7d3847d..a5d08bd72 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -48,7 +48,7 @@ from lancedb.index import ( Bitmap, LabelList, ) -from lancedb.prewarm import PrewarmDataResult +from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult from lancedb.job import Job from lancedb.functions import ( FunctionProvenance, @@ -1486,6 +1486,24 @@ class RemoteTable(Table): self._table.prewarm_data(columns, filter=filter, concurrency=concurrency) ) + def explain_prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> PrewarmDataPlan: + """Preview prewarm without submitting a warming job. + + See [Table.explain_prewarm_data][lancedb.table.Table.explain_prewarm_data] + for options, permissions, snapshot semantics, and limitations. + """ + return LOOP.run( + self._table.explain_prewarm_data( + columns, filter=filter, concurrency=concurrency + ) + ) + def prewarm_data_async( self, columns: Optional[List[str]] = None, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 1dab667df..d9c20e287 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -48,7 +48,7 @@ from ._blob import ( from .types import BlobMode from lancedb.arrow import peek_reader from lancedb.background_loop import LOOP, embedding_executor -from lancedb.prewarm import PrewarmDataResult +from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult from lancedb.job import AsyncJob, Job, _typed_job from lancedb.compaction import CompactionResult from .dependencies import ( @@ -2039,6 +2039,34 @@ class Table(ABC): """ self.prewarm_data_async(columns, filter=filter, concurrency=concurrency) + def explain_prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> PrewarmDataPlan: + """Preview data prewarm without creating a warming job. + + Accepts the same columns, filter, and concurrency as ``prewarm_data_async`` + and uses the table handle's namespace and branch. Requires LanceDB + Enterprise with structured SQL previews, table Select, and database/namespace + Usage. Historical-version and Embedded handles are unsupported. + + Returns the source version, readable plan, and conservative pruning summary. + Unknown metrics remain None; selected ranges are not exact matching rows. + The preview reads metadata. A later submission plans its own snapshot. + + Examples + -------- + >>> plan = table.explain_prewarm_data( # doctest: +SKIP + ... ["video"], filter="quality > 0.7") + >>> print(plan.pruning.selected_fragments) # doctest: +SKIP + """ + raise NotImplementedError( + "data prewarm previews are only supported on remote tables" + ) + def prewarm_data_async( self, columns: Optional[List[str]] = None, @@ -4984,6 +5012,24 @@ class LanceTable(Table): self._table.prewarm_data(columns, filter=filter, concurrency=concurrency) ) + def explain_prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> PrewarmDataPlan: + """Preview prewarm without submitting a warming job. + + See [Table.explain_prewarm_data][lancedb.table.Table.explain_prewarm_data] + for options, permissions, snapshot semantics, and limitations. + """ + return LOOP.run( + self._table.explain_prewarm_data( + columns, filter=filter, concurrency=concurrency + ) + ) + def prewarm_data_async( self, columns: Optional[List[str]] = None, @@ -7519,6 +7565,24 @@ class AsyncTable: """ await self.prewarm_data_async(columns, filter=filter, concurrency=concurrency) + async def explain_prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> PrewarmDataPlan: + """Preview prewarm without submitting a warming job. + + See [Table.explain_prewarm_data][lancedb.table.Table.explain_prewarm_data] + for options, permissions, snapshot semantics, and limitations. + """ + return PrewarmDataPlan.from_json( + await self._inner.explain_prewarm_data( + columns, filter=filter, concurrency=concurrency + ) + ) + async def prewarm_data_async( self, columns: Optional[List[str]] = None, diff --git a/python/python/tests/test_e2e_remote_db.py b/python/python/tests/test_e2e_remote_db.py index f09581bff..9ef746ce1 100644 --- a/python/python/tests/test_e2e_remote_db.py +++ b/python/python/tests/test_e2e_remote_db.py @@ -308,3 +308,65 @@ def test_against_local_server(): table = conn.open_table("sift1m_ivf1024_pq16") df = table.search(np.random.rand(128)).to_pandas() assert len(df) == 10 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +async def test_prewarm_preview_against_server( + maintenance_connection_options, asynchronous +): + """Preview is typed, source-versioned, and creates no maintenance jobs.""" + from lancedb.prewarm import PrewarmDataPlan + + connection = ( + await lancedb.connect_async(**maintenance_connection_options) + if asynchronous + else lancedb.connect(**maintenance_connection_options) + ) + + async def call(method, *args, **kwargs): + result = method(*args, **kwargs) + return await result if asynchronous else result + + async def jobs(): + reader = await call(connection.execute_query, f'SHOW JOBS FOR TABLE "{name}"') + result = await call(reader.read_all) + if asynchronous: + return [row for batch in result for row in batch.to_pylist()] + return result.to_pylist() + + name = f"preview_{uuid4().hex}" + created = False + try: + table = await call(connection.create_table, name, [{"id": 1, "payload": "one"}]) + created = True + version = await table.version() if asynchronous else table.version + before = await jobs() + for predicate, mode, selected in [ + (None, "unfiltered", 1), + ("TRUE", "full_warm_fallback", 1), + ("FALSE", "constant", 0), + ("id > 10", "full_warm_fallback", 1), + ]: + preview = await call( + table.explain_prewarm_data, ["payload"], filter=predicate, concurrency=2 + ) + assert isinstance(preview, PrewarmDataPlan) + assert preview.table_version == version + assert preview.pruning.mode == mode + assert preview.pruning.input_fragments == 1 + assert preview.pruning.selected_fragments == selected + if mode == "full_warm_fallback": + assert preview.pruning.fallback_reason + assert await jobs() == before + assert (await table.version() if asynchronous else table.version) == version + # A preview does not reserve the source snapshot for a later request. + await call(table.add, [{"id": 2, "payload": "two"}]) + newer = await call(table.explain_prewarm_data) + assert newer.table_version > version + assert newer.pruning.input_fragments == 2 + assert await jobs() == before + finally: + if created: + await call(connection.drop_table, name) + connection.close() diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index b74450553..381847954 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -8214,7 +8214,9 @@ async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mod {"concurrency": 1.5}, ], ) -@pytest.mark.parametrize("method", ["prewarm_data", "prewarm_data_async"]) +@pytest.mark.parametrize( + "method", ["prewarm_data", "prewarm_data_async", "explain_prewarm_data"] +) def test_remote_data_prewarm_validates_before_submission(options, method): flight = pytest.importorskip("pyarrow.flight") @@ -8441,3 +8443,125 @@ def test_remote_compaction_rejects_boolean_budgets_without_submitting( with pytest.raises(ValueError, match="must be an integer, not a bool"): getattr(table, method)(compaction_options={option: value}) assert server.calls == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "mode,selected,ranges,reason", + [ + ("unfiltered", 3, None, None), + ("constant", 0, 0, None), + ("zonemap_ranges", 1, 2, None), + ("full_warm_fallback", 3, None, "no metadata proof"), + ("future_mode", 2, None, None), + ], +) +async def test_remote_data_prewarm_preview( + asynchronous, mode, selected, ranges, reason +): + from lancedb.prewarm import PrewarmDataPlan, PrewarmPruningSummary + + flight = pytest.importorskip("pyarrow.flight") + + class PreviewServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + payload = { + "format_version": 1, + "table_version": 42, + "plan": "metadata preview", + "pruning": { + "mode": mode, + "input_fragments": 3, + "selected_fragments": selected, + "pruned_fragments": 3 - selected, + "selected_row_ranges": ranges, + "fallback_reason": reason, + }, + } + return flight.RecordBatchStream( + pa.table({"plan_type": ["logical_plan"], "plan": [json.dumps(payload)]}) + ) + + server = PreviewServer() + with _mock_remote_sql_connection(server) as kwargs: + if asynchronous: + db = await lancedb.connect_async(**kwargs) + table = await db.create_table("test", [{"id": 1}]) + plan = await table.explain_prewarm_data( + ["attrs.score"], filter="id > 0", concurrency=4 + ) + else: + db = lancedb.connect(**kwargs) + table = db.create_table("test", [{"id": 1}]) + plan = table.explain_prewarm_data( + ["attrs.score"], filter="id > 0", concurrency=4 + ) + assert isinstance(plan, PrewarmDataPlan) + assert isinstance(plan.pruning, PrewarmPruningSummary) + assert plan.table_version == 42 + assert plan.pruning.mode == mode + assert plan.pruning.selected_fragments == selected + assert plan.pruning.selected_row_ranges == ranges + assert plan.pruning.fallback_reason == reason + assert len(server.tickets) == 1 + assert b"EXPLAIN (FORMAT JSON) PREWARM" in server.tickets[0] + assert b'"attrs"."score"' in server.tickets[0] + assert b"concurrency = 4" in server.tickets[0] + assert b"id > 0" in server.tickets[0] + + +@pytest.mark.parametrize( + "payload", + [ + "legacy display text", + '{"format_version":2,"table_version":42,"plan":"future","pruning":{}}', + '{"format_version":1,"table_version":42,"plan":"missing pruning"}', + ], +) +def test_remote_prewarm_preview_rejects_incompatible_payload_without_retry(payload): + flight = pytest.importorskip("pyarrow.flight") + + class PreviewServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream(pa.table({"plan": [payload]})) + + server = PreviewServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(Exception, match="valid structured preview"): + table.explain_prewarm_data() + assert len(server.tickets) == 1 + + +def test_remote_prewarm_preview_reports_old_server_format_support(): + flight = pytest.importorskip("pyarrow.flight") + + class OldServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + raise flight.FlightInternalError( + "Invalid explain format. Expected 'indent', 'tree', 'pgjson' " + "or 'graphviz'. Got 'JSON'" + ) + + server = OldServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises( + NotImplementedError, match=r"EXPLAIN \(FORMAT JSON\) PREWARM" + ): + table.explain_prewarm_data() + assert len(server.tickets) == 1 diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index ebc3c3006..90ae62d1b 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -6418,7 +6418,9 @@ def test_fts_exist_ok_matches_quoted_default_name(mem_db): @pytest.mark.asyncio @pytest.mark.parametrize("asynchronous", [False, True]) -@pytest.mark.parametrize("method", ["prewarm_data", "prewarm_data_async"]) +@pytest.mark.parametrize( + "method", ["prewarm_data", "prewarm_data_async", "explain_prewarm_data"] +) async def test_data_prewarm_job_is_unsupported_locally(tmp_path, asynchronous, method): if asynchronous: db = await lancedb.connect_async(tmp_path) diff --git a/python/src/table.rs b/python/src/table.rs index e421c939d..a47d82d98 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1913,6 +1913,24 @@ impl Table { }) } + #[pyo3(signature = (columns=None, *, filter=None, concurrency=None))] + pub fn explain_prewarm_data<'py>( + self_: PyRef<'py, Self>, + columns: Option>, + filter: Option, + concurrency: Option<&Bound<'py, PyAny>>, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let mut options = + lancedb::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()); + options.filter = filter; + options.concurrency = positive_u32_integer(concurrency, "concurrency")?; + future_into_py(self_.py(), async move { + let plan = inner.explain_prewarm_data(options).await.infer_error()?; + serde_json::to_string(&plan).map_err(|error| PyRuntimeError::new_err(error.to_string())) + }) + } + pub fn list_indices(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index a80e26ad9..a8f39fc2e 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -518,7 +518,8 @@ impl FlightService for TestSqlService { { return Err(error.clone()); } - if command.query.starts_with("PREWARM") + if (command.query.starts_with("PREWARM") + || command.query.starts_with("EXPLAIN (FORMAT JSON) PREWARM")) && let Some(error) = &self.prewarm_error { return Err(error.clone()); @@ -4671,7 +4672,16 @@ async fn remote_prewarm_errors_preserve_diagnostics_and_never_fall_back() { unsupported, "{error}" ); - assert_eq!(statements.lock().unwrap().len(), 1); + let preview_error = table + .explain_prewarm_data(Default::default()) + .await + .unwrap_err(); + assert_eq!( + matches!(preview_error, Error::NotSupported { .. }), + unsupported, + "{preview_error}" + ); + assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } } @@ -4782,6 +4792,12 @@ async fn remote_prewarm_rejects_historical_checkout_without_submitting() { let error = table.prewarm_data(None).await.unwrap_err(); assert!(matches!(error, Error::NotSupported { .. })); assert!(error.to_string().contains("historical version 7")); + let error = table + .explain_prewarm_data(Default::default()) + .await + .unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("historical version 7")); assert!(statements.lock().unwrap().is_empty()); shutdown.send(()).unwrap(); } @@ -4851,3 +4867,79 @@ async fn remote_compaction_tracks_registry_job_and_real_result() { ); shutdown.send(()).unwrap(); } + +#[tokio::test] +async fn remote_prewarm_preview_uses_sql_without_any_http_jobs() { + use crate::table::PrewarmDataOptions; + for azure in [false, true] { + let preview = serde_json::json!({ + "format_version":1,"table_version":42,"plan":"metadata preview", + "pruning":{"mode":"zonemap_ranges","input_fragments":4, + "selected_fragments":1,"pruned_fragments":3,"selected_row_ranges":2} + }); + let service = TestSqlService { + adaptive: true, + result: RecordBatch::try_from_iter([ + ( + "plan_type", + Arc::new(StringArray::from(vec!["logical_plan"])) as ArrayRef, + ), + ( + "plan", + Arc::new(StringArray::from(vec![preview.to_string()])) as ArrayRef, + ), + ]) + .unwrap(), + prewarm_azure_supported: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let mut config = ClientConfig::default(); + if azure { + config.extra_headers.insert( + "x-azure-storage-account-name".into(), + "sourceaccount".into(), + ); + } + let (sql, shutdown) = start_sql_service(service, config).await; + let client = client_with_handler(|_| -> http::Response { + panic!("preview must not use HTTP job APIs or REST fallback") + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "clips".into(), + vec!["team".into()], + "team$clips".into(), + Default::default(), + Some(sql), + ) + .with_branch(Some("experiment".into())); + let plan = table + .explain_prewarm_data( + PrewarmDataOptions::new() + .columns(["attrs.score"]) + .filter("id > 0") + .concurrency(4), + ) + .await + .unwrap(); + assert_eq!(plan.table_version, 42); + assert_eq!(plan.pruning.selected_row_ranges, Some(2)); + assert_eq!( + *statements.lock().unwrap(), + [ + "EXPLAIN (FORMAT JSON) PREWARM WITH (branch = 'experiment', concurrency = 4) AS SELECT \"attrs\".\"score\" FROM \"clips\" WHERE id > 0" + ] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.namespace_path == "team" && h.database == "analytics") + ); + shutdown.send(()).unwrap(); + } +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 790f21961..649edd133 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4806,6 +4806,44 @@ impl BaseTable for RemoteTable { )))) } + async fn explain_prewarm_data( + &self, + options: crate::table::PrewarmDataOptions, + ) -> Result { + if let Some(version) = *self.version.read().await { + return Err(Error::NotSupported { + message: format!( + "SQL PREWARM does not support historical version {version}; use checkout_latest() to preview the current branch" + ), + }); + } + let statement = format!( + "EXPLAIN (FORMAT JSON) {}", + prewarm::statement(&self.name, self.branch.as_deref(), &options)? + ); + let client = self.sql_client.as_ref().ok_or_else(|| Error::NotSupported { + message: "data prewarm previews require a Flight SQL endpoint supporting EXPLAIN (FORMAT JSON) PREWARM".into(), + })?; + let query = client + .execute_prewarm(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + }) + .await + .map_err(prewarm::map_explain_error)?; + let mut reader = query.reader().await.map_err(prewarm::map_explain_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader + .try_next() + .await + .map_err(prewarm::map_explain_error)? + { + batches.push(batch); + } + prewarm::plan(&batches) + } + async fn table_definition(&self) -> Result { let schema = self.schema().await?; TableDefinition::try_from_rich_schema(schema) diff --git a/rust/lancedb/src/remote/table/prewarm.rs b/rust/lancedb/src/remote/table/prewarm.rs index 8388b6350..d87465acf 100644 --- a/rust/lancedb/src/remote/table/prewarm.rs +++ b/rust/lancedb/src/remote/table/prewarm.rs @@ -103,6 +103,77 @@ pub(super) fn receipt(batches: &[RecordBatch]) -> Result<(String, u64)> { Ok((id.value(0).into(), version.value(0))) } +/// Decode the versioned JSON payload without depending on the display text. +pub(super) fn plan(batches: &[RecordBatch]) -> Result { + let invalid = || { + Error::Runtime { + message: "EXPLAIN PREWARM did not return a valid structured preview; a server supporting EXPLAIN (FORMAT JSON) PREWARM is required".into(), + } + }; + if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { + return Err(invalid()); + } + let batch = batches + .iter() + .find(|batch| batch.num_rows() == 1) + .ok_or_else(invalid)?; + let payload = batch + .column_by_name("plan") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if payload.is_null(0) { + return Err(invalid()); + } + #[derive(serde::Deserialize)] + struct Preview { + format_version: u32, + #[serde(flatten)] + plan: crate::table::PrewarmDataPlan, + } + let preview: Preview = serde_json::from_str(payload.value(0)).map_err(|_| invalid())?; + if preview.format_version != 1 { + return Err(invalid()); + } + Ok(preview.plan) +} + +pub(super) fn map_explain_error(error: Error) -> Error { + fn unsupported_format(error: &Error) -> bool { + match error { + Error::Sql { + message, grpc_code, .. + } => { + let diagnostic = message.to_ascii_lowercase(); + // Older servers hand this EXPLAIN to DataFusion, which rejects + // JSON as a configuration error (sometimes gRPC Internal). + (*grpc_code == tonic::Code::Internal as i32 + || *grpc_code == tonic::Code::InvalidArgument as i32) + && diagnostic.contains("invalid explain format.") + && diagnostic.contains("got 'json'") + } + Error::JobFailed { failure, .. } => { + failure.source.as_deref().is_some_and(unsupported_format) + } + _ => false, + } + } + let error = if unsupported_format(&error) { + Error::NotSupported { + message: error.to_string(), + } + } else { + map_error(error) + }; + match error { + Error::NotSupported { message } => Error::NotSupported { + message: format!( + "Data prewarm previews require a server supporting EXPLAIN (FORMAT JSON) PREWARM; upgrade the server. Preview will not fall back to text or REST. Server diagnostic: {message}" + ), + }, + other => other, + } +} + pub(super) fn map_error(error: Error) -> Error { fn unsupported(error: &Error) -> Option<&Error> { match error { @@ -143,6 +214,85 @@ mod tests { use arrow_schema::{DataType, Field, Schema}; use std::sync::Arc; + #[test] + fn preview_maps_old_explain_format_errors_without_masking_auth_or_filters() { + for (code, message, unsupported) in [ + ( + tonic::Code::Internal, + "Invalid or Unsupported Configuration: Invalid explain format. Expected 'indent', 'tree', 'pgjson' or 'graphviz'. Got 'JSON'", + true, + ), + ( + tonic::Code::InvalidArgument, + "Invalid explain format. Got 'JSON'", + true, + ), + ( + tonic::Code::PermissionDenied, + "Invalid explain format. Got 'JSON'", + false, + ), + ( + tonic::Code::InvalidArgument, + "invalid filter expression", + false, + ), + ] { + let error = map_explain_error(Error::Sql { + message: message.into(), + request_id: "preview-request".into(), + grpc_code: code as i32, + metadata: Default::default(), + }); + assert_eq!( + matches!(error, Error::NotSupported { .. }), + unsupported, + "{error}" + ); + assert!(error.to_string().contains(message)); + assert!(error.to_string().contains("preview-request")); + if unsupported { + assert!(error.to_string().contains("EXPLAIN (FORMAT JSON) PREWARM")); + } + } + } + + #[test] + fn preview_requires_one_versioned_typed_payload() { + let valid = serde_json::json!({ + "format_version": 1, "table_version": 42, "plan": "display only", + "pruning": {"mode":"future_mode", "input_fragments":3, + "selected_fragments":0, "pruned_fragments":3, "selected_row_ranges":0}, + "future_field": true, + }); + let batch = |value: &serde_json::Value| { + RecordBatch::try_from_iter([( + "plan", + Arc::new(StringArray::from(vec![value.to_string()])) as arrow_array::ArrayRef, + )]) + .unwrap() + }; + let result = plan(&[batch(&valid)]).unwrap(); + assert_eq!(result.table_version, 42); + assert_eq!(result.pruning.mode, "future_mode"); + assert_eq!(result.pruning.selected_row_ranges, Some(0)); + assert_eq!(result.pruning.fallback_reason, None); + for mutation in ["version", "missing", "negative", "text"] { + let mut value = valid.clone(); + match mutation { + "version" => value["format_version"] = 2.into(), + "missing" => { + value.as_object_mut().unwrap().remove("pruning"); + } + "negative" => value["pruning"]["selected_fragments"] = (-1).into(), + _ => value = "legacy display text".into(), + } + assert!(plan(&[batch(&value)]).is_err(), "{mutation}"); + } + assert!(plan(&[]).is_err()); + assert!(plan(&[batch(&valid), batch(&valid)]).is_err()); + } + #[test] fn quotes_paths_branch_and_filter_without_changing_options() { let options = PrewarmDataOptions::new() diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 156474f23..775261bb5 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -88,7 +88,7 @@ pub mod merge; pub mod optimize; pub use optimize::CompactionResult; mod prewarm; -pub use prewarm::{PrewarmDataOptions, PrewarmDataResult}; +pub use prewarm::{PrewarmDataOptions, PrewarmDataPlan, PrewarmDataResult, PrewarmPruningSummary}; pub(crate) mod primary_key; pub mod query; pub mod refresh; @@ -701,6 +701,13 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "data prewarm jobs are only supported on remote tables".into(), }) } + /// Preview data-cache prewarm without submitting a warming job. + async fn explain_prewarm_data(&self, _options: PrewarmDataOptions) -> Result { + Err(Error::NotSupported { + message: "data prewarm previews are only supported on remote tables".into(), + }) + } + /// Get statistics about the index. async fn index_stats(&self, index_name: &str) -> Result>; /// Merge insert new records into the table. @@ -3199,6 +3206,29 @@ impl Table { self.inner.prewarm_data_async(options).await } + /// Preview data-cache prewarm using the same options as [`Self::prewarm_data_async`]. + /// + /// Requires LanceDB Enterprise with structured SQL PREWARM previews and + /// SELECT permission plus database/namespace usage. Reads metadata without + /// submitting a warming job. A later submission plans its own snapshot. + /// Historical-version and Embedded handles are unsupported. + /// + /// ```no_run + /// # async fn preview(table: &lancedb::Table) -> lancedb::Result<()> { + /// use lancedb::table::PrewarmDataOptions; + /// let plan = table.explain_prewarm_data(PrewarmDataOptions::new() + /// .columns(["video"]).filter("quality > 0.7")).await?; + /// println!("version={}, selected={}", plan.table_version, plan.pruning.selected_fragments); + /// # Ok(()) + /// # } + /// ``` + pub async fn explain_prewarm_data( + &self, + options: PrewarmDataOptions, + ) -> Result { + self.inner.explain_prewarm_data(options).await + } + /// Poll until the columns are fully indexed. Will return Error::Timeout if the columns /// are not fully indexed within the timeout. pub async fn wait_for_index( diff --git a/rust/lancedb/src/table/prewarm.rs b/rust/lancedb/src/table/prewarm.rs index 1d0f8c002..badb5a8ad 100644 --- a/rust/lancedb/src/table/prewarm.rs +++ b/rust/lancedb/src/table/prewarm.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! Options for submitting a durable data-cache prewarm job. +//! Options, previews, and results for data-cache prewarm. /// Data prewarm settings for [`super::Table::prewarm_data_async`]. /// @@ -44,6 +44,40 @@ impl PrewarmDataOptions { } } +/// Metadata-only preview of a data-cache prewarm on one table snapshot. +/// +/// No warming job is submitted. A later submission chooses its own snapshot and +/// may produce a different plan if the table or index metadata has changed. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct PrewarmDataPlan { + /// Source snapshot used to produce this preview. + pub table_version: u64, + /// Human-readable plan, intended for display rather than parsing. + pub plan: String, + /// Conservative metadata pruning, not exact row-filter matches. + pub pruning: PrewarmPruningSummary, +} + +/// Conservative pruning facts for a PREWARM preview. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct PrewarmPruningSummary { + /// Proof mode, such as `unfiltered`, `constant`, `zonemap_ranges`, or + /// `full_warm_fallback`. Future servers may return additional modes. + pub mode: String, + /// Fragments in the source snapshot. + pub input_fragments: u64, + /// Fragments selected for warming. + pub selected_fragments: u64, + /// Fragments excluded by metadata proof. + pub pruned_fragments: u64, + /// Candidate physical intervals, when known; not an exact matching-row count. + pub selected_row_ranges: Option, + /// Why metadata could not prune, when reported. + pub fallback_reason: Option, +} + /// Reported outcome of a remote data-prewarm job. Counts describe executor work; /// absent measurements remain unknown rather than being inferred as zero. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -108,6 +142,11 @@ mod tests { .prewarm_data_async(PrewarmDataOptions::new().filter("id > 0")) .await .unwrap_err(); + let preview_error = table + .explain_prewarm_data(Default::default()) + .await + .unwrap_err(); + assert!(matches!(preview_error, crate::Error::NotSupported { .. })); assert!(matches!(error, crate::Error::NotSupported { .. })); assert!( error From 23f9d5a74146cf2e8a1e402cdcaf71e09631b2a2 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Wed, 18 Nov 2026 11:07:32 -0800 Subject: [PATCH 18/78] feat(sdk): support bound parameters in data prewarm (#5076) Data prewarm methods accept filter expressions but cannot bind their values, which forces applications to build literal SQL themselves. This adds optional positional and named parameters to data-prewarm submission and typed previews across Rust, Python, and TypeScript. Values use the existing typed Arrow SQL transport and remain separate from the filter text. Existing calls and job-handle behavior are preserved; parameterized filters require a compatible LanceDB Enterprise server. This was accomplished with the following changes: - Add `PrewarmDataOptions::parameters(RecordBatch)` and forward the batch through SQL submission and `EXPLAIN PREWARM` requests. - Reuse Python's `QueryParameters` conversion for synchronous/asynchronous, legacy/job-returning, and typed preview methods. - Add TypeScript positional-array, named-object, and explicit Arrow parameter inputs, with safe scalar encoding and native IPC forwarding. - Keep parameter values out of Rust option debug output and reject invalid input before submission where possible. - Add transport and codec regression tests, including injection-shaped strings, typed Arrow values, legacy method forwarding, and typed preview bindings. - Document bound filters in the cache-prewarm guide with Python, TypeScript, and Rust examples; update generic SQL parameter documentation. ### Usage and behaviour ```python job = table.prewarm_data_async( ["payload"], filter="id >= $minimum", parameters={"minimum": 1000} ) job.wait() ``` ```typescript const job = await table.prewarmDataAsync({ columns: ["payload"], filter: "id >= $1", parameters: [1000], }); await job.wait(); ``` Python accepts a sequence, mapping, or one-row Arrow batch/table. TypeScript accepts scalar arrays/objects or one-row Arrow input; safe integers and bigint use Int64, fractional numbers use Float64. Rust accepts a one-row Arrow batch. Parameters bind filter values, while table identity, branch, and concurrency keep their existing interfaces. Submission-only methods also forward bindings and retain their existing return behavior. Typed preview helpers accept the same parameters without creating a job. ### Testing Python prewarm Flight transport tests pass (65 cases), Embedded compatibility tests pass (6 cases), and focused Node parameter/prewarm tests pass (45 cases, including ten codec and native-boundary cases). Earlier matching-server verification passed 57 Python/SQL scenarios, 14 Node scenarios, and Rust SDK checks, covering selective and empty plans, typed values, authorization, pinned branches, legacy methods, and injection-shaped strings. A bound job also survives a full runtime restart. The guide submission examples were also verified in Python, TypeScript, and Rust; the TypeScript example type-checks. Live-server checks used filesystem storage. --- docs/src/js/classes/Table.md | 7 +- docs/src/js/globals.md | 2 + docs/src/js/interfaces/PrewarmDataOptions.md | 10 ++ .../js/type-aliases/QueryParameterValue.md | 20 ++++ docs/src/js/type-aliases/QueryParameters.md | 16 +++ docs/web/enterprise/cache-prewarm.mdx | 69 ++++++++--- nodejs/__test__/sql_parameters.test.ts | 111 ++++++++++++++++++ nodejs/__test__/table.test.ts | 6 +- nodejs/lancedb/index.ts | 2 + nodejs/lancedb/sql.ts | 104 ++++++++++++++++ nodejs/lancedb/table.ts | 37 ++++-- nodejs/src/table.rs | 16 +++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/db.py | 7 +- python/python/lancedb/remote/table.py | 18 ++- python/python/lancedb/table.py | 61 ++++++++-- python/python/tests/test_remote_db.py | 84 +++++++++++++ python/src/table.rs | 8 +- rust/lancedb/src/connection.rs | 5 +- rust/lancedb/src/remote/table.rs | 4 +- rust/lancedb/src/remote/table/prewarm.rs | 33 ++++++ rust/lancedb/src/table/prewarm.rs | 41 ++++++- 22 files changed, 613 insertions(+), 50 deletions(-) create mode 100644 docs/src/js/type-aliases/QueryParameterValue.md create mode 100644 docs/src/js/type-aliases/QueryParameters.md create mode 100644 nodejs/__test__/sql_parameters.test.ts create mode 100644 nodejs/lancedb/sql.ts diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 63b6cffa0..72f68c40f 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -679,7 +679,9 @@ with an unsupported-operation error. #### Example ```ts -const plan = await table.explainPrewarmData({columns: ["video"], filter: "quality > 0.7"}); +const plan = await table.explainPrewarmData({ + columns: ["video"], filter: "quality > $minimum", parameters: {minimum: 0.7}, +}); console.log(plan.pruning.selectedFragments); ``` @@ -1221,7 +1223,8 @@ the job. After `job.refresh()`, `job.spec.table_version` is the pinned version. ```ts const job = await table.prewarmDataAsync({ - columns: ["video"], filter: "quality > 0.7", concurrency: 4, + columns: ["video"], filter: "quality > $minimum", + parameters: { minimum: 0.7 }, concurrency: 4, }); await job.wait(); ``` diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 3c348faac..0a0742389 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -191,6 +191,8 @@ - [JobProgressCallback](type-aliases/JobProgressCallback.md) - [MaterializedViewSelect](type-aliases/MaterializedViewSelect.md) - [MultiVector](type-aliases/MultiVector.md) +- [QueryParameterValue](type-aliases/QueryParameterValue.md) +- [QueryParameters](type-aliases/QueryParameters.md) - [RecordBatchLike](type-aliases/RecordBatchLike.md) - [SchemaLike](type-aliases/SchemaLike.md) - [TableLike](type-aliases/TableLike.md) diff --git a/docs/src/js/interfaces/PrewarmDataOptions.md b/docs/src/js/interfaces/PrewarmDataOptions.md index 4815b84fb..fae916320 100644 --- a/docs/src/js/interfaces/PrewarmDataOptions.md +++ b/docs/src/js/interfaces/PrewarmDataOptions.md @@ -37,3 +37,13 @@ optional filter: string; ``` A single SQL predicate for conservative metadata pruning. + +*** + +### parameters? + +```ts +optional parameters: QueryParameters; +``` + +Typed positional or named filter values, sent separately from SQL. diff --git a/docs/src/js/type-aliases/QueryParameterValue.md b/docs/src/js/type-aliases/QueryParameterValue.md new file mode 100644 index 000000000..a8f275052 --- /dev/null +++ b/docs/src/js/type-aliases/QueryParameterValue.md @@ -0,0 +1,20 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / QueryParameterValue + +# Type Alias: QueryParameterValue + +```ts +type QueryParameterValue: + | string + | number + | bigint + | boolean + | Date + | Uint8Array + | null; +``` + +Scalar SQL values. Use a one-row Arrow table for explicit Arrow types. diff --git a/docs/src/js/type-aliases/QueryParameters.md b/docs/src/js/type-aliases/QueryParameters.md new file mode 100644 index 000000000..dfce3ed30 --- /dev/null +++ b/docs/src/js/type-aliases/QueryParameters.md @@ -0,0 +1,16 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / QueryParameters + +# Type Alias: QueryParameters + +```ts +type QueryParameters: readonly QueryParameterValue[] | Readonly> | TableLike | RecordBatchLike; +``` + +Values for `$1`/`$name` placeholders, sent separately from SQL text. +Arrays bind by position; objects bind by name. Arrow columns bind both ways. +Safe integers and bigint use Int64; fractional numbers use Float64. +Arrow input preserves explicit types. diff --git a/docs/web/enterprise/cache-prewarm.mdx b/docs/web/enterprise/cache-prewarm.mdx index 56a091364..007cff0ab 100644 --- a/docs/web/enterprise/cache-prewarm.mdx +++ b/docs/web/enterprise/cache-prewarm.mdx @@ -14,7 +14,7 @@ the [tiered index cache](/enterprise/tiered-index-cache), and [on-demand data prewarm](#on-demand-data-prewarm) fills the [data page cache](/enterprise/data-page-cache) through a durable job. -For startup index prewarm, you configure which tables to warm. Each plan +For startup index prewarm, you configure which tables to warm. Each executor loads those tables' indexes before it joins the fleet. The executor does not accept queries until startup prewarming finishes. @@ -32,7 +32,7 @@ an idempotent hint that loads a built index into memory ahead of a query. }}}%% flowchart LR List[("Configured list
of tables to prewarm")] - Start["Plan executor starts
(not ready — no queries served)"] --> Warm["Loads the configured
tables' indexes into cache"] + Start["Executor starts
(not ready — no queries served)"] --> Warm["Loads the configured
tables' indexes into cache"] List -.-> Warm Warm --> Ready["Ready — joins the fleet,
starts serving queries"] classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 @@ -52,7 +52,7 @@ flowchart LR }}}%% flowchart LR List[("Configured list
of tables to prewarm")] - Start["Plan executor starts
(not ready — no queries served)"] --> Warm["Loads the configured
tables' indexes into cache"] + Start["Executor starts
(not ready — no queries served)"] --> Warm["Loads the configured
tables' indexes into cache"] List -.-> Warm Warm --> Ready["Ready — joins the fleet,
starts serving queries"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 @@ -91,7 +91,8 @@ The table handle determines the database, namespace, and branch in every SDK. from datetime import timedelta job = table.prewarm_data_async( - ["video"], filter="quality > 0.7", concurrency=4 + ["video"], filter="quality > $minimum", + parameters={"minimum": 0.7}, concurrency=4 ) print(job.id) result = job.wait(timeout=timedelta(minutes=10), progress=print) @@ -105,7 +106,8 @@ db.open_job(job.id).wait() ```typescript const job = await table.prewarmDataAsync({ columns: ["video"], - filter: "quality > 0.7", + filter: "quality > $1", + parameters: [0.7], concurrency: 4, }); console.log(job.id); @@ -121,14 +123,20 @@ if (job.id !== null) { ```rust use std::time::Duration; +use std::sync::Arc; +use arrow_array::{ArrayRef, Float64Array, RecordBatch}; use lancedb::job::JobWaitOptions; use lancedb::table::{PrewarmDataOptions, PrewarmDataResult}; +let parameters = RecordBatch::try_from_iter([ + ("minimum", Arc::new(Float64Array::from(vec![0.7])) as ArrayRef), +])?; let job = table .prewarm_data_async( PrewarmDataOptions::new() .columns(["video"]) - .filter("quality > 0.7") + .filter("quality > $minimum") + .parameters(parameters) .concurrency(4), ) .await?; @@ -150,8 +158,22 @@ The method returns when the job is accepted. Waiting finishes when warming reaches a terminal state; a timeout does not cancel the job. Use `job.refresh()` and `job.spec["table_version"]` to inspect the captured source version. In Python's asynchronous API, await submission and `job.wait()`. -Node exposes `table.prewarmDataAsync({ columns, filter, concurrency })` with -the same lifecycle. +The TypeScript SDK exposes +`table.prewarmDataAsync({ columns, filter, parameters, concurrency })` with the +same lifecycle. + +Pass `parameters` alongside a filter to bind positional `$1`/`$2` or named +`$name` values. Python accepts a sequence, mapping, or one-row Arrow batch/table; +TypeScript accepts a scalar array, named object, or one-row Arrow batch/table. +Rust accepts a one-row Arrow `RecordBatch`. Values travel separately from SQL +text, and table/column identifiers, branch, and concurrency retain their existing +interfaces. Existing literal filters continue to work without parameters. + +Bound filters require an Enterprise server that supports parameterized PREWARM. +The server accepts up to 1,024 scalar parameters and 64 KiB of encoded Arrow IPC. +Missing, unused, malformed, oversized, and unsupported bindings fail before job +creation. TypeScript encodes safe integer numbers and bigint as Int64 and +fractional numbers as Float64; use Arrow input when an explicit type is needed. Waiting returns a typed `PrewarmDataResult`: the pinned source version, selected fragment count, targeted/completed executor counts, and partial @@ -197,7 +219,7 @@ it creates no warming job and does not use the job-monitoring APIs. from lancedb.prewarm import PrewarmDataPlan plan: PrewarmDataPlan = table.explain_prewarm_data( - ["payload"], filter="id >= 1000", concurrency=4 + ["payload"], filter="id >= $minimum", parameters={"minimum": 1000}, concurrency=4 ) print(plan.table_version) print(plan.pruning.mode) @@ -214,7 +236,8 @@ import type { PrewarmDataPlan } from "@lancedb/lancedb"; const plan: PrewarmDataPlan = await table.explainPrewarmData({ columns: ["payload"], - filter: "id >= 1000", + filter: "id >= $minimum", + parameters: { minimum: 1000 }, concurrency: 4, }); console.log(plan.tableVersion); @@ -225,13 +248,19 @@ console.log(plan.pruning.selectedRowRanges, plan.pruning.fallbackReason); ```rust +use std::sync::Arc; +use arrow_array::{ArrayRef, Int64Array, RecordBatch}; use lancedb::table::{PrewarmDataOptions, PrewarmDataPlan}; +let parameters = RecordBatch::try_from_iter([ + ("minimum", Arc::new(Int64Array::from(vec![1000])) as ArrayRef), +])?; let plan: PrewarmDataPlan = table .explain_prewarm_data( PrewarmDataOptions::new() .columns(["payload"]) - .filter("id >= 1000") + .filter("id >= $minimum") + .parameters(parameters) .concurrency(4), ) .await?; @@ -255,15 +284,25 @@ when reported. Pruning modes may expand in future server versions. A preview doe resolves and plans its own source version. Unsupported servers fail explicitly without falling back to text parsing or REST. +Python's SQL interface also accepts bindings for a preview without submitting a +warming job: + +```python +plan = db.execute_query( + "EXPLAIN PREWARM AS SELECT video FROM clips WHERE quality > $minimum", + parameters={"minimum": 0.7}, +).read_all() +``` + The filter is a single SQL predicate used for conservative metadata pruning. Unknown or unavailable metadata keeps data eligible for warming. Omitted columns warm all fields; concurrency must be a positive integer. Historical version checkouts are unsupported: use the latest version of the selected branch. The server never needs to scan rows merely to evaluate the predicate. -`prewarm_data(columns, filter=..., concurrency=...)` and -`prewarmData({ columns, filter, concurrency })` accept the same options as the -job-returning methods but return after acceptance without retaining the handle. +`prewarm_data(columns, filter=..., parameters=..., concurrency=...)` and +`prewarmData({ columns, filter, parameters, concurrency })` accept the same +options as the job-returning methods but return after acceptance without retaining the handle. The existing TypeScript `prewarmData(columns)` array form remains supported. These methods require SQL PREWARM support and Flight SQL connectivity. Unsupported servers fail without a REST fallback or silently @@ -280,6 +319,6 @@ already-cached data is safe. Index prewarm keeps its existing behavior. The deserialized-index cache populated by startup index prewarm.
- Where plan executors and query nodes sit in the serving fleet. + Where executors and query nodes sit in the serving fleet.
diff --git a/nodejs/__test__/sql_parameters.test.ts b/nodejs/__test__/sql_parameters.test.ts new file mode 100644 index 000000000..2e8c979df --- /dev/null +++ b/nodejs/__test__/sql_parameters.test.ts @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { Int32, Table, tableFromIPC, vectorFromArray } from "../lancedb/arrow"; +import { toParameterBuffer } from "../lancedb/sql"; +import { LocalTable } from "../lancedb/table"; + +describe("SQL parameter encoding", () => { + test.each([false, true])( + "prewarm submission and preview forward typed bindings (named: %s)", + async (named) => { + const attack = "training' OR TRUE; DROP TABLE items; --"; + const parameters = named ? { minimum: 42n, tag: attack } : [42n, attack]; + const filter = named + ? "id >= $minimum AND tag = $tag" + : "id >= $1 AND tag = $2"; + const submission = jest.fn().mockResolvedValue({}); + const preview = jest.fn().mockResolvedValue( + JSON.parse(`{ + "table_version": 42, + "plan": "metadata preview", + "pruning": { + "mode": "zonemap_ranges", + "input_fragments": 3, + "selected_fragments": 1, + "pruned_fragments": 2, + "selected_row_ranges": 2 + } + }`), + ); + const table = new LocalTable({ + prewarmDataAsync: submission, + explainPrewarmData: preview, + } as never); + await table.prewarmDataAsync({ filter, parameters }); + const plan = await table.explainPrewarmData({ filter, parameters }); + expect(plan.tableVersion).toBe(42); + expect(plan.pruning.selectedFragments).toBe(1); + for (const call of [submission, preview]) { + expect(call).toHaveBeenCalledTimes(1); + const options = call.mock.calls[0][0]; + expect(options.filter).toBe(filter); + expect(options.filter).not.toContain(attack); + expect(Buffer.isBuffer(options.parameters)).toBe(true); + const batch = tableFromIPC(options.parameters); + expect(batch.schema.fields.map((field) => field.name)).toEqual( + named ? ["minimum", "tag"] : ["1", "2"], + ); + expect(batch.getChildAt(0)?.get(0)).toBe(42n); + expect(batch.getChildAt(1)?.get(0)).toBe(attack); + } + }, + ); + + test("positional and named bindings preserve values without SQL interpolation", async () => { + const attack = "training' OR TRUE; DROP TABLE items; --"; + const date = new Date("2026-01-02T00:00:00Z"); + const batch = tableFromIPC( + await toParameterBuffer([ + 42n, + attack, + null, + true, + date, + 0.7, + new Uint8Array([1, 2]), + ]), + ); + expect(batch.schema.fields.map((field) => field.name)).toEqual([ + "1", + "2", + "3", + "4", + "5", + "6", + "7", + ]); + expect(batch.getChildAt(0)?.get(0)).toBe(42n); + expect(batch.getChildAt(1)?.get(0)).toBe(attack); + expect(batch.getChildAt(2)?.get(0)).toBeNull(); + expect(batch.getChildAt(4)?.get(0)).toBe(date.getTime()); + const named = tableFromIPC( + await toParameterBuffer({ minimum: 42n, tag: attack }), + ); + expect(named.schema.fields.map((field) => field.name)).toEqual([ + "minimum", + "tag", + ]); + expect(named.getChild("tag")?.get(0)).toBe(attack); + }); + + test("explicit Arrow input preserves its types", async () => { + const input = new Table({ minimum: vectorFromArray([42], new Int32()) }); + for (const parameters of [input, input.batches[0]]) { + const decoded = tableFromIPC(await toParameterBuffer(parameters)); + expect(decoded.schema.fields[0].type.toString()).toBe("Int32"); + expect(decoded.getChildAt(0)?.get(0)).toBe(42); + } + }); + + test.each([ + [], + { value: undefined }, + { value: 2 ** 53 }, + { value: 1n << 63n }, + { value: {} }, + { value: new Date("invalid") }, + ])("invalid parameters fail before submission: %p", async (parameters) => { + await expect(toParameterBuffer(parameters as never)).rejects.toThrow(); + }); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 04d80d5f9..bfe69e931 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -4744,6 +4744,9 @@ describe.each(arrowVersions)( await expect(table.explainPrewarmData()).rejects.toThrow( "only supported on remote tables", ); + await expect( + table.explainPrewarmData({ filter: "id > $1", parameters: [1] }), + ).rejects.toThrow("only supported on remote tables"); await expect( table.explainPrewarmData({ unsupported: true } as never), ).rejects.toThrow("Unsupported data prewarm option"); @@ -4770,8 +4773,9 @@ describe.each(arrowVersions)( await expect( table.prewarmDataAsync({ columns: ["id"], - filter: "id > 0", + filter: "id > $1", concurrency: 2, + parameters: [1], }), ).rejects.toThrow("only supported on remote tables"); await expect( diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 8a2607724..b99d856cc 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -673,3 +673,5 @@ export type { PrewarmDataResult, PrewarmPruningSummary, } from "./prewarm"; + +export type { QueryParameters, QueryParameterValue } from "./sql"; diff --git a/nodejs/lancedb/sql.ts b/nodejs/lancedb/sql.ts new file mode 100644 index 000000000..e7cb4de6f --- /dev/null +++ b/nodejs/lancedb/sql.ts @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { + Binary, + Bool, + type DataType, + Float64, + Int64, + Null, + RecordBatchFileWriter, + type RecordBatchLike, + Table, + type TableLike, + TimestampMillisecond, + Utf8, + vectorFromArray, +} from "./arrow"; +import { sanitizeTable } from "./sanitize"; + +/** Scalar SQL values. Use a one-row Arrow table for explicit Arrow types. */ +export type QueryParameterValue = + | string + | number + | bigint + | boolean + | Date + | Uint8Array + | null; + +/** Values for `$1`/`$name` placeholders, sent separately from SQL text. + * Arrays bind by position; objects bind by name. Arrow columns bind both ways. + * Safe integers and bigint use Int64; fractional numbers use Float64. + * Arrow input preserves explicit types. + */ +export type QueryParameters = + | readonly QueryParameterValue[] + | Readonly> + | TableLike + | RecordBatchLike; + +/** @internal */ +export async function toParameterBuffer( + parameters: QueryParameters, +): Promise { + let table: Table; + if ( + "schema" in parameters && + parameters.schema !== null && + typeof parameters.schema === "object" && + "fields" in parameters.schema + ) { + const arrow = parameters as TableLike | RecordBatchLike; + table = sanitizeTable( + "batches" in arrow ? arrow : { schema: arrow.schema, batches: [arrow] }, + ); + } else { + const entries = Array.isArray(parameters) + ? parameters.map((value, index) => [String(index + 1), value] as const) + : Object.entries(parameters); + const columns = Object.fromEntries( + entries.map(([name, input]) => { + let value = input; + let type: DataType; + if (value === null) type = new Null(); + else if (typeof value === "string") type = new Utf8(); + else if (typeof value === "boolean") type = new Bool(); + else if (typeof value === "number") { + if ( + !Number.isFinite(value) || + (Number.isInteger(value) && !Number.isSafeInteger(value)) + ) { + throw new Error( + "Numeric parameters must be finite and integers must be safe; use bigint for Int64", + ); + } + type = Number.isInteger(value) ? new Int64() : new Float64(); + if (Number.isInteger(value)) value = BigInt(value); + } else if (typeof value === "bigint") { + if (value < -(1n << 63n) || value >= 1n << 63n) { + throw new Error("bigint parameters must fit Int64"); + } + type = new Int64(); + } else if (value instanceof Date && Number.isFinite(value.getTime())) { + type = new TimestampMillisecond(); + } else if (value instanceof Uint8Array) type = new Binary(); + else + throw new Error( + "Query parameters must be scalar values or a one-row Arrow table", + ); + return [name, vectorFromArray([value], type)]; + }), + ); + table = new Table(columns); + } + if (table.numRows !== 1) { + throw new Error( + `Query parameters must contain exactly one row, got ${table.numRows}`, + ); + } + return Buffer.from( + await RecordBatchFileWriter.writeAll(table).toUint8Array(), + ); +} diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 3b3e7abe5..eecb83fb6 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -71,6 +71,7 @@ import { instanceOfFullTextQuery, } from "./query"; import { sanitizeType } from "./sanitize"; +import { QueryParameters, toParameterBuffer } from "./sql"; import { IntoSql, toSQL } from "./util"; export { IndexConfig } from "./native"; export { @@ -179,6 +180,8 @@ export interface PrewarmDataOptions { columns?: string[]; /** A single SQL predicate for conservative metadata pruning. */ filter?: string; + /** Typed positional or named filter values, sent separately from SQL. */ + parameters?: QueryParameters; /** Positive per-executor concurrency, at most 4294967295. */ concurrency?: number; } @@ -624,7 +627,8 @@ export abstract class Table { * * @example * const job = await table.prewarmDataAsync({ - * columns: ["video"], filter: "quality > 0.7", concurrency: 4, + * columns: ["video"], filter: "quality > $minimum", + * parameters: { minimum: 0.7 }, concurrency: 4, * }); * await job.wait(); */ @@ -643,7 +647,9 @@ export abstract class Table { * with an unsupported-operation error. * * @example - * const plan = await table.explainPrewarmData({columns: ["video"], filter: "quality > 0.7"}); + * const plan = await table.explainPrewarmData({ + * columns: ["video"], filter: "quality > $minimum", parameters: {minimum: 0.7}, + * }); * console.log(plan.pruning.selectedFragments); */ async explainPrewarmData( @@ -1668,9 +1674,10 @@ export class LocalTable extends Table { async prewarmDataAsync( options?: PrewarmDataOptions, ): Promise> { - validatePrewarmDataOptions(options); return new Job( - await this.inner.prewarmDataAsync(options), + await this.inner.prewarmDataAsync( + await toNativePrewarmDataOptions(options), + ), decodePrewarmDataResult, ); } @@ -1678,8 +1685,11 @@ export class LocalTable extends Table { async explainPrewarmData( options?: PrewarmDataOptions, ): Promise { - validatePrewarmDataOptions(options); - return decodePrewarmDataPlan(await this.inner.explainPrewarmData(options)); + return decodePrewarmDataPlan( + await this.inner.explainPrewarmData( + await toNativePrewarmDataOptions(options), + ), + ); } async waitForIndex( @@ -2399,9 +2409,22 @@ function validateCompactionOptions(options?: CompactionOptions): void { } } +async function toNativePrewarmDataOptions(options?: PrewarmDataOptions) { + validatePrewarmDataOptions(options); + return options === undefined + ? undefined + : { + ...options, + parameters: + options.parameters === undefined + ? undefined + : await toParameterBuffer(options.parameters), + }; +} + function validatePrewarmDataOptions(options?: PrewarmDataOptions): void { for (const key of Object.keys(options ?? {})) { - if (!["columns", "filter", "concurrency"].includes(key)) { + if (!["columns", "filter", "concurrency", "parameters"].includes(key)) { throw new Error(`Unsupported data prewarm option: ${key}`); } } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 6a0a8cb60..1a4c3e91c 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -33,6 +33,7 @@ pub struct PrewarmDataOptions { pub columns: Option>, pub filter: Option, pub concurrency: Option, + pub parameters: Option, } impl PrewarmDataOptions { @@ -40,6 +41,21 @@ impl PrewarmDataOptions { let mut options = lancedb::table::PrewarmDataOptions::new().columns(self.columns.unwrap_or_default()); options.filter = self.filter; + if let Some(parameters) = self.parameters { + let mut batches = ipc_file_to_batches(parameters.to_vec()) + .and_then(|reader| { + reader + .collect::, _>>() + .map_err(Into::into) + }) + .map_err(|error| napi::Error::from_reason(error.to_string()))?; + if batches.len() != 1 || batches[0].num_rows() != 1 { + return Err(napi::Error::from_reason( + "prewarm parameters must contain one row in one batch", + )); + } + options.parameters = Some(batches.remove(0)); + } if let Some(value) = self.concurrency { if !value.is_finite() || value.fract() != 0.0 || value < 1.0 || value > u32::MAX as f64 { diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index cdeebf6ef..98936e0a2 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -651,6 +651,7 @@ class Table: *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[pa.RecordBatch] = None, ) -> str: ... async def prewarm_data_async( self, @@ -658,6 +659,7 @@ class Table: *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[pa.RecordBatch] = None, ) -> Job: ... async def list_indices(self) -> list[IndexConfig]: ... async def tokenize( diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 8c9901aff..86001ef10 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1738,8 +1738,11 @@ class DBConnection(EnforceOverrides): parameters=[np.array([0.1, 0.2, 0.3], dtype=np.float32), 10], ) - Parameters are supported in queries, not in DDL or DML. With or - without parameters, the server chooses whether to stream rows on the + Parameters are supported in queries and, on compatible Enterprise servers, + scalar filter values in ``PREWARM`` and ``EXPLAIN PREWARM``. Support for + other statement types depends on the server. + + With or without parameters, the server chooses whether to stream rows on the initial call or return a polling continuation. The reader follows either path transparently. Dropping an unread handle or its reader stops a directly streamed query; deferred execution requires explicit diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index a5d08bd72..f984b47fb 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -24,6 +24,7 @@ from typing import ( import warnings from lancedb import __version__ +from lancedb.sql import QueryParameters from lancedb._blob import BlobFile from lancedb._lancedb import ( @@ -1452,6 +1453,7 @@ class RemoteTable(Table): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> None: """Prewarm data for the table. @@ -1474,6 +1476,9 @@ class RemoteTable(Table): The columns to prewarm. If None, all columns are prewarmed. filter: str, optional A single SQL predicate for conservative metadata pruning. + parameters: sequence, mapping, or one-row Arrow batch/table, optional + Scalar values for ``$1``/``$name`` placeholders in ``filter``. + Values are sent separately from SQL; requires server support. concurrency: int, optional Positive per-executor warming concurrency; omitted uses the server default. @@ -1483,7 +1488,9 @@ class RemoteTable(Table): ... ["payload"], filter="quality > 0.7", concurrency=4) """ return LOOP.run( - self._table.prewarm_data(columns, filter=filter, concurrency=concurrency) + self._table.prewarm_data( + columns, filter=filter, concurrency=concurrency, parameters=parameters + ) ) def explain_prewarm_data( @@ -1492,6 +1499,7 @@ class RemoteTable(Table): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> PrewarmDataPlan: """Preview prewarm without submitting a warming job. @@ -1500,7 +1508,7 @@ class RemoteTable(Table): """ return LOOP.run( self._table.explain_prewarm_data( - columns, filter=filter, concurrency=concurrency + columns, filter=filter, concurrency=concurrency, parameters=parameters ) ) @@ -1510,11 +1518,15 @@ class RemoteTable(Table): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> Job[PrewarmDataResult]: return Job( LOOP.run( self._table.prewarm_data_async( - columns, filter=filter, concurrency=concurrency + columns, + filter=filter, + concurrency=concurrency, + parameters=parameters, ) ) ) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index d9c20e287..dfb1d1cde 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -47,6 +47,7 @@ from ._blob import ( ) from .types import BlobMode from lancedb.arrow import peek_reader +from lancedb.sql import QueryParameters, to_parameter_batch from lancedb.background_loop import LOOP, embedding_executor from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult from lancedb.job import AsyncJob, Job, _typed_job @@ -2019,6 +2020,7 @@ class Table(ABC): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> None: """Submit remote data prewarm and return after acceptance. @@ -2037,7 +2039,9 @@ class Table(ABC): >>> table.prewarm_data( # doctest: +SKIP ... ["payload"], filter="quality > 0.7", concurrency=4) """ - self.prewarm_data_async(columns, filter=filter, concurrency=concurrency) + self.prewarm_data_async( + columns, filter=filter, concurrency=concurrency, parameters=parameters + ) def explain_prewarm_data( self, @@ -2045,13 +2049,15 @@ class Table(ABC): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> PrewarmDataPlan: """Preview data prewarm without creating a warming job. - Accepts the same columns, filter, and concurrency as ``prewarm_data_async`` - and uses the table handle's namespace and branch. Requires LanceDB - Enterprise with structured SQL previews, table Select, and database/namespace - Usage. Historical-version and Embedded handles are unsupported. + Accepts the same columns, filter, parameters, and concurrency as + ``prewarm_data_async`` and uses the table handle's namespace and branch. + Requires LanceDB Enterprise with structured SQL previews, table Select, + and database/namespace Usage. Historical-version and Embedded handles + are unsupported. Returns the source version, readable plan, and conservative pruning summary. Unknown metrics remain None; selected ranges are not exact matching rows. @@ -2060,7 +2066,7 @@ class Table(ABC): Examples -------- >>> plan = table.explain_prewarm_data( # doctest: +SKIP - ... ["video"], filter="quality > 0.7") + ... ["video"], filter="quality > $minimum", parameters={"minimum": 0.7}) >>> print(plan.pruning.selected_fragments) # doctest: +SKIP """ raise NotImplementedError( @@ -2073,6 +2079,7 @@ class Table(ABC): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> Job[PrewarmDataResult]: """Submit a remote data-cache prewarm and return its durable job. @@ -2080,6 +2087,8 @@ class Table(ABC): The table handle supplies the branch and namespace. ``columns`` uses Lance field paths; an omitted/empty list warms all columns. ``filter`` is one SQL predicate for conservative metadata pruning, not a row scan. + ``parameters`` binds ``$1``/``$name`` values using a sequence, mapping, + or one-row Arrow batch/table. Values are sent separately from SQL. ``concurrency`` is a positive per-executor integer. Historical-version handles are unsupported; call ``checkout_latest()`` first. @@ -2097,7 +2106,8 @@ class Table(ABC): Examples -------- >>> job = table.prewarm_data_async( # doctest: +SKIP - ... ["video"], filter="quality > 0.7", concurrency=4) + ... ["video"], filter="quality > $min", parameters={"min": 0.7}, + ... concurrency=4) >>> job.wait() # doctest: +SKIP """ raise NotImplementedError( @@ -4977,6 +4987,7 @@ class LanceTable(Table): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> None: """ Prewarm data for the table. @@ -5000,6 +5011,9 @@ class LanceTable(Table): The columns to prewarm. If None, all columns are prewarmed. filter: str, optional A single SQL predicate for conservative metadata pruning. + parameters: sequence, mapping, or one-row Arrow batch/table, optional + Scalar values for ``$1``/``$name`` placeholders in ``filter``. + Values are sent separately from SQL; requires server support. concurrency: int, optional Positive per-executor warming concurrency; omitted uses the server default. @@ -5009,7 +5023,9 @@ class LanceTable(Table): ... ["payload"], filter="quality > 0.7", concurrency=4) """ return LOOP.run( - self._table.prewarm_data(columns, filter=filter, concurrency=concurrency) + self._table.prewarm_data( + columns, filter=filter, concurrency=concurrency, parameters=parameters + ) ) def explain_prewarm_data( @@ -5018,6 +5034,7 @@ class LanceTable(Table): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> PrewarmDataPlan: """Preview prewarm without submitting a warming job. @@ -5026,7 +5043,7 @@ class LanceTable(Table): """ return LOOP.run( self._table.explain_prewarm_data( - columns, filter=filter, concurrency=concurrency + columns, filter=filter, concurrency=concurrency, parameters=parameters ) ) @@ -5036,11 +5053,15 @@ class LanceTable(Table): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> Job[PrewarmDataResult]: return Job( LOOP.run( self._table.prewarm_data_async( - columns, filter=filter, concurrency=concurrency + columns, + filter=filter, + concurrency=concurrency, + parameters=parameters, ) ) ) @@ -7532,6 +7553,7 @@ class AsyncTable: *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> None: """ Prewarm data for the table. @@ -7555,6 +7577,9 @@ class AsyncTable: The columns to prewarm. If None, all columns are prewarmed. filter: str, optional A single SQL predicate for conservative metadata pruning. + parameters: sequence, mapping, or one-row Arrow batch/table, optional + Scalar values for ``$1``/``$name`` placeholders in ``filter``. + Values are sent separately from SQL; requires server support. concurrency: int, optional Positive per-executor warming concurrency; omitted uses the server default. @@ -7563,7 +7588,9 @@ class AsyncTable: >>> await table.prewarm_data( # doctest: +SKIP ... ["payload"], filter="quality > 0.7", concurrency=4) """ - await self.prewarm_data_async(columns, filter=filter, concurrency=concurrency) + await self.prewarm_data_async( + columns, filter=filter, concurrency=concurrency, parameters=parameters + ) async def explain_prewarm_data( self, @@ -7571,6 +7598,7 @@ class AsyncTable: *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> PrewarmDataPlan: """Preview prewarm without submitting a warming job. @@ -7579,7 +7607,10 @@ class AsyncTable: """ return PrewarmDataPlan.from_json( await self._inner.explain_prewarm_data( - columns, filter=filter, concurrency=concurrency + columns, + filter=filter, + concurrency=concurrency, + parameters=to_parameter_batch(parameters), ) ) @@ -7589,6 +7620,7 @@ class AsyncTable: *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> AsyncJob[PrewarmDataResult]: """Submit data prewarm and return a durable handle after acceptance. @@ -7604,7 +7636,10 @@ class AsyncTable: """ return _typed_job( await self._inner.prewarm_data_async( - columns, filter=filter, concurrency=concurrency + columns, + filter=filter, + concurrency=concurrency, + parameters=to_parameter_batch(parameters), ), PrewarmDataResult.from_json, ) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 381847954..bb649aaa2 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -8212,6 +8212,8 @@ async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mod {"concurrency": 2**32}, {"concurrency": True}, {"concurrency": 1.5}, + {"parameters": [1]}, + {"filter": "id > $1", "parameters": pa.table({"1": [1, 2]})}, ], ) @pytest.mark.parametrize( @@ -8236,6 +8238,88 @@ def test_remote_data_prewarm_validates_before_submission(options, method): assert not server.tickets +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "method", ["prewarm_data", "prewarm_data_async", "explain_prewarm_data"] +) +@pytest.mark.parametrize("named", [False, True]) +async def test_prewarm_bound_parameters_reach_flight(asynchronous, method, named): + flight = pytest.importorskip("pyarrow.flight") + attack = "training' OR TRUE; DROP TABLE items; --" + + class ParameterServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.calls = [] + + def do_exchange(self, context, descriptor, reader, writer): + self.calls.append((descriptor.command, reader.read_all())) + if method == "explain_prewarm_data": + result = pa.table( + { + "plan_type": ["logical_plan"], + "plan": [ + json.dumps( + { + "format_version": 1, + "table_version": 42, + "plan": "metadata preview", + "pruning": { + "mode": "zonemap_ranges", + "input_fragments": 3, + "selected_fragments": 1, + "pruned_fragments": 2, + "selected_row_ranges": 2, + }, + } + ) + ], + } + ) + else: + result = pa.table( + { + "job_id": ["bound-job"], + "table_version": pa.array([42], pa.uint64()), + } + ) + writer.begin(result.schema) + writer.write_table(result) + writer.close() + + server = ParameterServer() + with _mock_remote_sql_connection(server, _create_table_handler) as kwargs: + parameters = {"min": 8, "tag": attack} if named else [8, attack] + predicate = "id >= $min AND tag = $tag" if named else "id >= $1 AND tag = $2" + if asynchronous: + db = await lancedb.connect_async(**kwargs) + table = await db.create_table("test", [{"id": 1}]) + result = await getattr(table, method)( + ["payload"], filter=predicate, parameters=parameters + ) + else: + db = lancedb.connect(**kwargs) + table = db.create_table("test", [{"id": 1}]) + result = getattr(table, method)( + ["payload"], filter=predicate, parameters=parameters + ) + if method == "prewarm_data": + assert result is None + elif method == "explain_prewarm_data": + assert result.table_version == 42 + assert result.pruning.selected_fragments == 1 + else: + assert result.id == "bound-job" + ((command, received),) = server.calls + assert b"PREWARM" in command and predicate.encode() in command + if method == "explain_prewarm_data": + assert b"EXPLAIN (FORMAT JSON) PREWARM" in command + assert attack.encode() not in command + assert received.column(0).to_pylist() == [8] + assert received.column(1).to_pylist() == [attack] + + def test_remote_data_prewarm_malformed_receipt_is_not_retried(): flight = pytest.importorskip("pyarrow.flight") diff --git a/python/src/table.rs b/python/src/table.rs index a47d82d98..c24b10405 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1895,17 +1895,19 @@ impl Table { }) } - #[pyo3(signature = (columns=None, *, filter=None, concurrency=None))] + #[pyo3(signature = (columns=None, *, filter=None, concurrency=None, parameters=None))] pub fn prewarm_data_async<'py>( self_: PyRef<'py, Self>, columns: Option>, filter: Option, concurrency: Option<&Bound<'py, PyAny>>, + parameters: Option>, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); let mut options = lancedb::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()); options.filter = filter; + options.parameters = parameters.map(|parameters| parameters.0); options.concurrency = positive_u32_integer(concurrency, "concurrency")?; future_into_py(self_.py(), async move { let job = inner.prewarm_data_async(options).await.infer_error()?; @@ -1913,17 +1915,19 @@ impl Table { }) } - #[pyo3(signature = (columns=None, *, filter=None, concurrency=None))] + #[pyo3(signature = (columns=None, *, filter=None, concurrency=None, parameters=None))] pub fn explain_prewarm_data<'py>( self_: PyRef<'py, Self>, columns: Option>, filter: Option, concurrency: Option<&Bound<'py, PyAny>>, + parameters: Option>, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); let mut options = lancedb::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()); options.filter = filter; + options.parameters = parameters.map(|parameters| parameters.0); options.concurrency = positive_u32_integer(concurrency, "concurrency")?; future_into_py(self_.py(), async move { let plan = inner.explain_prewarm_data(options).await.infer_error()?; diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 29f70d164..bbefc3ca8 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -381,7 +381,10 @@ impl ExecuteQueryAsyncBuilder { /// /// Every placeholder needs a value and every parameter must be used by a /// placeholder. Parameters are supported in queries (`SELECT`, and - /// `EXPLAIN` of one), not in DDL or DML, nor in table-function arguments. + /// `EXPLAIN` of one) and, on compatible Enterprise servers, filter values in + /// `PREWARM` and `EXPLAIN PREWARM`. Prewarm bindings must be scalars. + /// Support for other statements depends on the server; table-function + /// arguments do not accept parameters. /// Do not follow a named placeholder directly with `$`: `$a$` starts a /// dollar-quoted string. /// diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 649edd133..54b7ea7b2 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4789,7 +4789,7 @@ impl BaseTable for RemoteTable { .execute_prewarm(crate::database::ExecuteQueryRequest { query: statement, default_namespace_path: self.namespace.clone(), - parameters: None, + parameters: options.parameters, }) .await .map_err(prewarm::map_error)?; @@ -4828,7 +4828,7 @@ impl BaseTable for RemoteTable { .execute_prewarm(crate::database::ExecuteQueryRequest { query: statement, default_namespace_path: self.namespace.clone(), - parameters: None, + parameters: options.parameters, }) .await .map_err(prewarm::map_explain_error)?; diff --git a/rust/lancedb/src/remote/table/prewarm.rs b/rust/lancedb/src/remote/table/prewarm.rs index d87465acf..4b6b2236f 100644 --- a/rust/lancedb/src/remote/table/prewarm.rs +++ b/rust/lancedb/src/remote/table/prewarm.rs @@ -20,6 +20,14 @@ pub(super) fn statement( if options.concurrency == Some(0) { return Err(invalid("prewarm concurrency must be greater than 0")); } + if let Some(parameters) = &options.parameters { + if options.filter.is_none() { + return Err(invalid("prewarm parameters require a filter")); + } + if parameters.num_rows() != 1 { + return Err(invalid("prewarm parameters must contain exactly one row")); + } + } if let Some(filter) = &options.filter { if filter.trim().is_empty() { return Err(invalid("prewarm filter must not be empty")); @@ -293,6 +301,31 @@ mod tests { assert!(plan(&[batch(&valid), batch(&valid)]).is_err()); } + #[test] + fn bound_values_are_never_rendered_into_sql() { + let value = "training' OR TRUE; DROP TABLE clips; --"; + let parameters = RecordBatch::try_from_iter(vec![( + "tag", + Arc::new(StringArray::from(vec![value])) as arrow_array::ArrayRef, + )]) + .unwrap(); + let options = PrewarmDataOptions::new() + .filter("tag = $tag") + .parameters(parameters); + let sql = statement("clips", Some("experiment"), &options).unwrap(); + assert!(sql.ends_with("WHERE tag = $tag")); + assert!(!sql.contains(value)); + assert!(!format!("{options:?}").contains(value)); + assert!( + statement( + "clips", + None, + &PrewarmDataOptions::new().parameters(options.parameters.unwrap()) + ) + .is_err() + ); + } + #[test] fn quotes_paths_branch_and_filter_without_changing_options() { let options = PrewarmDataOptions::new() diff --git a/rust/lancedb/src/table/prewarm.rs b/rust/lancedb/src/table/prewarm.rs index badb5a8ad..bc1128c54 100644 --- a/rust/lancedb/src/table/prewarm.rs +++ b/rust/lancedb/src/table/prewarm.rs @@ -3,22 +3,40 @@ //! Options, previews, and results for data-cache prewarm. -/// Data prewarm settings for [`super::Table::prewarm_data_async`]. +/// Data prewarm settings for [`super::Table::prewarm_data_async`] and +/// [`super::Table::explain_prewarm_data`]. /// /// The table handle supplies the database, namespace, and branch. Omitted /// columns warm all fields. The filter selects conservative metadata ranges; /// it does not execute a row-filter scan or change the source data. -#[derive(Debug, Clone, Default)] +#[derive(Clone, Default)] #[non_exhaustive] pub struct PrewarmDataOptions { /// Lance field paths, including nested paths such as `attrs.score`. pub columns: Vec, /// An optional SQL predicate for metadata pruning. pub filter: Option, + /// One row of typed filter values. Column i binds `$` and a + /// nonnumeric column name also binds `$name`. Requires server support. + pub parameters: Option, /// Positive per-executor warming concurrency. Omit for the server default. pub concurrency: Option, } +impl std::fmt::Debug for PrewarmDataOptions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PrewarmDataOptions") + .field("columns", &self.columns) + .field("filter", &self.filter) + .field("concurrency", &self.concurrency) + .field( + "parameter_count", + &self.parameters.as_ref().map(|batch| batch.num_columns()), + ) + .finish() + } +} + impl PrewarmDataOptions { /// Use server defaults and warm every column. pub fn new() -> Self { @@ -37,6 +55,25 @@ impl PrewarmDataOptions { self } + /// Bind scalar filter values without interpolating them into SQL text. + /// + /// ``` + /// # use lancedb::table::PrewarmDataOptions; + /// # use arrow_array::{ArrayRef, Int64Array, RecordBatch}; + /// # use std::sync::Arc; + /// let values = RecordBatch::try_from_iter(vec![( + /// "minimum", Arc::new(Int64Array::from(vec![100])) as ArrayRef, + /// )]).unwrap(); + /// let options = PrewarmDataOptions::new() + /// .columns(["payload"]) + /// .filter("id >= $minimum") + /// .parameters(values); + /// ``` + pub fn parameters(mut self, parameters: arrow_array::RecordBatch) -> Self { + self.parameters = Some(parameters); + self + } + /// Set positive per-executor warming concurrency. pub fn concurrency(mut self, concurrency: u32) -> Self { self.concurrency = Some(concurrency); From 72b46439bf0a4b8708a0e37af26a66cb909dfa37 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Wed, 18 Nov 2026 15:38:02 -0800 Subject: [PATCH 19/78] ci: publish and verify the CLI shell installer (#5090) #5082 added the CLI installer, but users still needed a repository checkout to run the script. This PR publishes it at `https://downloads.lancedb.com/cli/install.sh` whenever `scripts/install.sh` changes on `main`. The installer continues to fetch binaries and checksums from GitHub Releases. This was accomplished with the following changes: - Serialize publishes and check out current `main` so retrying an old run picks up the current script. - Use GitHub OIDC to upload the installer to S3, invalidate its CloudFront path, and compare the public download byte for byte with the checked-out script. - Allow a manual run on `main` for the first publish and retries. The first run requires the `CLI_INSTALLER_AWS_ROLE_ARN` and `CLI_INSTALLER_DISTRIBUTION_ID` repository variables. ### Testing The installer failure-case tests passed. With simulated AWS and HTTP responses, the publish step accepted matching bytes, rejected a stale download, and stopped before upload when the distribution ID was missing. --- .github/workflows/publish-cli-installer.yml | 48 +++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 .github/workflows/publish-cli-installer.yml diff --git a/.github/workflows/publish-cli-installer.yml b/.github/workflows/publish-cli-installer.yml new file mode 100644 index 000000000..6b73e2fc1 --- /dev/null +++ b/.github/workflows/publish-cli-installer.yml @@ -0,0 +1,48 @@ +name: Publish CLI installer + +on: + push: + branches: [main] + paths: + - scripts/install.sh + workflow_dispatch: + +permissions: + contents: read + id-token: write + +jobs: + publish: + if: github.repository == 'lancedb/lancedb' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + concurrency: + group: publish-cli-installer + cancel-in-progress: false + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # Queued jobs and retries publish the installer currently on main. + ref: refs/heads/main + persist-credentials: false + + - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 + with: + aws-region: us-west-2 + role-to-assume: ${{ vars.CLI_INSTALLER_AWS_ROLE_ARN }} + + - name: Publish and verify the installer + shell: bash + env: + DISTRIBUTION_ID: ${{ vars.CLI_INSTALLER_DISTRIBUTION_ID }} + run: | + : "${DISTRIBUTION_ID:?Set CLI_INSTALLER_DISTRIBUTION_ID before publishing}" + key=cli/install.sh + aws s3api put-object --bucket lancedb-downloads --key "$key" \ + --body scripts/install.sh --content-type 'text/plain; charset=utf-8' \ + --cache-control 'public, max-age=0, must-revalidate' > /dev/null + invalidation=$(aws cloudfront create-invalidation --distribution-id "$DISTRIBUTION_ID" \ + --paths "/$key" --query Invalidation.Id --output text) + aws cloudfront wait invalidation-completed --distribution-id "$DISTRIBUTION_ID" --id "$invalidation" + curl --fail --silent --show-error --retry 3 "https://downloads.lancedb.com/$key" \ + --output "$RUNNER_TEMP/published-installer.sh" + cmp scripts/install.sh "$RUNNER_TEMP/published-installer.sh" From 2dd1a6ad25ecf32a177bd02c1aa5971c73a420fc Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Wed, 18 Nov 2026 16:02:06 -0800 Subject: [PATCH 20/78] docs: add sidebar icons for Function failures and catalog pagination (#5092) ## Summary Add a warning triangle for Function Failures and a numbered list for Catalog listing pagination in the documentation sidebar. Each page gets one `icon` field in its metadata. ## Verification Assembled the documentation locally and confirmed both icon fields on the generated sidebar pages. --- docs/web/management/function-failures.mdx | 1 + docs/web/sql/pagination.mdx | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx index 131204382..226d8b573 100644 --- a/docs/web/management/function-failures.mdx +++ b/docs/web/management/function-failures.mdx @@ -2,6 +2,7 @@ title: "Handle Function failures" sidebarTitle: "Function Failures" description: "Keep usable outputs, inspect row errors, retry by stable identity and isolate inputs that need attention." +icon: triangle-exclamation tag: "Early access" availability: embedded: unavailable diff --git a/docs/web/sql/pagination.mdx b/docs/web/sql/pagination.mdx index d6649ebfe..d14a364fc 100644 --- a/docs/web/sql/pagination.mdx +++ b/docs/web/sql/pagination.mdx @@ -1,6 +1,7 @@ --- title: "Catalog listing pagination" description: "Use one continuation-token syntax for SQL catalog listings." +icon: list-ol --- Catalog `SHOW` statements share one pagination suffix: From 4b428101ddb19636421421e5e3106f5e808d6a5f Mon Sep 17 00:00:00 2001 From: Sarwar Bhuiyan Date: Wed, 18 Nov 2026 19:43:12 -0500 Subject: [PATCH 21/78] feat: expose the RTREE index in the Python and TypeScript SDKs (#4942) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of #4554. Supersedes #4555. This exposes Lance's R-tree index in the Python and TypeScript SDKs. Python gets a `lancedb.index.RTree` config with an optional `page_size`, accepted by `create_index(config=...)` on local, async and remote tables. TypeScript gets `Index.rtree({ pageSize })` and `RTreeOptions`. Both map to the Rust crate's existing `Index::RTree`, so remote tables send `index_type: "RTREE"`. The index accelerates `ST_Intersects`, `ST_Contains`, `ST_Within`, `ST_Touches`, `ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy` filters between a GeoArrow column and a constant geometry, in either argument order, including as a prefilter on vector search. The scalar index docs page gets an R-tree section. `geo` is now a default feature of the Python and Node packages. Without it, a local table can neither build the index nor evaluate `ST_*` filters, and because wheels and npm packages are prebuilt, an opt-in Cargo feature would not reach users. pylance already ships with `geo` on. It adds pure-Rust crates under licenses that `deny.toml` already allows. `Cargo.lock` doesn't change, and the third-party license notices are regenerated. The cost is size: the macOS arm64 release wheel grows from 69.4 MB to 71.7 MB (+2.4 MB, +3.4%). The tests pin the constant-first predicate bug that held up #4555, which lance-format/lance#10080 fixed, in queries, `delete()` and `update()`, with and without the index. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- RUST_THIRD_PARTY_LICENSES.html | 8133 ++++++++++++++++++++---- docs/src/js/classes/Index.md | 48 + docs/src/js/globals.md | 1 + docs/src/js/interfaces/RTreeOptions.md | 21 + docs/web-tests/py/test_indexing.py | 77 + docs/web/indexing/scalar-index.mdx | 142 +- docs/web/snippets/indexing.mdx | 10 + nodejs/Cargo.toml | 2 +- nodejs/RUST_THIRD_PARTY_LICENSES.html | 7683 ++++++++++++++++++---- nodejs/__test__/remote.test.ts | 81 + nodejs/__test__/table.test.ts | 98 + nodejs/lancedb/index.ts | 1 + nodejs/lancedb/indices.ts | 59 + nodejs/src/index.rs | 15 +- python/Cargo.toml | 2 +- python/RUST_THIRD_PARTY_LICENSES.html | 7610 +++++++++++++++++++--- python/python/lancedb/_lancedb.pyi | 3 + python/python/lancedb/index.py | 40 + python/python/lancedb/query.py | 8 +- python/python/lancedb/remote/table.py | 2 +- python/python/lancedb/table.py | 14 +- python/python/lancedb/types.py | 1 + python/python/tests/test_index.py | 386 ++ python/python/tests/test_remote_db.py | 49 + python/src/index.rs | 19 +- 25 files changed, 21398 insertions(+), 3107 deletions(-) create mode 100644 docs/src/js/interfaces/RTreeOptions.md diff --git a/RUST_THIRD_PARTY_LICENSES.html b/RUST_THIRD_PARTY_LICENSES.html index 2016fedcd..a1c82cfcb 100644 --- a/RUST_THIRD_PARTY_LICENSES.html +++ b/RUST_THIRD_PARTY_LICENSES.html @@ -44,19 +44,19 @@

Overview of licenses:

All license text:

@@ -65,230 +65,20 @@

BSD Zero Clause License

Used by:

-
Copyright (C) 2020 by museun <museun@outlook.com>
+                
Copyright (C) Jonas Schievink <jonasschievink@gmail.com>
 
-Permission to use, copy, modify, and/or distribute this software for any purpose
-with or without fee is hereby granted.
+Permission to use, copy, modify, and/or distribute this software for
+any purpose with or without fee is hereby granted.
 
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
-
- -
  • -

    Apache License 2.0

    -

    Used by:

    - -
    -                                 Apache License
    -                           Version 2.0, January 2004
    -                        http://www.apache.org/licenses/
    -
    -   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    -
    -   1. Definitions.
    -
    -      "License" shall mean the terms and conditions for use, reproduction,
    -      and distribution as defined by Sections 1 through 9 of this document.
    -
    -      "Licensor" shall mean the copyright owner or entity authorized by
    -      the copyright owner that is granting the License.
    -
    -      "Legal Entity" shall mean the union of the acting entity and all
    -      other entities that control, are controlled by, or are under common
    -      control with that entity. For the purposes of this definition,
    -      "control" means (i) the power, direct or indirect, to cause the
    -      direction or management of such entity, whether by contract or
    -      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    -      outstanding shares, or (iii) beneficial ownership of such entity.
    -
    -      "You" (or "Your") shall mean an individual or Legal Entity
    -      exercising permissions granted by this License.
    -
    -      "Source" form shall mean the preferred form for making modifications,
    -      including but not limited to software source code, documentation
    -      source, and configuration files.
    -
    -      "Object" form shall mean any form resulting from mechanical
    -      transformation or translation of a Source form, including but
    -      not limited to compiled object code, generated documentation,
    -      and conversions to other media types.
    -
    -      "Work" shall mean the work of authorship, whether in Source or
    -      Object form, made available under the License, as indicated by a
    -      copyright notice that is included in or attached to the work
    -      (an example is provided in the Appendix below).
    -
    -      "Derivative Works" shall mean any work, whether in Source or Object
    -      form, that is based on (or derived from) the Work and for which the
    -      editorial revisions, annotations, elaborations, or other modifications
    -      represent, as a whole, an original work of authorship. For the purposes
    -      of this License, Derivative Works shall not include works that remain
    -      separable from, or merely link (or bind by name) to the interfaces of,
    -      the Work and Derivative Works thereof.
    -
    -      "Contribution" shall mean any work of authorship, including
    -      the original version of the Work and any modifications or additions
    -      to that Work or Derivative Works thereof, that is intentionally
    -      submitted to Licensor for inclusion in the Work by the copyright owner
    -      or by an individual or Legal Entity authorized to submit on behalf of
    -      the copyright owner. For the purposes of this definition, "submitted"
    -      means any form of electronic, verbal, or written communication sent
    -      to the Licensor or its representatives, including but not limited to
    -      communication on electronic mailing lists, source code control systems,
    -      and issue tracking systems that are managed by, or on behalf of, the
    -      Licensor for the purpose of discussing and improving the Work, but
    -      excluding communication that is conspicuously marked or otherwise
    -      designated in writing by the copyright owner as "Not a Contribution."
    -
    -      "Contributor" shall mean Licensor and any individual or Legal Entity
    -      on behalf of whom a Contribution has been received by Licensor and
    -      subsequently incorporated within the Work.
    -
    -   2. Grant of Copyright License. Subject to the terms and conditions of
    -      this License, each Contributor hereby grants to You a perpetual,
    -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    -      copyright license to reproduce, prepare Derivative Works of,
    -      publicly display, publicly perform, sublicense, and distribute the
    -      Work and such Derivative Works in Source or Object form.
    -
    -   3. Grant of Patent License. Subject to the terms and conditions of
    -      this License, each Contributor hereby grants to You a perpetual,
    -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    -      (except as stated in this section) patent license to make, have made,
    -      use, offer to sell, sell, import, and otherwise transfer the Work,
    -      where such license applies only to those patent claims licensable
    -      by such Contributor that are necessarily infringed by their
    -      Contribution(s) alone or by combination of their Contribution(s)
    -      with the Work to which such Contribution(s) was submitted. If You
    -      institute patent litigation against any entity (including a
    -      cross-claim or counterclaim in a lawsuit) alleging that the Work
    -      or a Contribution incorporated within the Work constitutes direct
    -      or contributory patent infringement, then any patent licenses
    -      granted to You under this License for that Work shall terminate
    -      as of the date such litigation is filed.
    -
    -   4. Redistribution. You may reproduce and distribute copies of the
    -      Work or Derivative Works thereof in any medium, with or without
    -      modifications, and in Source or Object form, provided that You
    -      meet the following conditions:
    -
    -      (a) You must give any other recipients of the Work or
    -          Derivative Works a copy of this License; and
    -
    -      (b) You must cause any modified files to carry prominent notices
    -          stating that You changed the files; and
    -
    -      (c) You must retain, in the Source form of any Derivative Works
    -          that You distribute, all copyright, patent, trademark, and
    -          attribution notices from the Source form of the Work,
    -          excluding those notices that do not pertain to any part of
    -          the Derivative Works; and
    -
    -      (d) If the Work includes a "NOTICE" text file as part of its
    -          distribution, then any Derivative Works that You distribute must
    -          include a readable copy of the attribution notices contained
    -          within such NOTICE file, excluding those notices that do not
    -          pertain to any part of the Derivative Works, in at least one
    -          of the following places: within a NOTICE text file distributed
    -          as part of the Derivative Works; within the Source form or
    -          documentation, if provided along with the Derivative Works; or,
    -          within a display generated by the Derivative Works, if and
    -          wherever such third-party notices normally appear. The contents
    -          of the NOTICE file are for informational purposes only and
    -          do not modify the License. You may add Your own attribution
    -          notices within Derivative Works that You distribute, alongside
    -          or as an addendum to the NOTICE text from the Work, provided
    -          that such additional attribution notices cannot be construed
    -          as modifying the License.
    -
    -      You may add Your own copyright statement to Your modifications and
    -      may provide additional or different license terms and conditions
    -      for use, reproduction, or distribution of Your modifications, or
    -      for any such Derivative Works as a whole, provided Your use,
    -      reproduction, and distribution of the Work otherwise complies with
    -      the conditions stated in this License.
    -
    -   5. Submission of Contributions. Unless You explicitly state otherwise,
    -      any Contribution intentionally submitted for inclusion in the Work
    -      by You to the Licensor shall be under the terms and conditions of
    -      this License, without any additional terms or conditions.
    -      Notwithstanding the above, nothing herein shall supersede or modify
    -      the terms of any separate license agreement you may have executed
    -      with Licensor regarding such Contributions.
    -
    -   6. Trademarks. This License does not grant permission to use the trade
    -      names, trademarks, service marks, or product names of the Licensor,
    -      except as required for reasonable and customary use in describing the
    -      origin of the Work and reproducing the content of the NOTICE file.
    -
    -   7. Disclaimer of Warranty. Unless required by applicable law or
    -      agreed to in writing, Licensor provides the Work (and each
    -      Contributor provides its Contributions) on an "AS IS" BASIS,
    -      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    -      implied, including, without limitation, any warranties or conditions
    -      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    -      PARTICULAR PURPOSE. You are solely responsible for determining the
    -      appropriateness of using or redistributing the Work and assume any
    -      risks associated with Your exercise of permissions under this License.
    -
    -   8. Limitation of Liability. In no event and under no legal theory,
    -      whether in tort (including negligence), contract, or otherwise,
    -      unless required by applicable law (such as deliberate and grossly
    -      negligent acts) or agreed to in writing, shall any Contributor be
    -      liable to You for damages, including any direct, indirect, special,
    -      incidental, or consequential damages of any character arising as a
    -      result of this License or out of the use or inability to use the
    -      Work (including but not limited to damages for loss of goodwill,
    -      work stoppage, computer failure or malfunction, or any and all
    -      other commercial damages or losses), even if such Contributor
    -      has been advised of the possibility of such damages.
    -
    -   9. Accepting Warranty or Additional Liability. While redistributing
    -      the Work or Derivative Works thereof, You may choose to offer,
    -      and charge a fee for, acceptance of support, warranty, indemnity,
    -      or other liability obligations and/or rights consistent with this
    -      License. However, in accepting such obligations, You may act only
    -      on Your own behalf and on Your sole responsibility, not on behalf
    -      of any other Contributor, and only if You agree to indemnify,
    -      defend, and hold each Contributor harmless for any liability
    -      incurred by, or claims asserted against, such Contributor by reason
    -      of your accepting any such warranty or additional liability.
    -
    -   END OF TERMS AND CONDITIONS
    -
    -   APPENDIX: How to apply the Apache License to your work.
    -
    -      To apply the Apache License to your work, attach the following
    -      boilerplate notice, with the fields enclosed by brackets "[]"
    -      replaced with your own identifying information. (Don't include
    -      the brackets!)  The text should be enclosed in the appropriate
    -      comment syntax for the file format. We also recommend that a
    -      file or class name and description of purpose be included on the
    -      same "printed page" as the copyright notice for easier
    -      identification within third-party archives.
    -
    -   Copyright 2023 Jacob Pratt
    -
    -   Licensed under the Apache License, Version 2.0 (the "License");
    -   you may not use this file except in compliance with the License.
    -   You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
    +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
    +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     
  • @@ -505,7 +295,7 @@ THIS SOFTWARE.

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -715,7 +505,8 @@ THIS SOFTWARE.
                     

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -924,24 +715,19 @@ THIS SOFTWARE.
                     

    Apache License 2.0

    Used by:

    @@ -1152,7 +938,8 @@ THIS SOFTWARE.
                     

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -1364,7 +1151,15 @@ THIS SOFTWARE.
                     

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -1592,34 +1387,316 @@ Software.
                     

    Apache License 2.0

    Used by:

    +
    +                                 Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright [yyyy] [name of copyright owner]
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
    +Licenses for support code
    +-------------------------
    +
    +Parts of the TLS test suite are under the Go license. This code is not included
    +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so
    +distributing code linked against BoringSSL does not trigger this license:
    +
    +Copyright (c) 2009 The Go Authors. All rights reserved.
    +
    +Redistribution and use in source and binary forms, with or without
    +modification, are permitted provided that the following conditions are
    +met:
    +
    +   * Redistributions of source code must retain the above copyright
    +notice, this list of conditions and the following disclaimer.
    +   * Redistributions in binary form must reproduce the above
    +copyright notice, this list of conditions and the following disclaimer
    +in the documentation and/or other materials provided with the
    +distribution.
    +   * Neither the name of Google Inc. nor the names of its
    +contributors may be used to endorse or promote products derived from
    +this software without specific prior written permission.
    +
    +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    +
    +
    +BoringSSL uses the Chromium test infrastructure to run a continuous build,
    +trybots etc. The scripts which manage this, and the script for generating build
    +metadata, are under the Chromium license. Distributing code linked against
    +BoringSSL does not trigger this license.
    +
    +Copyright 2015 The Chromium Authors. All rights reserved.
    +
    +Redistribution and use in source and binary forms, with or without
    +modification, are permitted provided that the following conditions are
    +met:
    +
    +   * Redistributions of source code must retain the above copyright
    +notice, this list of conditions and the following disclaimer.
    +   * Redistributions in binary form must reproduce the above
    +copyright notice, this list of conditions and the following disclaimer
    +in the documentation and/or other materials provided with the
    +distribution.
    +   * Neither the name of Google Inc. nor the names of its
    +contributors may be used to endorse or promote products derived from
    +this software without specific prior written permission.
    +
    +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                      Apache License
    @@ -1833,6 +1910,238 @@ This project includes code from Apache Aurora.
     Copyright: 2016 The Apache Software Foundation.
     Home page: https://aurora.apache.org/
     License: http://www.apache.org/licenses/LICENSE-2.0
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
    +                                 Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright [yyyy] [name of copyright owner]
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +--------------------------------------------------------------------------------
    +
    +arrow-array/src/delta.rs: MIT
    +
    +This file is derived from the chronoutil crate. The full MIT license
    +text is in arrow-array/LICENSE-MIT.
     
  • @@ -1840,9 +2149,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0

    Used by:

                                      Apache License
    @@ -2052,7 +2359,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -2252,7 +2559,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Used by:

                                      Apache License
    @@ -2462,41 +2768,39 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -2705,7 +3009,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -2914,7 +3218,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -3104,7 +3409,425 @@ License: http://www.apache.org/licenses/LICENSE-2.0
           same "printed page" as the copyright notice for easier
           identification within third-party archives.
     
    -   Copyright 2020 - 2025 Tatsuya Kawano
    +   Copyright 2019 TiKV Project Authors.
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright 2020 - 2026 Tatsuya Kawano
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright 2020 Sébastien Crozet
     
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
    @@ -3124,7 +3847,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -3332,8 +4054,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -3752,7 +4474,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -3961,9 +4683,21 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -4172,7 +4906,456 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

    +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright [yyyy] [name of copyright owner]
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
    +------------------------------------------------------------------------------------
    +This product bundles third-party components under other open source licenses.
    +This section summarizes those components and their licenses. See the referenced
    +license files for text of these licenses.
    +
    +
    +Creative Commons Zero v1.0 Universal
    +------------------------------------
    +
    +bindings/dotnet/.gitignore
    +
    +The above file is derived from VisualStudio.gitignore in
    +https://github.com/github/gitignore. Its license text is in
    +bindings/dotnet/LICENSE-CC0-1.0.txt.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright [yyyy] [name of copyright owner]
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +   
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                     Apache License
                                Version 2.0, January 2004
    @@ -4381,6 +5564,219 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

    +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "{}"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright Individual contributors
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                     Apache License
    @@ -4590,22 +5986,38 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -4815,12 +6227,419 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

    +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   Copyright 2019 Yoshua Wuyts
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright 2020 Sébastien Crozet
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                    Apache License
                                Version 2.0, January 2004
    @@ -5030,7 +6849,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                   Apache License
                                Version 2.0, January 2004
    @@ -5448,15 +7267,15 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -5666,7 +7485,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -5874,7 +7693,8 @@ limitations under the License.

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -6083,8 +7903,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -6293,7 +8112,6 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
    @@ -6503,7 +8321,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -6693,7 +8511,7 @@ APPENDIX: How to apply the Apache License to your work.
        same "printed page" as the copyright notice for easier
        identification within third-party archives.
     
    -Copyright 2018 The pin-utils authors
    +Copyright 2018 Brian Myers
     
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
    @@ -6712,8 +8530,8 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -7120,6 +8938,215 @@ You may obtain a copy of the License at
     
        http://www.apache.org/licenses/LICENSE-2.0
     
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                  Apache License
    +                        Version 2.0, January 2004
    +                     http://www.apache.org/licenses/
    +
    +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +1. Definitions.
    +
    +   "License" shall mean the terms and conditions for use, reproduction,
    +   and distribution as defined by Sections 1 through 9 of this document.
    +
    +   "Licensor" shall mean the copyright owner or entity authorized by
    +   the copyright owner that is granting the License.
    +
    +   "Legal Entity" shall mean the union of the acting entity and all
    +   other entities that control, are controlled by, or are under common
    +   control with that entity. For the purposes of this definition,
    +   "control" means (i) the power, direct or indirect, to cause the
    +   direction or management of such entity, whether by contract or
    +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +   outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +   "You" (or "Your") shall mean an individual or Legal Entity
    +   exercising permissions granted by this License.
    +
    +   "Source" form shall mean the preferred form for making modifications,
    +   including but not limited to software source code, documentation
    +   source, and configuration files.
    +
    +   "Object" form shall mean any form resulting from mechanical
    +   transformation or translation of a Source form, including but
    +   not limited to compiled object code, generated documentation,
    +   and conversions to other media types.
    +
    +   "Work" shall mean the work of authorship, whether in Source or
    +   Object form, made available under the License, as indicated by a
    +   copyright notice that is included in or attached to the work
    +   (an example is provided in the Appendix below).
    +
    +   "Derivative Works" shall mean any work, whether in Source or Object
    +   form, that is based on (or derived from) the Work and for which the
    +   editorial revisions, annotations, elaborations, or other modifications
    +   represent, as a whole, an original work of authorship. For the purposes
    +   of this License, Derivative Works shall not include works that remain
    +   separable from, or merely link (or bind by name) to the interfaces of,
    +   the Work and Derivative Works thereof.
    +
    +   "Contribution" shall mean any work of authorship, including
    +   the original version of the Work and any modifications or additions
    +   to that Work or Derivative Works thereof, that is intentionally
    +   submitted to Licensor for inclusion in the Work by the copyright owner
    +   or by an individual or Legal Entity authorized to submit on behalf of
    +   the copyright owner. For the purposes of this definition, "submitted"
    +   means any form of electronic, verbal, or written communication sent
    +   to the Licensor or its representatives, including but not limited to
    +   communication on electronic mailing lists, source code control systems,
    +   and issue tracking systems that are managed by, or on behalf of, the
    +   Licensor for the purpose of discussing and improving the Work, but
    +   excluding communication that is conspicuously marked or otherwise
    +   designated in writing by the copyright owner as "Not a Contribution."
    +
    +   "Contributor" shall mean Licensor and any individual or Legal Entity
    +   on behalf of whom a Contribution has been received by Licensor and
    +   subsequently incorporated within the Work.
    +
    +2. Grant of Copyright License. Subject to the terms and conditions of
    +   this License, each Contributor hereby grants to You a perpetual,
    +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +   copyright license to reproduce, prepare Derivative Works of,
    +   publicly display, publicly perform, sublicense, and distribute the
    +   Work and such Derivative Works in Source or Object form.
    +
    +3. Grant of Patent License. Subject to the terms and conditions of
    +   this License, each Contributor hereby grants to You a perpetual,
    +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +   (except as stated in this section) patent license to make, have made,
    +   use, offer to sell, sell, import, and otherwise transfer the Work,
    +   where such license applies only to those patent claims licensable
    +   by such Contributor that are necessarily infringed by their
    +   Contribution(s) alone or by combination of their Contribution(s)
    +   with the Work to which such Contribution(s) was submitted. If You
    +   institute patent litigation against any entity (including a
    +   cross-claim or counterclaim in a lawsuit) alleging that the Work
    +   or a Contribution incorporated within the Work constitutes direct
    +   or contributory patent infringement, then any patent licenses
    +   granted to You under this License for that Work shall terminate
    +   as of the date such litigation is filed.
    +
    +4. Redistribution. You may reproduce and distribute copies of the
    +   Work or Derivative Works thereof in any medium, with or without
    +   modifications, and in Source or Object form, provided that You
    +   meet the following conditions:
    +
    +   (a) You must give any other recipients of the Work or
    +       Derivative Works a copy of this License; and
    +
    +   (b) You must cause any modified files to carry prominent notices
    +       stating that You changed the files; and
    +
    +   (c) You must retain, in the Source form of any Derivative Works
    +       that You distribute, all copyright, patent, trademark, and
    +       attribution notices from the Source form of the Work,
    +       excluding those notices that do not pertain to any part of
    +       the Derivative Works; and
    +
    +   (d) If the Work includes a "NOTICE" text file as part of its
    +       distribution, then any Derivative Works that You distribute must
    +       include a readable copy of the attribution notices contained
    +       within such NOTICE file, excluding those notices that do not
    +       pertain to any part of the Derivative Works, in at least one
    +       of the following places: within a NOTICE text file distributed
    +       as part of the Derivative Works; within the Source form or
    +       documentation, if provided along with the Derivative Works; or,
    +       within a display generated by the Derivative Works, if and
    +       wherever such third-party notices normally appear. The contents
    +       of the NOTICE file are for informational purposes only and
    +       do not modify the License. You may add Your own attribution
    +       notices within Derivative Works that You distribute, alongside
    +       or as an addendum to the NOTICE text from the Work, provided
    +       that such additional attribution notices cannot be construed
    +       as modifying the License.
    +
    +   You may add Your own copyright statement to Your modifications and
    +   may provide additional or different license terms and conditions
    +   for use, reproduction, or distribution of Your modifications, or
    +   for any such Derivative Works as a whole, provided Your use,
    +   reproduction, and distribution of the Work otherwise complies with
    +   the conditions stated in this License.
    +
    +5. Submission of Contributions. Unless You explicitly state otherwise,
    +   any Contribution intentionally submitted for inclusion in the Work
    +   by You to the Licensor shall be under the terms and conditions of
    +   this License, without any additional terms or conditions.
    +   Notwithstanding the above, nothing herein shall supersede or modify
    +   the terms of any separate license agreement you may have executed
    +   with Licensor regarding such Contributions.
    +
    +6. Trademarks. This License does not grant permission to use the trade
    +   names, trademarks, service marks, or product names of the Licensor,
    +   except as required for reasonable and customary use in describing the
    +   origin of the Work and reproducing the content of the NOTICE file.
    +
    +7. Disclaimer of Warranty. Unless required by applicable law or
    +   agreed to in writing, Licensor provides the Work (and each
    +   Contributor provides its Contributions) on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +   implied, including, without limitation, any warranties or conditions
    +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +   PARTICULAR PURPOSE. You are solely responsible for determining the
    +   appropriateness of using or redistributing the Work and assume any
    +   risks associated with Your exercise of permissions under this License.
    +
    +8. Limitation of Liability. In no event and under no legal theory,
    +   whether in tort (including negligence), contract, or otherwise,
    +   unless required by applicable law (such as deliberate and grossly
    +   negligent acts) or agreed to in writing, shall any Contributor be
    +   liable to You for damages, including any direct, indirect, special,
    +   incidental, or consequential damages of any character arising as a
    +   result of this License or out of the use or inability to use the
    +   Work (including but not limited to damages for loss of goodwill,
    +   work stoppage, computer failure or malfunction, or any and all
    +   other commercial damages or losses), even if such Contributor
    +   has been advised of the possibility of such damages.
    +
    +9. Accepting Warranty or Additional Liability. While redistributing
    +   the Work or Derivative Works thereof, You may choose to offer,
    +   and charge a fee for, acceptance of support, warranty, indemnity,
    +   or other liability obligations and/or rights consistent with this
    +   License. However, in accepting such obligations, You may act only
    +   on Your own behalf and on Your sole responsibility, not on behalf
    +   of any other Contributor, and only if You agree to indemnify,
    +   defend, and hold each Contributor harmless for any liability
    +   incurred by, or claims asserted against, such Contributor by reason
    +   of your accepting any such warranty or additional liability.
    +
    +END OF TERMS AND CONDITIONS
    +
    +APPENDIX: How to apply the Apache License to your work.
    +
    +   To apply the Apache License to your work, attach the following
    +   boilerplate notice, with the fields enclosed by brackets "[]"
    +   replaced with your own identifying information. (Don't include
    +   the brackets!)  The text should be enclosed in the appropriate
    +   comment syntax for the file format. We also recommend that a
    +   file or class name and description of purpose be included on the
    +   same "printed page" as the copyright notice for easier
    +   identification within third-party archives.
    +
    +Copyright 2019 quininer kel
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +	http://www.apache.org/licenses/LICENSE-2.0
    +
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    @@ -7132,7 +9159,9 @@ limitations under the License.
                     

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -7342,7 +9371,7 @@ limitations under the License.
                     

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -7760,7 +9789,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -7969,7 +9998,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -8180,7 +10209,216 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

    +
                                  Apache License
    +                        Version 2.0, January 2004
    +                     http://www.apache.org/licenses/
    +
    +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +1. Definitions.
    +
    +   "License" shall mean the terms and conditions for use, reproduction,
    +   and distribution as defined by Sections 1 through 9 of this document.
    +
    +   "Licensor" shall mean the copyright owner or entity authorized by
    +   the copyright owner that is granting the License.
    +
    +   "Legal Entity" shall mean the union of the acting entity and all
    +   other entities that control, are controlled by, or are under common
    +   control with that entity. For the purposes of this definition,
    +   "control" means (i) the power, direct or indirect, to cause the
    +   direction or management of such entity, whether by contract or
    +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +   outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +   "You" (or "Your") shall mean an individual or Legal Entity
    +   exercising permissions granted by this License.
    +
    +   "Source" form shall mean the preferred form for making modifications,
    +   including but not limited to software source code, documentation
    +   source, and configuration files.
    +
    +   "Object" form shall mean any form resulting from mechanical
    +   transformation or translation of a Source form, including but
    +   not limited to compiled object code, generated documentation,
    +   and conversions to other media types.
    +
    +   "Work" shall mean the work of authorship, whether in Source or
    +   Object form, made available under the License, as indicated by a
    +   copyright notice that is included in or attached to the work
    +   (an example is provided in the Appendix below).
    +
    +   "Derivative Works" shall mean any work, whether in Source or Object
    +   form, that is based on (or derived from) the Work and for which the
    +   editorial revisions, annotations, elaborations, or other modifications
    +   represent, as a whole, an original work of authorship. For the purposes
    +   of this License, Derivative Works shall not include works that remain
    +   separable from, or merely link (or bind by name) to the interfaces of,
    +   the Work and Derivative Works thereof.
    +
    +   "Contribution" shall mean any work of authorship, including
    +   the original version of the Work and any modifications or additions
    +   to that Work or Derivative Works thereof, that is intentionally
    +   submitted to Licensor for inclusion in the Work by the copyright owner
    +   or by an individual or Legal Entity authorized to submit on behalf of
    +   the copyright owner. For the purposes of this definition, "submitted"
    +   means any form of electronic, verbal, or written communication sent
    +   to the Licensor or its representatives, including but not limited to
    +   communication on electronic mailing lists, source code control systems,
    +   and issue tracking systems that are managed by, or on behalf of, the
    +   Licensor for the purpose of discussing and improving the Work, but
    +   excluding communication that is conspicuously marked or otherwise
    +   designated in writing by the copyright owner as "Not a Contribution."
    +
    +   "Contributor" shall mean Licensor and any individual or Legal Entity
    +   on behalf of whom a Contribution has been received by Licensor and
    +   subsequently incorporated within the Work.
    +
    +2. Grant of Copyright License. Subject to the terms and conditions of
    +   this License, each Contributor hereby grants to You a perpetual,
    +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +   copyright license to reproduce, prepare Derivative Works of,
    +   publicly display, publicly perform, sublicense, and distribute the
    +   Work and such Derivative Works in Source or Object form.
    +
    +3. Grant of Patent License. Subject to the terms and conditions of
    +   this License, each Contributor hereby grants to You a perpetual,
    +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +   (except as stated in this section) patent license to make, have made,
    +   use, offer to sell, sell, import, and otherwise transfer the Work,
    +   where such license applies only to those patent claims licensable
    +   by such Contributor that are necessarily infringed by their
    +   Contribution(s) alone or by combination of their Contribution(s)
    +   with the Work to which such Contribution(s) was submitted. If You
    +   institute patent litigation against any entity (including a
    +   cross-claim or counterclaim in a lawsuit) alleging that the Work
    +   or a Contribution incorporated within the Work constitutes direct
    +   or contributory patent infringement, then any patent licenses
    +   granted to You under this License for that Work shall terminate
    +   as of the date such litigation is filed.
    +
    +4. Redistribution. You may reproduce and distribute copies of the
    +   Work or Derivative Works thereof in any medium, with or without
    +   modifications, and in Source or Object form, provided that You
    +   meet the following conditions:
    +
    +   (a) You must give any other recipients of the Work or
    +       Derivative Works a copy of this License; and
    +
    +   (b) You must cause any modified files to carry prominent notices
    +       stating that You changed the files; and
    +
    +   (c) You must retain, in the Source form of any Derivative Works
    +       that You distribute, all copyright, patent, trademark, and
    +       attribution notices from the Source form of the Work,
    +       excluding those notices that do not pertain to any part of
    +       the Derivative Works; and
    +
    +   (d) If the Work includes a "NOTICE" text file as part of its
    +       distribution, then any Derivative Works that You distribute must
    +       include a readable copy of the attribution notices contained
    +       within such NOTICE file, excluding those notices that do not
    +       pertain to any part of the Derivative Works, in at least one
    +       of the following places: within a NOTICE text file distributed
    +       as part of the Derivative Works; within the Source form or
    +       documentation, if provided along with the Derivative Works; or,
    +       within a display generated by the Derivative Works, if and
    +       wherever such third-party notices normally appear. The contents
    +       of the NOTICE file are for informational purposes only and
    +       do not modify the License. You may add Your own attribution
    +       notices within Derivative Works that You distribute, alongside
    +       or as an addendum to the NOTICE text from the Work, provided
    +       that such additional attribution notices cannot be construed
    +       as modifying the License.
    +
    +   You may add Your own copyright statement to Your modifications and
    +   may provide additional or different license terms and conditions
    +   for use, reproduction, or distribution of Your modifications, or
    +   for any such Derivative Works as a whole, provided Your use,
    +   reproduction, and distribution of the Work otherwise complies with
    +   the conditions stated in this License.
    +
    +5. Submission of Contributions. Unless You explicitly state otherwise,
    +   any Contribution intentionally submitted for inclusion in the Work
    +   by You to the Licensor shall be under the terms and conditions of
    +   this License, without any additional terms or conditions.
    +   Notwithstanding the above, nothing herein shall supersede or modify
    +   the terms of any separate license agreement you may have executed
    +   with Licensor regarding such Contributions.
    +
    +6. Trademarks. This License does not grant permission to use the trade
    +   names, trademarks, service marks, or product names of the Licensor,
    +   except as required for reasonable and customary use in describing the
    +   origin of the Work and reproducing the content of the NOTICE file.
    +
    +7. Disclaimer of Warranty. Unless required by applicable law or
    +   agreed to in writing, Licensor provides the Work (and each
    +   Contributor provides its Contributions) on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +   implied, including, without limitation, any warranties or conditions
    +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +   PARTICULAR PURPOSE. You are solely responsible for determining the
    +   appropriateness of using or redistributing the Work and assume any
    +   risks associated with Your exercise of permissions under this License.
    +
    +8. Limitation of Liability. In no event and under no legal theory,
    +   whether in tort (including negligence), contract, or otherwise,
    +   unless required by applicable law (such as deliberate and grossly
    +   negligent acts) or agreed to in writing, shall any Contributor be
    +   liable to You for damages, including any direct, indirect, special,
    +   incidental, or consequential damages of any character arising as a
    +   result of this License or out of the use or inability to use the
    +   Work (including but not limited to damages for loss of goodwill,
    +   work stoppage, computer failure or malfunction, or any and all
    +   other commercial damages or losses), even if such Contributor
    +   has been advised of the possibility of such damages.
    +
    +9. Accepting Warranty or Additional Liability. While redistributing
    +   the Work or Derivative Works thereof, You may choose to offer,
    +   and charge a fee for, acceptance of support, warranty, indemnity,
    +   or other liability obligations and/or rights consistent with this
    +   License. However, in accepting such obligations, You may act only
    +   on Your own behalf and on Your sole responsibility, not on behalf
    +   of any other Contributor, and only if You agree to indemnify,
    +   defend, and hold each Contributor harmless for any liability
    +   incurred by, or claims asserted against, such Contributor by reason
    +   of your accepting any such warranty or additional liability.
    +
    +END OF TERMS AND CONDITIONS
    +
    +APPENDIX: How to apply the Apache License to your work.
    +
    +   To apply the Apache License to your work, attach the following
    +   boilerplate notice, with the fields enclosed by brackets "[]"
    +   replaced with your own identifying information. (Don't include
    +   the brackets!)  The text should be enclosed in the appropriate
    +   comment syntax for the file format. We also recommend that a
    +   file or class name and description of purpose be included on the
    +   same "printed page" as the copyright notice for easier
    +   identification within third-party archives.
    +
    +Copyright 2024 Liam Gray <gmail@liamg.me>
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +	http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                  Apache License
                             Version 2.0, January 2004
    @@ -8390,7 +10628,8 @@ limitations under the License.
                     

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -8598,156 +10837,175 @@ limitations under the License.

    Apache License 2.0

    Used by:

      +
    • addr2line 0.25.1
    • ahash 0.8.12
    • -
    • arc-swap 1.7.1
    • -
    • arrayvec 0.7.6
    • +
    • arc-swap 1.9.3
    • +
    • arrayvec 0.7.8
    • async-channel 2.5.0
    • -
    • async-compression 0.4.19
    • -
    • async-lock 3.4.1
    • +
    • async-compression 0.4.42
    • +
    • async-lock 3.4.2
    • atomic-waker 1.1.2
    • autocfg 1.5.0
    • -
    • base64 0.21.7
    • +
    • backtrace 0.3.76
    • base64 0.22.1
    • -
    • bitflags 2.9.4
    • -
    • bumpalo 3.19.0
    • +
    • base64 0.23.1
    • +
    • bitflags 1.3.2
    • +
    • bitflags 2.11.1
    • +
    • bstr 1.12.1
    • +
    • bumpalo 3.20.2
    • bytes-utils 0.1.4
    • -
    • cc 1.2.40
    • -
    • cexpr 0.6.0
    • -
    • cfg-if 1.0.3
    • -
    • cmake 0.1.54
    • +
    • cast 0.3.0
    • +
    • cc 1.2.62
    • +
    • cfg-if 0.1.10
    • +
    • cfg-if 1.0.4
    • +
    • cmake 0.1.58
    • +
    • compression-codecs 0.4.38
    • +
    • compression-core 0.4.32
    • concurrent-queue 2.5.0
    • const-random-macro 0.1.16
    • const-random 0.1.18
    • core-foundation-sys 0.8.7
    • core-foundation 0.10.1
    • core-foundation 0.9.4
    • +
    • cpp_demangle 0.4.5
    • +
    • criterion-plot 0.8.2
    • +
    • criterion 0.8.2
    • crossbeam-channel 0.5.15
    • crossbeam-deque 0.8.6
    • -
    • crossbeam-epoch 0.9.18
    • +
    • crossbeam-epoch 0.9.20
    • crossbeam-queue 0.3.12
    • +
    • crossbeam-skiplist 0.1.3
    • crossbeam-utils 0.8.21
    • +
    • debugid 0.8.0
    • displaydoc 0.2.5
    • either 1.15.0
    • +
    • encoding_rs_io 0.1.7
    • equivalent 1.0.2
    • errno 0.3.14
    • event-listener-strategy 0.5.4
    • -
    • event-listener 5.4.1
    • -
    • fastrand 2.3.0
    • -
    • find-msvc-tools 0.1.3
    • +
    • event-listener 5.4.2
    • +
    • fastrand 2.4.1
    • +
    • find-msvc-tools 0.1.9
    • +
    • findshlibs 0.10.2
    • fixedbitset 0.5.7
    • +
    • flate2 1.1.9
    • fnv 1.0.7
    • form_urlencoded 1.2.2
    • -
    • fs4 0.8.4
    • +
    • foyer-intrusive-collections 0.10.0-dev
    • +
    • fs4 0.13.1
    • futures-timer 3.0.3
    • -
    • geohash 0.13.1
    • +
    • geohash 0.13.2
    • +
    • gimli 0.32.3
    • glob 0.3.3
    • -
    • group 0.12.1
    • +
    • group 0.14.0
    • hash32 0.3.1
    • hashbrown 0.14.5
    • hashbrown 0.15.5
    • -
    • hashbrown 0.16.0
    • +
    • hashbrown 0.16.1
    • +
    • hashbrown 0.17.1
    • heapless 0.8.0
    • heck 0.5.0
    • hermit-abi 0.5.2
    • httparse 1.10.1
    • -
    • hyper-rustls 0.24.2
    • -
    • hyper-rustls 0.27.7
    • +
    • hyper-rustls 0.27.9
    • +
    • hyper-timeout 0.5.2
    • +
    • hyper-tls 0.6.0
    • idna 1.1.0
    • -
    • idna_adapter 1.2.1
    • -
    • indexmap 2.12.0
    • -
    • itertools 0.11.0
    • -
    • itertools 0.12.1
    • +
    • idna_adapter 1.2.2
    • +
    • indexmap 2.14.0
    • itertools 0.13.0
    • itertools 0.14.0
    • +
    • itertools 0.15.0
    • jobserver 0.1.34
    • -
    • js-sys 0.3.81
    • +
    • js-sys 0.3.107
    • lazy_static 1.5.0
    • -
    • lazycell 1.3.0
    • -
    • linux-raw-sys 0.11.0
    • +
    • linux-raw-sys 0.12.1
    • linux-raw-sys 0.4.15
    • lock_api 0.4.14
    • -
    • log 0.4.28
    • +
    • log 0.4.34
    • lzma-sys 0.1.20
    • matrixmultiply 0.3.10
    • mime 0.3.17
    • -
    • multimap 0.10.1
    • ndarray 0.16.1
    • -
    • num-bigint-dig 0.8.4
    • +
    • num-bigint-dig 0.8.6
    • num-bigint 0.4.6
    • +
    • num-bigint 0.5.1
    • num-complex 0.4.6
    • num-integer 0.1.46
    • num-iter 0.1.45
    • +
    • num-rational 0.4.2
    • num-traits 0.2.19
    • num_cpus 1.17.0
    • -
    • once_cell 1.21.3
    • -
    • openssl-probe 0.1.6
    • +
    • oauth2 5.0.0
    • +
    • object 0.37.3
    • +
    • once_cell 1.21.4
    • +
    • openssl-probe 0.2.1
    • parking 2.2.1
    • parking_lot 0.12.5
    • parking_lot_core 0.9.12
    • percent-encoding 2.3.2
    • petgraph 0.8.3
    • -
    • pkg-config 0.3.32
    • -
    • prost-build 0.14.3
    • -
    • prost-derive 0.14.3
    • +
    • pkg-config 0.3.33
    • +
    • prost-derive 0.14.4
    • prost-types 0.14.3
    • -
    • prost 0.14.3
    • +
    • prost 0.14.4
    • +
    • rand_xoshiro 0.6.0
    • rawpointer 0.2.1
    • rayon-core 1.13.0
    • -
    • rayon 1.11.0
    • -
    • regex-automata 0.4.13
    • -
    • regex-lite 0.1.7
    • -
    • regex-syntax 0.8.6
    • -
    • regex 1.12.2
    • +
    • rayon 1.12.0
    • +
    • regex-automata 0.4.16
    • +
    • regex-lite 0.1.9
    • +
    • regex-syntax 0.8.11
    • +
    • regex 1.13.1
    • ring 0.17.14
    • +
    • roaring 0.11.5
    • robust 1.2.0
    • -
    • rustc-hash 1.1.0
    • +
    • rustc-demangle 0.1.27
    • rustc_version 0.4.1
    • rustix 0.38.44
    • -
    • rustix 1.1.2
    • -
    • rustls-native-certs 0.6.3
    • -
    • rustls-native-certs 0.8.1
    • -
    • rustls-pemfile 1.0.4
    • -
    • rustls-pemfile 2.2.0
    • -
    • rustls 0.21.12
    • -
    • rustls 0.23.31
    • +
    • rustix 1.1.4
    • +
    • rustls-native-certs 0.8.3
    • +
    • rustls 0.23.46
    • scoped-tls 1.0.1
    • scopeguard 1.2.0
    • -
    • sct 0.7.1
    • -
    • security-framework-sys 2.15.0
    • -
    • security-framework 2.11.1
    • -
    • security-framework 3.5.1
    • -
    • serde_with 3.15.0
    • -
    • serde_with_macros 3.15.0
    • -
    • shellexpand 3.1.1
    • -
    • signal-hook-registry 1.4.6
    • -
    • smallvec 1.15.1
    • -
    • socket2 0.5.10
    • -
    • socket2 0.6.0
    • -
    • sqlparser 0.59.0
    • -
    • sqlparser_derive 0.3.0
    • -
    • stable_deref_trait 1.2.0
    • -
    • syn 1.0.109
    • +
    • security-framework-sys 2.17.0
    • +
    • security-framework 3.7.0
    • +
    • serde_with 3.24.0
    • +
    • serde_with_macros 3.24.0
    • +
    • shellexpand 3.1.2
    • +
    • signal-hook-registry 1.4.8
    • +
    • simd_cesu8 1.1.1
    • +
    • smallvec 1.16.5
    • +
    • socket2 0.6.3
    • +
    • sqlparser 0.62.0
    • +
    • sqlparser_derive 0.5.0
    • +
    • stable_deref_trait 1.2.1
    • +
    • str_stack 0.1.1
    • +
    • symlink 0.1.0
    • system-configuration-sys 0.6.0
    • -
    • system-configuration 0.6.1
    • -
    • tempfile 3.23.0
    • +
    • system-configuration 0.7.0
    • +
    • tempfile 3.27.0
    • thread-tree 0.3.3
    • -
    • thread_local 1.1.9
    • -
    • unicase 2.8.1
    • -
    • unicode-segmentation 1.12.0
    • -
    • unicode-width 0.2.2
    • -
    • url 2.5.7
    • -
    • uuid 1.18.1
    • +
    • thread_local 1.1.10
    • +
    • tinytemplate 1.2.1
    • +
    • unicase 2.9.0
    • +
    • unicode-normalization 0.1.25
    • +
    • unicode-segmentation 1.13.2
    • +
    • unicode-width 0.1.14
    • +
    • unicode-width 0.2.3
    • +
    • url 2.5.8
    • +
    • uuid 1.29.0
    • version_check 0.9.5
    • wasi 0.11.1+wasi-snapshot-preview1
    • wasi 0.14.7+wasi-0.2.4
    • -
    • wasm-bindgen-backend 0.2.104
    • -
    • wasm-bindgen-futures 0.4.54
    • -
    • wasm-bindgen-macro-support 0.2.104
    • -
    • wasm-bindgen-macro 0.2.104
    • -
    • wasm-bindgen-shared 0.2.104
    • -
    • wasm-bindgen 0.2.104
    • -
    • web-sys 0.3.81
    • -
    • wit-bindgen 0.46.0
    • +
    • wasip2 1.0.3+wasi-0.2.9
    • +
    • wasm-bindgen-futures 0.4.80
    • +
    • wasm-bindgen-macro-support 0.2.130
    • +
    • wasm-bindgen-macro 0.2.130
    • +
    • wasm-bindgen-shared 0.2.130
    • +
    • wasm-bindgen 0.2.130
    • +
    • web-sys 0.3.107
    • +
    • wit-bindgen 0.57.1
    • wkb 0.9.2
    • wkt 0.14.0
    • xmlparser 0.13.6
    • @@ -8959,7 +11217,7 @@ limitations under the License.

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -9169,14 +11427,14 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -9386,41 +11644,56 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -9629,10 +11902,209 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +Copyright (c) 2015-2022 Amod Malviya
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      + +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                    Apache License
                               Version 2.0, January 2004
      @@ -9827,11 +12299,13 @@ APPENDIX: How to apply the Apache License to your work.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -10040,8 +12514,8 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -10250,7 +12724,427 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright [yyyy] [name of copyright owner]
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright [yyyy] [name of copyright owner]
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
         Copyright (c) 2017-present PyO3 Project and Contributors.  https://github.com/PyO3
       
      @@ -10447,7 +13341,9 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      Apache License
                                  Version 2.0, January 2004
      @@ -10656,7 +13552,9 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      Apache License
       Version 2.0, January 2004
      @@ -10935,137 +13833,190 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      Apache License
       Version 2.0, January 2004
      @@ -11382,10 +14333,10 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      Rust-chrono is dual-licensed under The MIT License [1] and
      -Apache 2.0 License [2]. Copyright (c) 2014--2025, Kang Seonghoon and
      +Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and
       contributors.
       
       Nota Bene: This is same as the Rust Project's own license.
      @@ -11624,6 +14575,40 @@ See the License for the specific language governing permissions and
       limitations under the License.
       ~~~~
       
      +
      +
    • +
    • +

      BSD 2-Clause "Simplified" License

      +

      Used by:

      + +
      Copyright (c) 2013-2014, Naoki Yoshinaga, Paul Meng
      +All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are
      +met:
      +
      +1. Redistributions of source code must retain the above copyright
      +   notice, this list of conditions and the following disclaimer.
      +
      +2. Redistributions in binary form must reproduce the above copyright
      +   notice, this list of conditions and the following disclaimer in the
      +   documentation and/or other materials provided with the
      +   distribution.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
      +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
      +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
      +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
      +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
      +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
       
    • @@ -11658,6 +14643,99 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
    • + +
    • +

      BSD 2-Clause "Simplified" License

      +

      Used by:

      + +
      Copyright (c) 2017-2020
      +All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are met:
      +
      +1. Redistributions of source code must retain the above copyright notice, this
      +   list of conditions and the following disclaimer.
      +2. Redistributions in binary form must reproduce the above copyright notice,
      +   this list of conditions and the following disclaimer in the documentation
      +   and/or other materials provided with the distribution.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
      +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
      +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
      +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      BSD 3-Clause "New" or "Revised" License

      +

      Used by:

      + +
      // Copyright © WHATWG (Apple, Google, Mozilla, Microsoft).
      +//
      +// Redistribution and use in source and binary forms, with or without
      +// modification, are permitted provided that the following conditions are met:
      +//
      +// 1. Redistributions of source code must retain the above copyright notice, this
      +//    list of conditions and the following disclaimer.
      +//
      +// 2. Redistributions in binary form must reproduce the above copyright notice,
      +//    this list of conditions and the following disclaimer in the documentation
      +//    and/or other materials provided with the distribution.
      +//
      +// 3. Neither the name of the copyright holder nor the names of its
      +//    contributors may be used to endorse or promote products derived from
      +//    this software without specific prior written permission.
      +//
      +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
      +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
      +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
      +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
      +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
      +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
      +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +/// The PUA code points special-cased in the GB18030 encoder.
      +pub(crate) static GB18030_2022_OVERRIDE_PUA: [u16; 18] = [
      +    0xE78D, 0xE78E, 0xE78F, 0xE790, 0xE791, 0xE792, 0xE793, 0xE794, 0xE795, 0xE796, 0xE81E, 0xE826,
      +    0xE82B, 0xE82C, 0xE832, 0xE843, 0xE854, 0xE864,
      +];
      +
      +/// The bytes corresponding to the PUA code points special-cased in the GB18030 encoder.
      +pub(crate) static GB18030_2022_OVERRIDE_BYTES: [[u8; 2]; 18] = [
      +    [0xA6, 0xD9],
      +    [0xA6, 0xDA],
      +    [0xA6, 0xDB],
      +    [0xA6, 0xDC],
      +    [0xA6, 0xDD],
      +    [0xA6, 0xDE],
      +    [0xA6, 0xDF],
      +    [0xA6, 0xEC],
      +    [0xA6, 0xED],
      +    [0xA6, 0xF3],
      +    [0xFE, 0x59],
      +    [0xFE, 0x61],
      +    [0xFE, 0x66],
      +    [0xFE, 0x67],
      +    [0xFE, 0x6D],
      +    [0xFE, 0x7E],
      +    [0xFE, 0x90],
      +    [0xFE, 0xA0],
      +];
       
    • @@ -11665,6 +14743,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

      Used by:

      BSD 3-Clause License
       
      @@ -11701,26 +14780,27 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                       

      BSD 3-Clause "New" or "Revised" License

      Used by:

      BSD 3-Clause License
       
      -Copyright (c) 2013, Jyun-Yan You
      -All rights reserved.
      +Copyright (c) 2026, Alexandre Bury
       
       Redistribution and use in source and binary forms, with or without
       modification, are permitted provided that the following conditions are met:
       
      -* Redistributions of source code must retain the above copyright notice, this
      -  list of conditions and the following disclaimer.
      +1. Redistributions of source code must retain the above copyright notice, this
      +   list of conditions and the following disclaimer.
       
      -* Redistributions in binary form must reproduce the above copyright notice,
      -  this list of conditions and the following disclaimer in the documentation
      -  and/or other materials provided with the distribution.
      +2. Redistributions in binary form must reproduce the above copyright notice,
      +   this list of conditions and the following disclaimer in the documentation
      +   and/or other materials provided with the distribution.
       
      -* Neither the name of the copyright holder nor the names of its
      -  contributors may be used to endorse or promote products derived from
      -  this software without specific prior written permission.
      +3. Neither the name of the copyright holder nor the names of its
      +   contributors may be used to endorse or promote products derived from
      +   this software without specific prior written permission.
       
       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
       AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      @@ -11738,10 +14818,50 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                       

      BSD 3-Clause "New" or "Revised" License

      Used by:

      +
      BSD License
      +
      +For Zstandard software
      +
      +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without modification,
      +are permitted provided that the following conditions are met:
      +
      + * Redistributions of source code must retain the above copyright notice, this
      +   list of conditions and the following disclaimer.
      +
      + * Redistributions in binary form must reproduce the above copyright notice,
      +   this list of conditions and the following disclaimer in the documentation
      +   and/or other materials provided with the distribution.
      +
      + * Neither the name Facebook, nor Meta, nor the names of its contributors may
      +   be used to endorse or promote products derived from this software without
      +   specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
      +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
      +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
      +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      BSD 3-Clause "New" or "Revised" License

      +

      Used by:

      +
      Copyright (c) 2001, Dr Martin Porter
       Copyright (c) 2004,2005, Richard Boulton
      +Copyright (c) 2013, Yoshiki Shibukawa
      +Copyright (c) 2006-2025, Olly Betts
       All rights reserved.
       
       Redistribution and use in source and binary forms, with or without
      @@ -11766,16 +14886,16 @@ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
       LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
       ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
       (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
    • BSD 3-Clause "New" or "Revised" License

      Used by:

      Copyright (c) 2016 Dropbox, Inc.
       All rights reserved.
      @@ -11832,8 +14952,53 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                       

      BSD 3-Clause "New" or "Revised" License

      Used by:

      +
      Copyright (c) 2026, frostem contributors
      +Copyright (c) 2001, Dr Martin Porter
      +Copyright (c) 2004,2005, Richard Boulton
      +Copyright (c) 2013, Yoshiki Shibukawa
      +Copyright (c) 2006-2025, Olly Betts
      +All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions
      +are met:
      +
      +  1. Redistributions of source code must retain the above copyright notice,
      +     this list of conditions and the following disclaimer.
      +  2. Redistributions in binary form must reproduce the above copyright notice,
      +     this list of conditions and the following disclaimer in the documentation
      +     and/or other materials provided with the distribution.
      +  3. Neither the name of the Snowball project nor the names of its contributors
      +     may be used to endorse or promote products derived from this software
      +     without specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
      +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
      +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
      +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      BSD 3-Clause "New" or "Revised" License

      +

      Used by:

      +
      Copyright (c) <year> <owner>. 
       
      @@ -11880,13 +15045,54 @@ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
       CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
       OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
       OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      BSD 3-Clause "New" or "Revised" License

      +

      Used by:

      + +
      The auto-generated bindings are under the 3-clause BSD license:
      +
      +BSD License
      +
      +For Zstandard software
      +
      +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without modification,
      +are permitted provided that the following conditions are met:
      +
      + * Redistributions of source code must retain the above copyright notice, this
      +   list of conditions and the following disclaimer.
      +
      + * Redistributions in binary form must reproduce the above copyright notice,
      +   this list of conditions and the following disclaimer in the documentation
      +   and/or other materials provided with the distribution.
      +
      + * Neither the name Facebook, nor Meta, nor the names of its contributors may
      +   be used to endorse or promote products derived from this software without
      +   specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
      +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
      +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
      +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
       
    • Boost Software License 1.0

      Used by:

      Boost Software License - Version 1.0 - August 17th, 2003
       
      @@ -11911,6 +15117,21 @@ SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
       FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
       ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
       DEALINGS IN THE SOFTWARE.
      +
      +
    • +
    • +

      Boost Software License 1.0

      +

      Used by:

      + +
      Boost Software License - Version 1.0 - August 17th, 2003
      +
      +Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following:
      +
      +The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
       
    • @@ -12040,13 +15261,405 @@ express Statement of Purpose. d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. +
    • + +
    • +

      Common Development and Distribution License 1.0

      +

      Used by:

      + +
      Unless otherwise noted, all files in this distribution are released
      +under the Common Development and Distribution License (CDDL).
      +Exceptions are noted within the associated source files.
      +
      +--------------------------------------------------------------------
      +
      +
      +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE Version 1.0
      +
      +1. Definitions.
      +
      +    1.1. "Contributor" means each individual or entity that creates
      +         or contributes to the creation of Modifications.
      +
      +    1.2. "Contributor Version" means the combination of the Original
      +         Software, prior Modifications used by a Contributor (if any),
      +         and the Modifications made by that particular Contributor.
      +
      +    1.3. "Covered Software" means (a) the Original Software, or (b)
      +         Modifications, or (c) the combination of files containing
      +         Original Software with files containing Modifications, in
      +         each case including portions thereof.
      +
      +    1.4. "Executable" means the Covered Software in any form other
      +         than Source Code.
      +
      +    1.5. "Initial Developer" means the individual or entity that first
      +         makes Original Software available under this License.
      +
      +    1.6. "Larger Work" means a work which combines Covered Software or
      +         portions thereof with code not governed by the terms of this
      +         License.
      +
      +    1.7. "License" means this document.
      +
      +    1.8. "Licensable" means having the right to grant, to the maximum
      +         extent possible, whether at the time of the initial grant or
      +         subsequently acquired, any and all of the rights conveyed
      +         herein.
      +
      +    1.9. "Modifications" means the Source Code and Executable form of
      +         any of the following:
      +
      +        A. Any file that results from an addition to, deletion from or
      +           modification of the contents of a file containing Original
      +           Software or previous Modifications;
      +
      +        B. Any new file that contains any part of the Original
      +           Software or previous Modifications; or
      +
      +        C. Any new file that is contributed or otherwise made
      +           available under the terms of this License.
      +
      +    1.10. "Original Software" means the Source Code and Executable
      +          form of computer software code that is originally released
      +          under this License.
      +
      +    1.11. "Patent Claims" means any patent claim(s), now owned or
      +          hereafter acquired, including without limitation, method,
      +          process, and apparatus claims, in any patent Licensable by
      +          grantor.
      +
      +    1.12. "Source Code" means (a) the common form of computer software
      +          code in which modifications are made and (b) associated
      +          documentation included in or with such code.
      +
      +    1.13. "You" (or "Your") means an individual or a legal entity
      +          exercising rights under, and complying with all of the terms
      +          of, this License.  For legal entities, "You" includes any
      +          entity which controls, is controlled by, or is under common
      +          control with You.  For purposes of this definition,
      +          "control" means (a) the power, direct or indirect, to cause
      +          the direction or management of such entity, whether by
      +          contract or otherwise, or (b) ownership of more than fifty
      +          percent (50%) of the outstanding shares or beneficial
      +          ownership of such entity.
      +
      +2. License Grants.
      +
      +    2.1. The Initial Developer Grant.
      +
      +    Conditioned upon Your compliance with Section 3.1 below and
      +    subject to third party intellectual property claims, the Initial
      +    Developer hereby grants You a world-wide, royalty-free,
      +    non-exclusive license:
      +
      +        (a) under intellectual property rights (other than patent or
      +            trademark) Licensable by Initial Developer, to use,
      +            reproduce, modify, display, perform, sublicense and
      +            distribute the Original Software (or portions thereof),
      +            with or without Modifications, and/or as part of a Larger
      +            Work; and
      +
      +        (b) under Patent Claims infringed by the making, using or
      +            selling of Original Software, to make, have made, use,
      +            practice, sell, and offer for sale, and/or otherwise
      +            dispose of the Original Software (or portions thereof).
      +
      +        (c) The licenses granted in Sections 2.1(a) and (b) are
      +            effective on the date Initial Developer first distributes
      +            or otherwise makes the Original Software available to a
      +            third party under the terms of this License.
      +
      +        (d) Notwithstanding Section 2.1(b) above, no patent license is
      +            granted: (1) for code that You delete from the Original
      +            Software, or (2) for infringements caused by: (i) the
      +            modification of the Original Software, or (ii) the
      +            combination of the Original Software with other software
      +            or devices.
      +
      +    2.2. Contributor Grant.
      +
      +    Conditioned upon Your compliance with Section 3.1 below and
      +    subject to third party intellectual property claims, each
      +    Contributor hereby grants You a world-wide, royalty-free,
      +    non-exclusive license:
      +
      +        (a) under intellectual property rights (other than patent or
      +            trademark) Licensable by Contributor to use, reproduce,
      +            modify, display, perform, sublicense and distribute the
      +            Modifications created by such Contributor (or portions
      +            thereof), either on an unmodified basis, with other
      +            Modifications, as Covered Software and/or as part of a
      +            Larger Work; and
      +
      +        (b) under Patent Claims infringed by the making, using, or
      +            selling of Modifications made by that Contributor either
      +            alone and/or in combination with its Contributor Version
      +            (or portions of such combination), to make, use, sell,
      +            offer for sale, have made, and/or otherwise dispose of:
      +            (1) Modifications made by that Contributor (or portions
      +            thereof); and (2) the combination of Modifications made by
      +            that Contributor with its Contributor Version (or portions
      +            of such combination).
      +
      +        (c) The licenses granted in Sections 2.2(a) and 2.2(b) are
      +            effective on the date Contributor first distributes or
      +            otherwise makes the Modifications available to a third
      +            party.
      +
      +        (d) Notwithstanding Section 2.2(b) above, no patent license is
      +            granted: (1) for any code that Contributor has deleted
      +            from the Contributor Version; (2) for infringements caused
      +            by: (i) third party modifications of Contributor Version,
      +            or (ii) the combination of Modifications made by that
      +            Contributor with other software (except as part of the
      +            Contributor Version) or other devices; or (3) under Patent
      +            Claims infringed by Covered Software in the absence of
      +            Modifications made by that Contributor.
      +
      +3. Distribution Obligations.
      +
      +    3.1. Availability of Source Code.
      +
      +    Any Covered Software that You distribute or otherwise make
      +    available in Executable form must also be made available in Source
      +    Code form and that Source Code form must be distributed only under
      +    the terms of this License.  You must include a copy of this
      +    License with every copy of the Source Code form of the Covered
      +    Software You distribute or otherwise make available.  You must
      +    inform recipients of any such Covered Software in Executable form
      +    as to how they can obtain such Covered Software in Source Code
      +    form in a reasonable manner on or through a medium customarily
      +    used for software exchange.
      +
      +    3.2. Modifications.
      +
      +    The Modifications that You create or to which You contribute are
      +    governed by the terms of this License.  You represent that You
      +    believe Your Modifications are Your original creation(s) and/or
      +    You have sufficient rights to grant the rights conveyed by this
      +    License.
      +
      +    3.3. Required Notices.
      +
      +    You must include a notice in each of Your Modifications that
      +    identifies You as the Contributor of the Modification.  You may
      +    not remove or alter any copyright, patent or trademark notices
      +    contained within the Covered Software, or any notices of licensing
      +    or any descriptive text giving attribution to any Contributor or
      +    the Initial Developer.
      +
      +    3.4. Application of Additional Terms.
      +
      +    You may not offer or impose any terms on any Covered Software in
      +    Source Code form that alters or restricts the applicable version
      +    of this License or the recipients' rights hereunder.  You may
      +    choose to offer, and to charge a fee for, warranty, support,
      +    indemnity or liability obligations to one or more recipients of
      +    Covered Software.  However, you may do so only on Your own behalf,
      +    and not on behalf of the Initial Developer or any Contributor.
      +    You must make it absolutely clear that any such warranty, support,
      +    indemnity or liability obligation is offered by You alone, and You
      +    hereby agree to indemnify the Initial Developer and every
      +    Contributor for any liability incurred by the Initial Developer or
      +    such Contributor as a result of warranty, support, indemnity or
      +    liability terms You offer.
      +
      +    3.5. Distribution of Executable Versions.
      +
      +    You may distribute the Executable form of the Covered Software
      +    under the terms of this License or under the terms of a license of
      +    Your choice, which may contain terms different from this License,
      +    provided that You are in compliance with the terms of this License
      +    and that the license for the Executable form does not attempt to
      +    limit or alter the recipient's rights in the Source Code form from
      +    the rights set forth in this License.  If You distribute the
      +    Covered Software in Executable form under a different license, You
      +    must make it absolutely clear that any terms which differ from
      +    this License are offered by You alone, not by the Initial
      +    Developer or Contributor.  You hereby agree to indemnify the
      +    Initial Developer and every Contributor for any liability incurred
      +    by the Initial Developer or such Contributor as a result of any
      +    such terms You offer.
      +
      +    3.6. Larger Works.
      +
      +    You may create a Larger Work by combining Covered Software with
      +    other code not governed by the terms of this License and
      +    distribute the Larger Work as a single product.  In such a case,
      +    You must make sure the requirements of this License are fulfilled
      +    for the Covered Software.
      +
      +4. Versions of the License.
      +
      +    4.1. New Versions.
      +
      +    Sun Microsystems, Inc. is the initial license steward and may
      +    publish revised and/or new versions of this License from time to
      +    time.  Each version will be given a distinguishing version number.
      +    Except as provided in Section 4.3, no one other than the license
      +    steward has the right to modify this License.
      +
      +    4.2. Effect of New Versions.
      +
      +    You may always continue to use, distribute or otherwise make the
      +    Covered Software available under the terms of the version of the
      +    License under which You originally received the Covered Software.
      +    If the Initial Developer includes a notice in the Original
      +    Software prohibiting it from being distributed or otherwise made
      +    available under any subsequent version of the License, You must
      +    distribute and make the Covered Software available under the terms
      +    of the version of the License under which You originally received
      +    the Covered Software.  Otherwise, You may also choose to use,
      +    distribute or otherwise make the Covered Software available under
      +    the terms of any subsequent version of the License published by
      +    the license steward.
      +
      +    4.3. Modified Versions.
      +
      +    When You are an Initial Developer and You want to create a new
      +    license for Your Original Software, You may create and use a
      +    modified version of this License if You: (a) rename the license
      +    and remove any references to the name of the license steward
      +    (except to note that the license differs from this License); and
      +    (b) otherwise make it clear that the license contains terms which
      +    differ from this License.
      +
      +5. DISCLAIMER OF WARRANTY.
      +
      +    COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS"
      +    BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
      +    INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED
      +    SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR
      +    PURPOSE OR NON-INFRINGING.  THE ENTIRE RISK AS TO THE QUALITY AND
      +    PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU.  SHOULD ANY
      +    COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
      +    INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
      +    NECESSARY SERVICING, REPAIR OR CORRECTION.  THIS DISCLAIMER OF
      +    WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.  NO USE OF
      +    ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS
      +    DISCLAIMER.
      +
      +6. TERMINATION.
      +
      +    6.1. This License and the rights granted hereunder will terminate
      +    automatically if You fail to comply with terms herein and fail to
      +    cure such breach within 30 days of becoming aware of the breach.
      +    Provisions which, by their nature, must remain in effect beyond
      +    the termination of this License shall survive.
      +
      +    6.2. If You assert a patent infringement claim (excluding
      +    declaratory judgment actions) against Initial Developer or a
      +    Contributor (the Initial Developer or Contributor against whom You
      +    assert such claim is referred to as "Participant") alleging that
      +    the Participant Software (meaning the Contributor Version where
      +    the Participant is a Contributor or the Original Software where
      +    the Participant is the Initial Developer) directly or indirectly
      +    infringes any patent, then any and all rights granted directly or
      +    indirectly to You by such Participant, the Initial Developer (if
      +    the Initial Developer is not the Participant) and all Contributors
      +    under Sections 2.1 and/or 2.2 of this License shall, upon 60 days
      +    notice from Participant terminate prospectively and automatically
      +    at the expiration of such 60 day notice period, unless if within
      +    such 60 day period You withdraw Your claim with respect to the
      +    Participant Software against such Participant either unilaterally
      +    or pursuant to a written agreement with Participant.
      +
      +    6.3. In the event of termination under Sections 6.1 or 6.2 above,
      +    all end user licenses that have been validly granted by You or any
      +    distributor hereunder prior to termination (excluding licenses
      +    granted to You by any distributor) shall survive termination.
      +
      +7. LIMITATION OF LIABILITY.
      +
      +    UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
      +    (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE
      +    INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF
      +    COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE
      +    LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
      +    CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT
      +    LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK
      +    STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
      +    COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
      +    INFORMED OF THE POSSIBILITY OF SUCH DAMAGES.  THIS LIMITATION OF
      +    LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL
      +    INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT
      +    APPLICABLE LAW PROHIBITS SUCH LIMITATION.  SOME JURISDICTIONS DO
      +    NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR
      +    CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT
      +    APPLY TO YOU.
      +
      +8. U.S. GOVERNMENT END USERS.
      +
      +    The Covered Software is a "commercial item," as that term is
      +    defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial
      +    computer software" (as that term is defined at 48
      +    C.F.R. 252.227-7014(a)(1)) and "commercial computer software
      +    documentation" as such terms are used in 48 C.F.R. 12.212
      +    (Sept. 1995).  Consistent with 48 C.F.R. 12.212 and 48
      +    C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all
      +    U.S. Government End Users acquire Covered Software with only those
      +    rights set forth herein.  This U.S. Government Rights clause is in
      +    lieu of, and supersedes, any other FAR, DFAR, or other clause or
      +    provision that addresses Government rights in computer software
      +    under this License.
      +
      +9. MISCELLANEOUS.
      +
      +    This License represents the complete agreement concerning subject
      +    matter hereof.  If any provision of this License is held to be
      +    unenforceable, such provision shall be reformed only to the extent
      +    necessary to make it enforceable.  This License shall be governed
      +    by the law of the jurisdiction specified in a notice contained
      +    within the Original Software (except to the extent applicable law,
      +    if any, provides otherwise), excluding such jurisdiction's
      +    conflict-of-law provisions.  Any litigation relating to this
      +    License shall be subject to the jurisdiction of the courts located
      +    in the jurisdiction and venue specified in a notice contained
      +    within the Original Software, with the losing party responsible
      +    for costs, including, without limitation, court costs and
      +    reasonable attorneys' fees and expenses.  The application of the
      +    United Nations Convention on Contracts for the International Sale
      +    of Goods is expressly excluded.  Any law or regulation which
      +    provides that the language of a contract shall be construed
      +    against the drafter shall not apply to this License.  You agree
      +    that You alone are responsible for compliance with the United
      +    States export administration regulations (and the export control
      +    laws and regulation of any other countries) when You use,
      +    distribute or otherwise make available any Covered Software.
      +
      +10. RESPONSIBILITY FOR CLAIMS.
      +
      +    As between Initial Developer and the Contributors, each party is
      +    responsible for claims and damages arising, directly or
      +    indirectly, out of its utilization of rights under this License
      +    and You agree to work with Initial Developer and Contributors to
      +    distribute such responsibility on an equitable basis.  Nothing
      +    herein is intended or shall be deemed to constitute any admission
      +    of liability.
      +
      +--------------------------------------------------------------------
      +
      +NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND
      +DISTRIBUTION LICENSE (CDDL)
      +
      +For Covered Software in this distribution, this License shall
      +be governed by the laws of the State of California (excluding
      +conflict-of-law provisions).
      +
      +Any litigation relating to this License shall be subject to the
      +jurisdiction of the Federal Courts of the Northern District of
      +California and the state courts of the State of California, with
      +venue lying in Santa Clara County, California.
       
    • Community Data License Agreement Permissive 2.0

      Used by:

      # Community Data License Agreement - Permissive - Version 2.0
       
      @@ -12115,9 +15728,9 @@ insights.
                       

      ISC License

      Used by:

      -
      /* Copyright (c) 2018, Google Inc.
      +                
      /* Copyright (c) 2014, Intel Corporation.
        *
        * Permission to use, copy, modify, and/or distribute this software for any
        * purpose with or without fee is hereby granted, provided that the above
      @@ -12131,15 +15744,65 @@ insights.
        * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
       
      -#include <openssl/crypto.h>
      +#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H
      +#define OPENSSL_HEADER_EC_ECP_NISTZ384_H
       
      -#include <gtest/gtest.h>
      +#include "../../limbs/limbs.h"
      +
      +#define P384_LIMBS (384u / LIMB_BITS)
      +
      +typedef struct {
      +  Limb X[P384_LIMBS];
      +  Limb Y[P384_LIMBS];
      +  Limb Z[P384_LIMBS];
      +} P384_POINT;
      +
      +typedef struct {
      +  Limb X[P384_LIMBS];
      +  Limb Y[P384_LIMBS];
      +} P384_POINT_AFFINE;
       
       
      -TEST(SelfTests, KAT) {
      -#if !defined(_MSC_VER)
      -  EXPECT_TRUE(BORINGSSL_self_test());
      -#endif
      +#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2015-2016 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +//! EdDSA Signatures.
      +
      +use super::ops::ELEM_LEN;
      +use crate::digest;
      +
      +pub mod signing;
      +pub mod verification;
      +
      +/// The length of an Ed25519 public key.
      +pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN;
      +
      +pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest {
      +    let mut ctx = digest::Context::new(&digest::SHA512);
      +    ctx.update(signature_r);
      +    ctx.update(public_key);
      +    ctx.update(msg);
      +    ctx.finish()
       }
       
    • @@ -12169,29 +15832,44 @@ TEST(SelfTests, KAT) {

      ISC License

      Used by:

      -
      // Copyright 2021 Brian Smith.
      +                
      // Copyright 2015-2022 Brian Smith.
       //
       // Permission to use, copy, modify, and/or distribute this software for any
       // purpose with or without fee is hereby granted, provided that the above
       // copyright notice and this permission notice appear in all copies.
       //
      -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
       // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
      -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
      -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
      -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
       
      -#[test]
      -fn cert_without_extensions_test() {
      -    // Check the certificate is valid with
      -    // `openssl x509 -in cert_without_extensions.der -inform DER -text -noout`
      -    const CERT_WITHOUT_EXTENSIONS_DER: &[u8] = include_bytes!("cert_without_extensions.der");
      +use crate::limb::Limb;
       
      -    assert!(webpki::EndEntityCert::try_from(CERT_WITHOUT_EXTENSIONS_DER).is_ok());
      +#[derive(Clone, Copy)]
      +#[repr(transparent)]
      +pub struct N0([Limb; 2]);
      +
      +impl N0 {
      +    #[cfg(feature = "alloc")]
      +    pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS;
      +
      +    #[inline]
      +    pub const fn precalculated(n0: u64) -> Self {
      +        #[cfg(target_pointer_width = "64")]
      +        {
      +            Self([n0, 0])
      +        }
      +
      +        #[cfg(target_pointer_width = "32")]
      +        {
      +            Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb])
      +        }
      +    }
       }
       
      @@ -12199,21 +15877,372 @@ fn cert_without_extensions_test() {

      ISC License

      Used by:

      -
      Copyright (c) 2017 Adam Wick
      +                
      // Copyright 2015-2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
       
      -Permission to use, copy, modify, and/or distribute this software for any purpose
      -with or without fee is hereby granted, provided that the above copyright notice
      -and this permission notice appear in all copies.
      +use crate::{bb, error};
       
      -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
      -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
      -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
      -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
      -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
      -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
      -THIS SOFTWARE.
      +#[deprecated(
      +    note = "To be removed. Internal function not intended for external use with no promises regarding side channels."
      +)]
      +pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
      +    bb::verify_slices_are_equal(a, b)
      +}
      +
      + +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2016 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +//! Elliptic curve operations and schemes using Curve25519.
      +
      +pub mod ed25519;
      +
      +pub mod x25519;
      +
      +mod ops;
      +mod scalar;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2016-2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +use crate::error::{KeyRejected, Unspecified};
      +
      +impl From<untrusted::EndOfInput> for Unspecified {
      +    fn from(source: untrusted::EndOfInput) -> Self {
      +        super::erase(source)
      +    }
      +}
      +
      +impl From<core::array::TryFromSliceError> for Unspecified {
      +    fn from(source: core::array::TryFromSliceError) -> Self {
      +        super::erase(source)
      +    }
      +}
      +
      +impl From<KeyRejected> for Unspecified {
      +    fn from(source: KeyRejected) -> Self {
      +        super::erase(source)
      +    }
      +}
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2018 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +//! Serialization and deserialization.
      +
      +#[doc(hidden)]
      +pub mod der;
      +
      +#[cfg(feature = "alloc")]
      +mod writer;
      +
      +#[cfg(feature = "alloc")]
      +pub(crate) mod der_writer;
      +
      +pub(crate) mod positive;
      +
      +pub use self::positive::Positive;
      +
      +#[cfg(feature = "alloc")]
      +pub(crate) use self::writer::TooLongError;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2019-2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +use super::BlockLen;
      +
      +pub(super) use self::{
      +    sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN},
      +    sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN},
      +};
      +
      +pub(super) const CHAINING_WORDS: usize = 8;
      +
      +#[cfg(any(
      +    all(target_arch = "aarch64", target_endian = "little"),
      +    all(target_arch = "arm", target_endian = "little"),
      +    target_arch = "x86_64"
      +))]
      +#[macro_use]
      +mod ffi;
      +
      +pub(super) mod fallback;
      +mod sha2_32;
      +mod sha2_64;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`.
      +#[allow(dead_code)]
      +#[inline(always)]
      +pub fn from_mut<T: ?Sized>(r: &mut T) -> *mut T {
      +    r
      +}
      +
      +// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`.
      +#[allow(dead_code)]
      +#[inline(always)]
      +pub const fn from_ref<T: ?Sized>(r: &T) -> *const T {
      +    r
      +}
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +//! Integration tests for non-public APIs.
      +
      +mod bits_tests;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +pub use self::{
      +    array::Array,
      +    base::{IndexError, Overlapping},
      +    partial_block::PartialBlock,
      +};
      +
      +mod array;
      +mod base;
      +mod partial_block;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +#![cfg(all(target_arch = "aarch64", target_endian = "little"))]
      +
      +pub(in super::super) mod mont;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +#![cfg(target_arch = "x86_64")]
      +
      +pub(in super::super::super) mod mont;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +mod storage;
      +
      +pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK};
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +pub(super) mod aarch64;
      +pub(super) mod x86_64;
       
    • @@ -12241,7 +16270,7 @@ CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

      ISC License

      Used by:

      Copyright © 2015, Simonas Kazlauskas
       
      @@ -12261,7 +16290,7 @@ THIS SOFTWARE.
                       

      ISC License

      Used by:

      Except as otherwise noted, this project is licensed under the following
       (ISC-style) terms:
      @@ -12288,12 +16317,12 @@ third-party/chromium/LICENSE.
                       

      ISC License

      Used by:

      ISC License
       
       Copyright (c) 2016, Mapbox
      -Copyright (c) 2018, Tree Cricket
      +Copyright (c) 2023, Taku Fukada
       
       Permission to use, copy, modify, and/or distribute this software for any purpose
       with or without fee is hereby granted, provided that the above copyright notice
      @@ -12312,7 +16341,8 @@ THIS SOFTWARE.
                       

      ISC License

      Used by:

      ISC License:
       
      @@ -12328,7 +16358,581 @@ THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
                       

      MIT License

      Used by:

      +
                                        MIT License
      +
      +Copyright 2024 Antoine Catton
      +Copyright 2016-2024 David Tolnay
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy of
      +this software and associated documentation files (the “Software”), to deal in
      +the Software without restriction, including without limitation the rights to
      +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
      +of the Software, and to permit persons to whom the Software is furnished to do
      +so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      # 3rd Party Notices
      +
      +The `cfg_aliases!` macro uses a lot of the code from [`tectonic_cfg_support::target_cfg!`] macro which is under the following license:
      +
      +[`tectonic_cfg_support::target_cfg!`]: https://github.com/tectonic-typesetting/tectonic/blob/f2439b936470ad27bdf92882064bc4702ee01899/cfg_support/src/lib.rs#L166
      +
      +    tectonic_cfg_support is licensed under the MIT License.
      +
      +    Permission is hereby granted, free of charge, to any person obtaining a copy
      +    of this software and associated documentation files (the “Software”), to deal
      +    in the Software without restriction, including without limitation the rights
      +    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +    copies of the Software, and to permit persons to whom the Software is
      +    furnished to do so, subject to the following conditions:
      +
      +    The above copyright notice and this permission notice shall be included in all
      +    copies or substantial portions of the Software.
      +
      +    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +    SOFTWARE.
      +---
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * Permission is hereby granted, free of charge, to any person obtaining a copy
      + * of this software and associated documentation files (the "Software"), to
      + * deal in the Software without restriction, including without limitation the
      + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
      + * sell copies of the Software, and to permit persons to whom the Software is
      + * furnished to do so, subject to the following conditions:
      + *
      + * The above copyright notice and this permission notice shall be included in
      + * all copies or substantial portions of the Software.
      + *
      + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
      + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
      + * IN THE SOFTWARE.
      + *
      + */
      +
      +//! Codegen exports used by `tonic-build`.
      +
      +pub use async_trait::async_trait;
      +pub use tokio_stream;
      +
      +pub use std::future::Future;
      +pub use std::pin::Pin;
      +pub use std::sync::Arc;
      +pub use std::task::{Context, Poll};
      +pub use tower_service::Service;
      +pub type StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
      +pub use crate::codec::{CompressionEncoding, EnabledCompressionEncodings};
      +pub use crate::extensions::GrpcMethod;
      +pub use crate::service::interceptor::InterceptedService;
      +pub use bytes::Bytes;
      +pub use http;
      +pub use http_body::Body;
      +
      +pub type BoxFuture<T, E> = self::Pin<Box<dyn self::Future<Output = Result<T, E>> + Send + 'static>>;
      +pub type BoxStream<T> =
      +    self::Pin<Box<dyn tokio_stream::Stream<Item = Result<T, crate::Status>> + Send + 'static>>;
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * Permission is hereby granted, free of charge, to any person obtaining a copy
      + * of this software and associated documentation files (the "Software"), to
      + * deal in the Software without restriction, including without limitation the
      + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
      + * sell copies of the Software, and to permit persons to whom the Software is
      + * furnished to do so, subject to the following conditions:
      + *
      + * The above copyright notice and this permission notice shall be included in
      + * all copies or substantial portions of the Software.
      + *
      + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
      + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
      + * IN THE SOFTWARE.
      + *
      + */
      +
      +//! Utilities for using Tower services with Tonic.
      +
      +pub mod interceptor;
      +pub(crate) mod layered;
      +#[cfg(feature = "router")]
      +pub(crate) mod router;
      +
      +#[doc(inline)]
      +pub use self::interceptor::{Interceptor, InterceptorLayer};
      +pub use self::layered::{LayerExt, Layered};
      +#[doc(inline)]
      +#[cfg(feature = "router")]
      +pub use self::router::{Routes, RoutesBuilder};
      +#[cfg(feature = "router")]
      +pub use axum::{Router as AxumRouter, body::Body as AxumBody};
      +
      +pub mod recover_error;
      +pub use self::recover_error::{RecoverError, RecoverErrorLayer};
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * Permission is hereby granted, free of charge, to any person obtaining a copy
      + * of this software and associated documentation files (the "Software"), to
      + * deal in the Software without restriction, including without limitation the
      + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
      + * sell copies of the Software, and to permit persons to whom the Software is
      + * furnished to do so, subject to the following conditions:
      + *
      + * The above copyright notice and this permission notice shall be included in
      + * all copies or substantial portions of the Software.
      + *
      + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
      + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
      + * IN THE SOFTWARE.
      + *
      + */
      +
      +//! Various utilities used throughout tonic.
      +
      +// some combinations of features might cause things here not to be used
      +#![allow(dead_code)]
      +
      +pub(crate) mod base64 {
      +    use base64::{
      +        alphabet,
      +        engine::{
      +            DecodePaddingMode,
      +            general_purpose::{GeneralPurpose, GeneralPurposeConfig},
      +        },
      +    };
      +
      +    pub(crate) const STANDARD: GeneralPurpose = GeneralPurpose::new(
      +        &alphabet::STANDARD,
      +        GeneralPurposeConfig::new()
      +            .with_encode_padding(true)
      +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
      +    );
      +
      +    pub(crate) const STANDARD_NO_PAD: GeneralPurpose = GeneralPurpose::new(
      +        &alphabet::STANDARD,
      +        GeneralPurposeConfig::new()
      +            .with_encode_padding(false)
      +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
      +    );
      +}
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * Permission is hereby granted, free of charge, to any person obtaining a copy
      + * of this software and associated documentation files (the "Software"), to
      + * deal in the Software without restriction, including without limitation the
      + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
      + * sell copies of the Software, and to permit persons to whom the Software is
      + * furnished to do so, subject to the following conditions:
      + *
      + * The above copyright notice and this permission notice shall be included in
      + * all copies or substantial portions of the Software.
      + *
      + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
      + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
      + * IN THE SOFTWARE.
      + *
      + */
      +
      +/// A gRPC Method info extension.
      +#[derive(Debug, Clone)]
      +pub struct GrpcMethod<'a> {
      +    service: &'a str,
      +    method: &'a str,
      +}
      +
      +impl<'a> GrpcMethod<'a> {
      +    /// Create a new `GrpcMethod` extension.
      +    #[doc(hidden)]
      +    pub fn new(service: &'a str, method: &'a str) -> Self {
      +        Self { service, method }
      +    }
      +
      +    /// gRPC service name
      +    pub fn service(&self) -> &str {
      +        self.service
      +    }
      +    /// gRPC method name
      +    pub fn method(&self) -> &str {
      +        self.method
      +    }
      +}
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * Permission is hereby granted, free of charge, to any person obtaining a copy
      + * of this software and associated documentation files (the "Software"), to
      + * deal in the Software without restriction, including without limitation the
      + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
      + * sell copies of the Software, and to permit persons to whom the Software is
      + * furnished to do so, subject to the following conditions:
      + *
      + * The above copyright notice and this permission notice shall be included in
      + * all copies or substantial portions of the Software.
      + *
      + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
      + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
      + * IN THE SOFTWARE.
      + *
      + */
      +
      +mod add_origin;
      +use self::add_origin::AddOrigin;
      +
      +mod user_agent;
      +use self::user_agent::UserAgent;
      +
      +mod reconnect;
      +use self::reconnect::Reconnect;
      +
      +mod connection;
      +pub(super) use self::connection::Connection;
      +
      +mod discover;
      +pub use self::discover::Change;
      +pub(super) use self::discover::DynamicServiceStream;
      +
      +mod io;
      +use self::io::BoxedIo;
      +
      +mod connector;
      +pub(crate) use self::connector::Connector;
      +
      +mod executor;
      +pub(super) use self::executor::{Executor, SharedExec};
      +
      +#[cfg(feature = "_tls-any")]
      +mod tls;
      +#[cfg(feature = "_tls-any")]
      +pub(super) use self::tls::TlsConnector;
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * Permission is hereby granted, free of charge, to any person obtaining a copy
      + * of this software and associated documentation files (the "Software"), to
      + * deal in the Software without restriction, including without limitation the
      + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
      + * sell copies of the Software, and to permit persons to whom the Software is
      + * furnished to do so, subject to the following conditions:
      + *
      + * The above copyright notice and this permission notice shall be included in
      + * all copies or substantial portions of the Software.
      + *
      + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
      + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
      + * IN THE SOFTWARE.
      + *
      + */
      +
      +mod io;
      +pub(crate) use self::io::{ConnectInfoLayer, ServerIo};
      +
      +#[cfg(feature = "_tls-any")]
      +mod tls;
      +#[cfg(feature = "_tls-any")]
      +pub(crate) use self::tls::TlsAcceptor;
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * Permission is hereby granted, free of charge, to any person obtaining a copy
      + * of this software and associated documentation files (the "Software"), to
      + * deal in the Software without restriction, including without limitation the
      + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
      + * sell copies of the Software, and to permit persons to whom the Software is
      + * furnished to do so, subject to the following conditions:
      + *
      + * The above copyright notice and this permission notice shall be included in
      + * all copies or substantial portions of the Software.
      + *
      + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
      + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
      + * IN THE SOFTWARE.
      + *
      + */
      +
      +pub(crate) mod grpc_timeout;
      +#[cfg(feature = "_tls-any")]
      +pub(crate) mod tls;
      +
      +pub(crate) use self::grpc_timeout::GrpcTimeout;
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * Permission is hereby granted, free of charge, to any person obtaining a copy
      + * of this software and associated documentation files (the "Software"), to
      + * deal in the Software without restriction, including without limitation the
      + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
      + * sell copies of the Software, and to permit persons to whom the Software is
      + * furnished to do so, subject to the following conditions:
      + *
      + * The above copyright notice and this permission notice shall be included in
      + * all copies or substantial portions of the Software.
      + *
      + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
      + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
      + * IN THE SOFTWARE.
      + *
      + */
      +
      +use crate::transport::channel::BoxFuture;
      +use hyper_util::rt::TokioExecutor;
      +use std::{future::Future, sync::Arc};
      +
      +pub(crate) use hyper::rt::Executor;
      +
      +#[derive(Clone)]
      +pub(crate) struct SharedExec {
      +    inner: Arc<dyn Executor<BoxFuture<'static, ()>> + Send + Sync + 'static>,
      +}
      +
      +impl SharedExec {
      +    pub(crate) fn new<E>(exec: E) -> Self
      +    where
      +        E: Executor<BoxFuture<'static, ()>> + Send + Sync + 'static,
      +    {
      +        Self {
      +            inner: Arc::new(exec),
      +        }
      +    }
      +
      +    pub(crate) fn tokio() -> Self {
      +        Self::new(TokioExecutor::new())
      +    }
      +}
      +
      +impl<F> Executor<F> for SharedExec
      +where
      +    F: Future<Output = ()> + Send + 'static,
      +{
      +    fn execute(&self, fut: F) {
      +        self.inner.execute(Box::pin(fut))
      +    }
      +}
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * Permission is hereby granted, free of charge, to any person obtaining a copy
      + * of this software and associated documentation files (the "Software"), to
      + * deal in the Software without restriction, including without limitation the
      + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
      + * sell copies of the Software, and to permit persons to whom the Software is
      + * furnished to do so, subject to the following conditions:
      + *
      + * The above copyright notice and this permission notice shall be included in
      + * all copies or substantial portions of the Software.
      + *
      + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
      + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
      + * IN THE SOFTWARE.
      + *
      + */
      +
      +use super::Connected;
      +use std::sync::Arc;
      +
      +/// Connection info for Unix domain socket streams.
      +///
      +/// This type will be accessible through [request extensions][ext] if you're using
      +/// a unix stream.
      +///
      +/// See [Connected] for more details.
      +///
      +/// [ext]: crate::Request::extensions
      +#[derive(Clone, Debug)]
      +pub struct UdsConnectInfo {
      +    /// Peer address. This will be "unnamed" for client unix sockets.
      +    pub peer_addr: Option<Arc<tokio::net::unix::SocketAddr>>,
      +    /// Process credentials for the unix socket.
      +    pub peer_cred: Option<tokio::net::unix::UCred>,
      +}
      +
      +impl Connected for tokio::net::UnixStream {
      +    type ConnectInfo = UdsConnectInfo;
      +
      +    fn connect_info(&self) -> Self::ConnectInfo {
      +        UdsConnectInfo {
      +            peer_addr: self.peer_addr().ok().map(Arc::new),
      +            peer_cred: self.peer_cred().ok(),
      +        }
      +    }
      +}
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      // Copyright (c) 2019 Nuclear Furnace
      +//
      +// Permission is hereby granted, free of charge, to any person obtaining a copy
      +// of this software and associated documentation files (the "Software"), to deal
      +// in the Software without restriction, including without limitation the rights
      +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +// copies of the Software, and to permit persons to whom the Software is
      +// furnished to do so, subject to the following conditions:
      +//
      +// The above copyright notice and this permission notice shall be included in all
      +// copies or substantial portions of the Software.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +// SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
       
      @@ -12355,7 +16959,40 @@ THE SOFTWARE.
                       

      MIT License

      Used by:

      +
      Copyright (c) 2014 Alex Crichton
      +
      +Permission is hereby granted, free of charge, to any
      +person obtaining a copy of this software and associated
      +documentation files (the "Software"), to deal in the
      +Software without restriction, including without
      +limitation the rights to use, copy, modify, merge,
      +publish, distribute, sublicense, and/or sell copies of
      +the Software, and to permit persons to whom the Software
      +is furnished to do so, subject to the following
      +conditions:
      +
      +The above copyright notice and this permission notice
      +shall be included in all copies or substantial portions
      +of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
      +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
      +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
      +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
      +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
      +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
      +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
      +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
      +DEALINGS IN THE SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      Copyright (c) 2014 Carl Lerche and other MIO contributors
       
      @@ -12382,7 +17019,6 @@ THE SOFTWARE.
                       

      MIT License

      Used by:

      Copyright (c) 2014-2019 Geoffroy Couprie
      @@ -12411,9 +17047,36 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2014-2021 Sean McArthur
      +                
      Copyright (c) 2014-2020 Optimal Computing (NZ) Ltd
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy of
      +this software and associated documentation files (the "Software"), to deal in
      +the Software without restriction, including without limitation the rights to
      +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
      +of the Software, and to permit persons to whom the Software is furnished to do
      +so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
      +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
      +IN THE SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright (c) 2014-2026 Sean McArthur
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -12438,34 +17101,8 @@ THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2014-2025 Sean McArthur
      -
      -Permission is hereby granted, free of charge, to any person obtaining a copy
      -of this software and associated documentation files (the "Software"), to deal
      -in the Software without restriction, including without limitation the rights
      -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      -copies of the Software, and to permit persons to whom the Software is
      -furnished to do so, subject to the following conditions:
      -
      -The above copyright notice and this permission notice shall be included in
      -all copies or substantial portions of the Software.
      -
      -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      -THE SOFTWARE.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      -
      Copyright (c) 2015 Jonathan Reem
       
      @@ -12498,34 +17135,34 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2015 fangyuanziti
      -
      -Permission is hereby granted, free of charge, to any person obtaining a copy
      -of this software and associated documentation files (the "Software"), to deal
      -in the Software without restriction, including without limitation the rights
      -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      -copies of the Software, and to permit persons to whom the Software is
      -furnished to do so, subject to the following conditions:
      -
      -The above copyright notice and this permission notice shall be included in
      -all copies or substantial portions of the Software.
      -
      -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      -THE SOFTWARE.
      +                
      Copyright (c) 2015 fangyuanziti
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in
      +all copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      +THE SOFTWARE.
       
    • MIT License

      Used by:

      Copyright (c) 2015 steffengy
       
      @@ -12540,16 +17177,28 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES
                       

      MIT License

      Used by:

      -
      Copyright (c) 2016 Paul Masurel
      +                
      Copyright (c) 2015-2024 Doug Tangren
       
      -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
      +Permission is hereby granted, free of charge, to any person obtaining
      +a copy of this software and associated documentation files (the
      +"Software"), to deal in the Software without restriction, including
      +without limitation the rights to use, copy, modify, merge, publish,
      +distribute, sublicense, and/or sell copies of the Software, and to
      +permit persons to whom the Software is furnished to do so, subject to
      +the following conditions:
       
      -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      +The above copyright notice and this permission notice shall be
      +included in all copies or substantial portions of the Software.
       
      -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      -
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    • MIT License

      @@ -12611,8 +17260,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

      MIT License

      Used by:

      Copyright (c) 2017 h2 authors
       
      @@ -12645,7 +17293,7 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      Copyright (c) 2018 Carl Lerche
       
      @@ -12678,52 +17326,34 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2018 Paul Masurel
      +                
      Copyright (c) 2018 Tom Parker-Shemilt
       
      -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
       
      -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
       
      -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      -
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.
    • MIT License

      Used by:

      -
      Copyright (c) 2018 by Quickwit, Inc. 
      -
      -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
      -
      -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      -
      -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      - -
      Copyright (c) 2018 by the project authors, as listed in the AUTHORS file. 
      -
      -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
      -
      -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      -
      -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      -
      Copyright (c) 2018-2019 Sean McArthur
       
      @@ -12814,7 +17444,7 @@ DEALINGS IN THE SOFTWARE.
                       

      Used by:

      Copyright (c) 2019 Carl Lerche
       
      @@ -12901,44 +17531,14 @@ SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2019 Hyper Contributors
      -
      -Permission is hereby granted, free of charge, to any
      -person obtaining a copy of this software and associated
      -documentation files (the "Software"), to deal in the
      -Software without restriction, including without
      -limitation the rights to use, copy, modify, merge,
      -publish, distribute, sublicense, and/or sell copies of
      -the Software, and to permit persons to whom the Software
      -is furnished to do so, subject to the following
      -conditions:
      -
      -The above copyright notice and this permission notice
      -shall be included in all copies or substantial portions
      -of the Software.
      -
      -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
      -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
      -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
      -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
      -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
      -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
      -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
      -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
      -DEALINGS IN THE SOFTWARE.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      -
      Copyright (c) 2019 Tokio Contributors
       
      @@ -12973,7 +17573,7 @@ DEALINGS IN THE SOFTWARE.
                       
                       
      Copyright (c) 2019 Tower Contributors
       
      @@ -13006,10 +17606,9 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2019-2021 Tower Contributors
      +                
      Copyright (c) 2019 axum Contributors
       
       Permission is hereby granted, free of charge, to any
       person obtaining a copy of this software and associated
      @@ -13040,9 +17639,10 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2019-2024 Sean McArthur & Hyper Contributors
      +                
      Copyright (c) 2019-2021 Tower Contributors
       
       Permission is hereby granted, free of charge, to any
       person obtaining a copy of this software and associated
      @@ -13106,7 +17706,94 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      +
      Copyright (c) 2019-2026 Sean McArthur & Hyper Contributors
      +
      +Permission is hereby granted, free of charge, to any
      +person obtaining a copy of this software and associated
      +documentation files (the "Software"), to deal in the
      +Software without restriction, including without
      +limitation the rights to use, copy, modify, merge,
      +publish, distribute, sublicense, and/or sell copies of
      +the Software, and to permit persons to whom the Software
      +is furnished to do so, subject to the following
      +conditions:
      +
      +The above copyright notice and this permission notice
      +shall be included in all copies or substantial portions
      +of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
      +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
      +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
      +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
      +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
      +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
      +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
      +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
      +DEALINGS IN THE SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright (c) 2019-present, Rodrigo Cesar de Freitas Dias
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright (c) 2021 Metrics Contributors
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      Copyright (c) 2023-2025 Sean McArthur
       
      @@ -13127,36 +17814,6 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
       LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
       OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
       THE SOFTWARE.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      - -
      Copyright (c) 2024 by Quickwit Inc.
      -
      -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
      -
      -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      -
      -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      - -
      Copyright (c) 2024-Present Paul Masurel
      -
      -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
      -
      -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      -
      -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
       
    • @@ -13164,6 +17821,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

      Used by:

      Copyright 2016 Nika Layzell
       
      @@ -13171,6 +17829,48 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
       
       The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
       
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright 2019 gRPC authors.
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in
      +all copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      +THE SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright 2020 David Koloski
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      +
       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
       
    • @@ -13193,25 +17893,73 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

      MIT License

      Used by:

      -
      Includes portions of humantime
      -Copyright (c) 2016 The humantime Developers
      +                
      Copyright 2021 David Koloski
       
       Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
       
       The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
       
       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      -
      -
       
    • MIT License

      Used by:

      +
      Copyright 2023 David Koloski
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright 2023 David Koloski
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright 2024 David Koloski
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13234,6 +17982,65 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
       LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
       OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
       SOFTWARE.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2016 Michael Ma
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2016 fengcen
      +Copyright (c) 2019 svartalf
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
    • MIT License

      @@ -13356,9 +18163,41 @@ SOFTWARE.

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2017 Sam Rijs
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13374,6 +18213,35 @@ furnished to do so, subject to the following conditions:
       The above copyright notice and this permission notice shall be included in all
       copies or substantial portions of the Software.
       
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2018 Canop
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
       IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
       FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      @@ -13417,7 +18285,36 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2018 sgodwincs
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13446,7 +18343,7 @@ SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      @@ -13475,36 +18372,7 @@ SOFTWARE.
                       

      MIT License

      Used by:

      -
      MIT License
      -
      -Copyright (c) 2019 Aeledfyr
      -
      -Permission is hereby granted, free of charge, to any person obtaining a copy
      -of this software and associated documentation files (the "Software"), to deal
      -in the Software without restriction, including without limitation the rights
      -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      -copies of the Software, and to permit persons to whom the Software is
      -furnished to do so, subject to the following conditions:
      -
      -The above copyright notice and this permission notice shall be included in all
      -copies or substantial portions of the Software.
      -
      -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      -SOFTWARE.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      -
      MIT License
       
      @@ -13533,8 +18401,37 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2019 Kornel
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13563,7 +18460,7 @@ SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      @@ -13617,6 +18514,40 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
       OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
       SOFTWARE.
       
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2019–2025 axum Contributors
      +
      +Permission is hereby granted, free of charge, to any
      +person obtaining a copy of this software and associated
      +documentation files (the "Software"), to deal in the
      +Software without restriction, including without
      +limitation the rights to use, copy, modify, merge,
      +publish, distribute, sublicense, and/or sell copies of
      +the Software, and to permit persons to whom the Software
      +is furnished to do so, subject to the following
      +conditions:
      +
      +The above copyright notice and this permission notice
      +shall be included in all copies or substantial portions
      +of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
      +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
      +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
      +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
      +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
      +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
      +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
      +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
      +DEALINGS IN THE SOFTWARE.
    • MIT License

      @@ -13651,11 +18582,31 @@ SOFTWARE.

      MIT License

      Used by:

      MIT License
       
      -Copyright (c) 2020 David Purdum
      +Copyright (c) 2020 Katharos Technology
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2020 Scripta Qumranica Electronica
      +
      +Created by Bronson Brown-deVost
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -13680,13 +18631,11 @@ SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      -Copyright (c) 2020 Scripta Qumranica Electronica
      -
      -Created by Bronson Brown-deVost
      +Copyright (c) 2020 magiclen.org (Ron Li)
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -13727,6 +18676,93 @@ furnished to do so, subject to the following conditions:
       The above copyright notice and this permission notice shall be included in all
       copies or substantial portions of the Software.
       
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2020-2022 Oliver Margetts
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2020-2026 Nugine
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2021 Adel Prokurov
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
       IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
       FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      @@ -13756,6 +18792,35 @@ furnished to do so, subject to the following conditions:
       The above copyright notice and this permission notice shall be included in all
       copies or substantial portions of the Software.
       
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2022 Arthur Silva
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
       IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
       FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      @@ -13770,6 +18835,7 @@ SOFTWARE.
                       

      Used by:

      MIT License
       
      @@ -13785,6 +18851,35 @@ furnished to do so, subject to the following conditions:
       The above copyright notice and this permission notice shall be included in all
       copies or substantial portions of the Software.
       
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2022 Jeroen Van Der Donckt
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
       IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
       FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      @@ -13826,7 +18921,36 @@ SOFTWARE.

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2022 sarah
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13855,8 +18979,8 @@ SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      @@ -13885,8 +19009,66 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2023 sarah
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2024 Spire Team
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13910,30 +19092,67 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
       OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
       SOFTWARE.
       
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2025 rutrum
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
    • MIT License

      Used by:

      MIT License
      @@ -13960,9 +19179,9 @@ USE OR OTHER DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      @@ -13991,7 +19210,100 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) [2021] [Marvin Countryman]
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Permission is hereby granted, free of charge, to any
      +person obtaining a copy of this software and associated
      +documentation files (the "Software"), to deal in the
      +Software without restriction, including without
      +limitation the rights to use, copy, modify, merge,
      +publish, distribute, sublicense, and/or sell copies of
      +the Software, and to permit persons to whom the Software
      +is furnished to do so, subject to the following
      +conditions:
      +
      +The above copyright notice and this permission notice
      +shall be included in all copies or substantial portions
      +of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
      +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
      +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
      +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
      +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
      +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
      +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
      +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
      +DEALINGS IN THE SOFTWARE.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Permission is hereby granted, free of charge, to any
      +person obtaining a copy of this software and associated
      +documentation files (the "Software"), to deal in the
      +Software without restriction, including without
      +limitation the rights to use, copy, modify, merge,
      +publish, distribute, sublicense, and/or sell copies of
      +the Software, and to permit persons to whom the Software
      +is furnished to do so, subject to the following
      +conditions:
      +
      +The above copyright notice and this permission notice
      +shall be included in all copies or substantial portions
      +of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
      +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
      +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
      +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
      +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
      +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
      +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
      +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
      +DEALINGS IN THE SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      Permission is hereby granted, free of charge, to any person obtaining
       a copy of this software and associated documentation files (the
      @@ -14017,12 +19329,42 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      The MIT License (MIT)
      +                
      Portions of this project are derived from atty, which bears the following
      +copyright notice and permission notice:
       
      -Copyright (c) 2014 Benjamin Sago
      -Copyright (c) 2021-2022 The Nushell Project Developers
      +Copyright (c) 2015-2019 Doug Tangren
      +
      +Permission is hereby granted, free of charge, to any person obtaining
      +a copy of this software and associated documentation files (the
      +"Software"), to deal in the Software without restriction, including
      +without limitation the rights to use, copy, modify, merge, publish,
      +distribute, sublicense, and/or sell copies of the Software, and to
      +permit persons to whom the Software is furnished to do so, subject to
      +the following conditions:
      +
      +The above copyright notice and this permission notice shall be
      +included in all copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
      +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
      +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
      +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
      +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
      +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
      +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License
      +
      +Copyright 2015 The Fancy Regex Authors.
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -14031,23 +19373,24 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
       copies of the Software, and to permit persons to whom the Software is
       furnished to do so, subject to the following conditions:
       
      -The above copyright notice and this permission notice shall be included in all
      -copies or substantial portions of the Software.
      +The above copyright notice and this permission notice shall be included in
      +all copies or substantial portions of the Software.
       
       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
       IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
       FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
       AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
       LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      -SOFTWARE.
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      +THE SOFTWARE.
       
    • MIT License

      Used by:

      The MIT License (MIT)
       
      @@ -14070,13 +19413,63 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
       LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
       OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
       SOFTWARE.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2014 Mathijs van de Nes
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2014 Y. T. CHUNG
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      +
    • MIT License

      Used by:

      The MIT License (MIT)
       
      @@ -14104,21 +19497,11 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      The MIT License (MIT)
       
      -Copyright (c) 2015 Andrew Gallant
      +Copyright (c) 2015 
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -14127,28 +19510,39 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
       copies of the Software, and to permit persons to whom the Software is
       furnished to do so, subject to the following conditions:
       
      -The above copyright notice and this permission notice shall be included in
      -all copies or substantial portions of the Software.
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
       
       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
       IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
       FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
       AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
       LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      -THE SOFTWARE.
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
       
    • MIT License

      Used by:

      The MIT License (MIT)
       
       Copyright (c) 2015 Andrew Gallant
      -Copyright (c) 2019 Paul Masurel
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -14198,6 +19592,37 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
       OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
       SOFTWARE.
       
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Carl Lerche + nix-rust Authors
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in
      +all copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      +THE SOFTWARE.
       
    • @@ -14229,6 +19654,64 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +
    • + +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Gerd Zellweger
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in
      +all copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      +THE SOFTWARE.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Guillaume Gomez
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
       
    • @@ -14264,11 +19747,102 @@ SOFTWARE.

      MIT License

      Used by:

      The MIT License (MIT)
       
      -Copyright (c) 2015 Vincent Prouillet
      +Copyright (c) 2015 Katsu Kawakami & Rustyline authors
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in
      +all copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      +THE SOFTWARE.
      +
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Markus Westerlind
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in
      +all copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      +THE SOFTWARE.
      +
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Michael Sproul
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in
      +all copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      +THE SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015-2020 the fiat-crypto authors (see
      +https://github.com/mit-plv/fiat-crypto/blob/master/AUTHORS).
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -14293,7 +19867,7 @@ SOFTWARE.
                       

      MIT License

      Used by:

      The MIT License (MIT)
       
      @@ -14309,6 +19883,35 @@ furnished to do so, subject to the following conditions:
       The above copyright notice and this permission notice shall be included in all
       copies or substantial portions of the Software.
       
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2016 nabijaczleweli
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
       IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
       FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      @@ -14352,6 +19955,7 @@ THE SOFTWARE.
                       

      MIT License

      Used by:

      The MIT License (MIT)
      @@ -14382,8 +19986,36 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      The MIT License (MIT)
      +
      +Copyright (c) 2019 Simon Heath
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      The MIT License (MIT)
       
      @@ -14450,6 +20082,36 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
       The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
       
       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2014 Benjamin Sago
      +Copyright (c) 2021-2022 The Nushell Project Developers
      +
      +Permission is hereby granted, free of charge, to any person obtaining a copy
      +of this software and associated documentation files (the "Software"), to deal
      +in the Software without restriction, including without limitation the rights
      +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      +copies of the Software, and to permit persons to whom the Software is
      +furnished to do so, subject to the following conditions:
      +
      +The above copyright notice and this permission notice shall be included in all
      +copies or substantial portions of the Software.
      +
      +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
       
    • @@ -14514,8 +20176,9 @@ SOFTWARE.
    • MIT License

      Used by:

      The MIT License (MIT)
       
      @@ -14568,6 +20231,387 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
       LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
       OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
       THE SOFTWARE.
      +
      + +
    • +

      Mozilla Public License 2.0

      +

      Used by:

      + +
      Mozilla Public License Version 2.0
      +==================================
      +
      +1. Definitions
      +--------------
      +
      +1.1. "Contributor"
      +    means each individual or legal entity that creates, contributes to
      +    the creation of, or owns Covered Software.
      +
      +1.2. "Contributor Version"
      +    means the combination of the Contributions of others (if any) used
      +    by a Contributor and that particular Contributor's Contribution.
      +
      +1.3. "Contribution"
      +    means Covered Software of a particular Contributor.
      +
      +1.4. "Covered Software"
      +    means Source Code Form to which the initial Contributor has attached
      +    the notice in Exhibit A, the Executable Form of such Source Code
      +    Form, and Modifications of such Source Code Form, in each case
      +    including portions thereof.
      +
      +1.5. "Incompatible With Secondary Licenses"
      +    means
      +
      +    (a) that the initial Contributor has attached the notice described
      +        in Exhibit B to the Covered Software; or
      +
      +    (b) that the Covered Software was made available under the terms of
      +        version 1.1 or earlier of the License, but not also under the
      +        terms of a Secondary License.
      +
      +1.6. "Executable Form"
      +    means any form of the work other than Source Code Form.
      +
      +1.7. "Larger Work"
      +    means a work that combines Covered Software with other material, in 
      +    a separate file or files, that is not Covered Software.
      +
      +1.8. "License"
      +    means this document.
      +
      +1.9. "Licensable"
      +    means having the right to grant, to the maximum extent possible,
      +    whether at the time of the initial grant or subsequently, any and
      +    all of the rights conveyed by this License.
      +
      +1.10. "Modifications"
      +    means any of the following:
      +
      +    (a) any file in Source Code Form that results from an addition to,
      +        deletion from, or modification of the contents of Covered
      +        Software; or
      +
      +    (b) any new file in Source Code Form that contains any Covered
      +        Software.
      +
      +1.11. "Patent Claims" of a Contributor
      +    means any patent claim(s), including without limitation, method,
      +    process, and apparatus claims, in any patent Licensable by such
      +    Contributor that would be infringed, but for the grant of the
      +    License, by the making, using, selling, offering for sale, having
      +    made, import, or transfer of either its Contributions or its
      +    Contributor Version.
      +
      +1.12. "Secondary License"
      +    means either the GNU General Public License, Version 2.0, the GNU
      +    Lesser General Public License, Version 2.1, the GNU Affero General
      +    Public License, Version 3.0, or any later versions of those
      +    licenses.
      +
      +1.13. "Source Code Form"
      +    means the form of the work preferred for making modifications.
      +
      +1.14. "You" (or "Your")
      +    means an individual or a legal entity exercising rights under this
      +    License. For legal entities, "You" includes any entity that
      +    controls, is controlled by, or is under common control with You. For
      +    purposes of this definition, "control" means (a) the power, direct
      +    or indirect, to cause the direction or management of such entity,
      +    whether by contract or otherwise, or (b) ownership of more than
      +    fifty percent (50%) of the outstanding shares or beneficial
      +    ownership of such entity.
      +
      +2. License Grants and Conditions
      +--------------------------------
      +
      +2.1. Grants
      +
      +Each Contributor hereby grants You a world-wide, royalty-free,
      +non-exclusive license:
      +
      +(a) under intellectual property rights (other than patent or trademark)
      +    Licensable by such Contributor to use, reproduce, make available,
      +    modify, display, perform, distribute, and otherwise exploit its
      +    Contributions, either on an unmodified basis, with Modifications, or
      +    as part of a Larger Work; and
      +
      +(b) under Patent Claims of such Contributor to make, use, sell, offer
      +    for sale, have made, import, and otherwise transfer either its
      +    Contributions or its Contributor Version.
      +
      +2.2. Effective Date
      +
      +The licenses granted in Section 2.1 with respect to any Contribution
      +become effective for each Contribution on the date the Contributor first
      +distributes such Contribution.
      +
      +2.3. Limitations on Grant Scope
      +
      +The licenses granted in this Section 2 are the only rights granted under
      +this License. No additional rights or licenses will be implied from the
      +distribution or licensing of Covered Software under this License.
      +Notwithstanding Section 2.1(b) above, no patent license is granted by a
      +Contributor:
      +
      +(a) for any code that a Contributor has removed from Covered Software;
      +    or
      +
      +(b) for infringements caused by: (i) Your and any other third party's
      +    modifications of Covered Software, or (ii) the combination of its
      +    Contributions with other software (except as part of its Contributor
      +    Version); or
      +
      +(c) under Patent Claims infringed by Covered Software in the absence of
      +    its Contributions.
      +
      +This License does not grant any rights in the trademarks, service marks,
      +or logos of any Contributor (except as may be necessary to comply with
      +the notice requirements in Section 3.4).
      +
      +2.4. Subsequent Licenses
      +
      +No Contributor makes additional grants as a result of Your choice to
      +distribute the Covered Software under a subsequent version of this
      +License (see Section 10.2) or under the terms of a Secondary License (if
      +permitted under the terms of Section 3.3).
      +
      +2.5. Representation
      +
      +Each Contributor represents that the Contributor believes its
      +Contributions are its original creation(s) or it has sufficient rights
      +to grant the rights to its Contributions conveyed by this License.
      +
      +2.6. Fair Use
      +
      +This License is not intended to limit any rights You have under
      +applicable copyright doctrines of fair use, fair dealing, or other
      +equivalents.
      +
      +2.7. Conditions
      +
      +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
      +in Section 2.1.
      +
      +3. Responsibilities
      +-------------------
      +
      +3.1. Distribution of Source Form
      +
      +All distribution of Covered Software in Source Code Form, including any
      +Modifications that You create or to which You contribute, must be under
      +the terms of this License. You must inform recipients that the Source
      +Code Form of the Covered Software is governed by the terms of this
      +License, and how they can obtain a copy of this License. You may not
      +attempt to alter or restrict the recipients' rights in the Source Code
      +Form.
      +
      +3.2. Distribution of Executable Form
      +
      +If You distribute Covered Software in Executable Form then:
      +
      +(a) such Covered Software must also be made available in Source Code
      +    Form, as described in Section 3.1, and You must inform recipients of
      +    the Executable Form how they can obtain a copy of such Source Code
      +    Form by reasonable means in a timely manner, at a charge no more
      +    than the cost of distribution to the recipient; and
      +
      +(b) You may distribute such Executable Form under the terms of this
      +    License, or sublicense it under different terms, provided that the
      +    license for the Executable Form does not attempt to limit or alter
      +    the recipients' rights in the Source Code Form under this License.
      +
      +3.3. Distribution of a Larger Work
      +
      +You may create and distribute a Larger Work under terms of Your choice,
      +provided that You also comply with the requirements of this License for
      +the Covered Software. If the Larger Work is a combination of Covered
      +Software with a work governed by one or more Secondary Licenses, and the
      +Covered Software is not Incompatible With Secondary Licenses, this
      +License permits You to additionally distribute such Covered Software
      +under the terms of such Secondary License(s), so that the recipient of
      +the Larger Work may, at their option, further distribute the Covered
      +Software under the terms of either this License or such Secondary
      +License(s).
      +
      +3.4. Notices
      +
      +You may not remove or alter the substance of any license notices
      +(including copyright notices, patent notices, disclaimers of warranty,
      +or limitations of liability) contained within the Source Code Form of
      +the Covered Software, except that You may alter any license notices to
      +the extent required to remedy known factual inaccuracies.
      +
      +3.5. Application of Additional Terms
      +
      +You may choose to offer, and to charge a fee for, warranty, support,
      +indemnity or liability obligations to one or more recipients of Covered
      +Software. However, You may do so only on Your own behalf, and not on
      +behalf of any Contributor. You must make it absolutely clear that any
      +such warranty, support, indemnity, or liability obligation is offered by
      +You alone, and You hereby agree to indemnify every Contributor for any
      +liability incurred by such Contributor as a result of warranty, support,
      +indemnity or liability terms You offer. You may include additional
      +disclaimers of warranty and limitations of liability specific to any
      +jurisdiction.
      +
      +4. Inability to Comply Due to Statute or Regulation
      +---------------------------------------------------
      +
      +If it is impossible for You to comply with any of the terms of this
      +License with respect to some or all of the Covered Software due to
      +statute, judicial order, or regulation then You must: (a) comply with
      +the terms of this License to the maximum extent possible; and (b)
      +describe the limitations and the code they affect. Such description must
      +be placed in a text file included with all distributions of the Covered
      +Software under this License. Except to the extent prohibited by statute
      +or regulation, such description must be sufficiently detailed for a
      +recipient of ordinary skill to be able to understand it.
      +
      +5. Termination
      +--------------
      +
      +5.1. The rights granted under this License will terminate automatically
      +if You fail to comply with any of its terms. However, if You become
      +compliant, then the rights granted under this License from a particular
      +Contributor are reinstated (a) provisionally, unless and until such
      +Contributor explicitly and finally terminates Your grants, and (b) on an
      +ongoing basis, if such Contributor fails to notify You of the
      +non-compliance by some reasonable means prior to 60 days after You have
      +come back into compliance. Moreover, Your grants from a particular
      +Contributor are reinstated on an ongoing basis if such Contributor
      +notifies You of the non-compliance by some reasonable means, this is the
      +first time You have received notice of non-compliance with this License
      +from such Contributor, and You become compliant prior to 30 days after
      +Your receipt of the notice.
      +
      +5.2. If You initiate litigation against any entity by asserting a patent
      +infringement claim (excluding declaratory judgment actions,
      +counter-claims, and cross-claims) alleging that a Contributor Version
      +directly or indirectly infringes any patent, then the rights granted to
      +You by any and all Contributors for the Covered Software under Section
      +2.1 of this License shall terminate.
      +
      +5.3. In the event of termination under Sections 5.1 or 5.2 above, all
      +end user license agreements (excluding distributors and resellers) which
      +have been validly granted by You or Your distributors under this License
      +prior to termination shall survive termination.
      +
      +************************************************************************
      +*                                                                      *
      +*  6. Disclaimer of Warranty                                           *
      +*  -------------------------                                           *
      +*                                                                      *
      +*  Covered Software is provided under this License on an "as is"       *
      +*  basis, without warranty of any kind, either expressed, implied, or  *
      +*  statutory, including, without limitation, warranties that the       *
      +*  Covered Software is free of defects, merchantable, fit for a        *
      +*  particular purpose or non-infringing. The entire risk as to the     *
      +*  quality and performance of the Covered Software is with You.        *
      +*  Should any Covered Software prove defective in any respect, You     *
      +*  (not any Contributor) assume the cost of any necessary servicing,   *
      +*  repair, or correction. This disclaimer of warranty constitutes an   *
      +*  essential part of this License. No use of any Covered Software is   *
      +*  authorized under this License except under this disclaimer.         *
      +*                                                                      *
      +************************************************************************
      +
      +************************************************************************
      +*                                                                      *
      +*  7. Limitation of Liability                                          *
      +*  --------------------------                                          *
      +*                                                                      *
      +*  Under no circumstances and under no legal theory, whether tort      *
      +*  (including negligence), contract, or otherwise, shall any           *
      +*  Contributor, or anyone who distributes Covered Software as          *
      +*  permitted above, be liable to You for any direct, indirect,         *
      +*  special, incidental, or consequential damages of any character      *
      +*  including, without limitation, damages for lost profits, loss of    *
      +*  goodwill, work stoppage, computer failure or malfunction, or any    *
      +*  and all other commercial damages or losses, even if such party      *
      +*  shall have been informed of the possibility of such damages. This   *
      +*  limitation of liability shall not apply to liability for death or   *
      +*  personal injury resulting from such party's negligence to the       *
      +*  extent applicable law prohibits such limitation. Some               *
      +*  jurisdictions do not allow the exclusion or limitation of           *
      +*  incidental or consequential damages, so this exclusion and          *
      +*  limitation may not apply to You.                                    *
      +*                                                                      *
      +************************************************************************
      +
      +8. Litigation
      +-------------
      +
      +Any litigation relating to this License may be brought only in the
      +courts of a jurisdiction where the defendant maintains its principal
      +place of business and such litigation shall be governed by laws of that
      +jurisdiction, without reference to its conflict-of-law provisions.
      +Nothing in this Section shall prevent a party's ability to bring
      +cross-claims or counter-claims.
      +
      +9. Miscellaneous
      +----------------
      +
      +This License represents the complete agreement concerning the subject
      +matter hereof. If any provision of this License is held to be
      +unenforceable, such provision shall be reformed only to the extent
      +necessary to make it enforceable. Any law or regulation which provides
      +that the language of a contract shall be construed against the drafter
      +shall not be used to construe this License against a Contributor.
      +
      +10. Versions of the License
      +---------------------------
      +
      +10.1. New Versions
      +
      +Mozilla Foundation is the license steward. Except as provided in Section
      +10.3, no one other than the license steward has the right to modify or
      +publish new versions of this License. Each version will be given a
      +distinguishing version number.
      +
      +10.2. Effect of New Versions
      +
      +You may distribute the Covered Software under the terms of the version
      +of the License under which You originally received the Covered Software,
      +or under the terms of any subsequent version published by the license
      +steward.
      +
      +10.3. Modified Versions
      +
      +If you create software not governed by this License, and you want to
      +create a new license for such software, you may create and use a
      +modified version of this License if you rename the license and remove
      +any references to the name of the license steward (except to note that
      +such modified license differs from this License).
      +
      +10.4. Distributing Source Code Form that is Incompatible With Secondary
      +Licenses
      +
      +If You choose to distribute Source Code Form that is Incompatible With
      +Secondary Licenses under the terms of this version of the License, the
      +notice described in Exhibit B of this License must be attached.
      +
      +Exhibit A - Source Code Form License Notice
      +-------------------------------------------
      +
      +  This Source Code Form is subject to the terms of the Mozilla Public
      +  License, v. 2.0. If a copy of the MPL was not distributed with this
      +  file, You can obtain one at http://mozilla.org/MPL/2.0/.
      +
      +If it is not possible or desirable to put the notice in a particular
      +file, then You may include the notice in a location (such as a LICENSE
      +file in a relevant directory) where a recipient would be likely to look
      +for such a notice.
      +
      +You may add additional accurate notices of copyright ownership.
      +
      +Exhibit B - "Incompatible With Secondary Licenses" Notice
      +---------------------------------------------------------
      +
      +  This Source Code Form is "Incompatible With Secondary Licenses", as
      +  defined by the Mozilla Public License, v. 2.0.
       
    • @@ -14949,187 +20993,13 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. -
    • - -
    • -

      OpenSSL License

      -

      Used by:

      - -
      /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
      - * All rights reserved.
      - *
      - * This package is an SSL implementation written
      - * by Eric Young (eay@cryptsoft.com).
      - * The implementation was written so as to conform with Netscapes SSL.
      - *
      - * This library is free for commercial and non-commercial use as long as
      - * the following conditions are aheared to.  The following conditions
      - * apply to all code found in this distribution, be it the RC4, RSA,
      - * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
      - * included with this distribution is covered by the same copyright terms
      - * except that the holder is Tim Hudson (tjh@cryptsoft.com).
      - *
      - * Copyright remains Eric Young's, and as such any Copyright notices in
      - * the code are not to be removed.
      - * If this package is used in a product, Eric Young should be given attribution
      - * as the author of the parts of the library used.
      - * This can be in the form of a textual message at program startup or
      - * in documentation (online or textual) provided with the package.
      - *
      - * Redistribution and use in source and binary forms, with or without
      - * modification, are permitted provided that the following conditions
      - * are met:
      - * 1. Redistributions of source code must retain the copyright
      - *    notice, this list of conditions and the following disclaimer.
      - * 2. Redistributions in binary form must reproduce the above copyright
      - *    notice, this list of conditions and the following disclaimer in the
      - *    documentation and/or other materials provided with the distribution.
      - * 3. All advertising materials mentioning features or use of this software
      - *    must display the following acknowledgement:
      - *    "This product includes cryptographic software written by
      - *     Eric Young (eay@cryptsoft.com)"
      - *    The word 'cryptographic' can be left out if the rouines from the library
      - *    being used are not cryptographic related :-).
      - * 4. If you include any Windows specific code (or a derivative thereof) from
      - *    the apps directory (application code) you must include an acknowledgement:
      - *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
      - *
      - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
      - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
      - * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
      - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
      - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
      - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
      - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
      - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
      - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
      - * SUCH DAMAGE.
      - *
      - * The licence and distribution terms for any publically available version or
      - * derivative of this code cannot be changed.  i.e. this code cannot simply be
      - * copied and put under another distribution licence
      - * [including the GNU Public Licence.]
      - */
      -/* ====================================================================
      - * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
      - *
      - * Redistribution and use in source and binary forms, with or without
      - * modification, are permitted provided that the following conditions
      - * are met:
      - *
      - * 1. Redistributions of source code must retain the above copyright
      - *    notice, this list of conditions and the following disclaimer.
      - *
      - * 2. Redistributions in binary form must reproduce the above copyright
      - *    notice, this list of conditions and the following disclaimer in
      - *    the documentation and/or other materials provided with the
      - *    distribution.
      - *
      - * 3. All advertising materials mentioning features or use of this
      - *    software must display the following acknowledgment:
      - *    "This product includes software developed by the OpenSSL Project
      - *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
      - *
      - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
      - *    endorse or promote products derived from this software without
      - *    prior written permission. For written permission, please contact
      - *    openssl-core@openssl.org.
      - *
      - * 5. Products derived from this software may not be called "OpenSSL"
      - *    nor may "OpenSSL" appear in their names without prior written
      - *    permission of the OpenSSL Project.
      - *
      - * 6. Redistributions of any form whatsoever must retain the following
      - *    acknowledgment:
      - *    "This product includes software developed by the OpenSSL Project
      - *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
      - *
      - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
      - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
      - * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
      - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
      - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
      - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
      - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
      - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
      - * OF THE POSSIBILITY OF SUCH DAMAGE.
      - * ====================================================================
      - *
      - * This product includes cryptographic software written by Eric Young
      - * (eay@cryptsoft.com).  This product includes software written by Tim
      - * Hudson (tjh@cryptsoft.com).
      - *
      - */
      -
      -#include <openssl/ssl.h>
      -
      -#if !defined(OPENSSL_WINDOWS) && !defined(OPENSSL_PNACL) && \
      -    !defined(OPENSSL_NO_FILESYSTEM)
      -
      -#include <dirent.h>
      -#include <errno.h>
      -#include <string.h>
      -
      -#include <openssl/err.h>
      -#include <openssl/mem.h>
      -
      -
      -int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
      -                                       const char *path) {
      -  DIR *dir = opendir(path);
      -  if (dir == NULL) {
      -    OPENSSL_PUT_ERROR(SSL, ERR_R_SYS_LIB);
      -    ERR_add_error_data(3, "opendir('", dir, "')");
      -    return 0;
      -  }
      -
      -  int ret = 0;
      -  for (;;) {
      -    // |readdir| may fail with or without setting |errno|.
      -    errno = 0;
      -    struct dirent *dirent = readdir(dir);
      -    if (dirent == NULL) {
      -      if (errno) {
      -        OPENSSL_PUT_ERROR(SSL, ERR_R_SYS_LIB);
      -        ERR_add_error_data(3, "readdir('", path, "')");
      -      } else {
      -        ret = 1;
      -      }
      -      break;
      -    }
      -
      -    char buf[1024];
      -    if (strlen(path) + strlen(dirent->d_name) + 2 > sizeof(buf)) {
      -      OPENSSL_PUT_ERROR(SSL, SSL_R_PATH_TOO_LONG);
      -      break;
      -    }
      -
      -    int r = snprintf(buf, sizeof(buf), "%s/%s", path, dirent->d_name);
      -    if (r <= 0 ||
      -        r >= (int)sizeof(buf) ||
      -        !SSL_add_file_cert_subjects_to_stack(stack, buf)) {
      -      break;
      -    }
      -  }
      -
      -  closedir(dir);
      -  return ret;
      -}
      -
      -#endif  // !WINDOWS && !PNACL && !OPENSSL_NO_FILESYSTEM
       
    • Unicode License v3

      Used by:

      UNICODE LICENSE V3
       
      @@ -15176,24 +21046,28 @@ authorization of the copyright holder.
                       

      Unicode License v3

      Used by:

      UNICODE LICENSE V3
       
      @@ -15242,12 +21116,63 @@ SPDX-License-Identifier: Unicode-3.0
       Portions of ICU4X may have been adapted from ICU4C and/or ICU4J.
       ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others.
       
      +
    • +
    • +

      zlib License

      +

      Used by:

      + +
      Copyright (c) 2021 Matias Rodriguez.
      +
      +This software is provided 'as-is', without any express or implied
      +warranty. In no event will the authors be held liable for any damages
      +arising from the use of this software.
      +
      +Permission is granted to anyone to use this software for any purpose,
      +including commercial applications, and to alter it and redistribute it
      +freely, subject to the following restrictions:
      +
      +1. The origin of this software must not be misrepresented; you must not
      +   claim that you wrote the original software. If you use this software
      +   in a product, an acknowledgment in the product documentation would be
      +   appreciated but is not required.
      +2. Altered source versions must be plainly marked as such, and must not be
      +   misrepresented as being the original software.
      +3. This notice may not be removed or altered from any source distribution.
      +
    • +
    • +

      zlib License

      +

      Used by:

      + +
      Copyright (c) 2023 Matias Rodriguez.
      +
      +This software is provided 'as-is', without any express or implied
      +warranty. In no event will the authors be held liable for any damages
      +arising from the use of this software.
      +
      +Permission is granted to anyone to use this software for any purpose,
      +including commercial applications, and to alter it and redistribute it
      +freely, subject to the following restrictions:
      +
      +1. The origin of this software must not be misrepresented; you must not
      +   claim that you wrote the original software. If you use this software
      +   in a product, an acknowledgment in the product documentation would be
      +   appreciated but is not required.
      +2. Altered source versions must be plainly marked as such, and must not be
      +   misrepresented as being the original software.
      +3. This notice may not be removed or altered from any source distribution.
    • zlib License

      Used by:

      Copyright (c) 2024 Orson Peters
       
      diff --git a/docs/src/js/classes/Index.md b/docs/src/js/classes/Index.md
      index e613882e4..b3fcf5ec3 100644
      --- a/docs/src/js/classes/Index.md
      +++ b/docs/src/js/classes/Index.md
      @@ -258,3 +258,51 @@ using an underlying bitmap index.
       #### Returns
       
       [`Index`](Index.md)
      +
      +***
      +
      +### rtree()
      +
      +```ts
      +static rtree(options?): Index
      +```
      +
      +Create an RTree index.
      +
      +An RTree index is a scalar index on a GeoArrow geometry column, that is, a
      +column whose Arrow field metadata sets `ARROW:extension:name` to a GeoArrow
      +type such as `geoarrow.point`, `geoarrow.polygon` or `geoarrow.wkb`. It
      +stores the bounding box of each geometry and accelerates spatial filters.
      +
      +The index accelerates `ST_Intersects`, `ST_Contains`, `ST_Within`,
      +`ST_Touches`, `ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy`
      +between the indexed column and a constant geometry, in either argument
      +order, for example
      +`ST_Within(geom, ST_GeomFromText('POLYGON ((...))'))`, as well as
      +`geom IS NULL`. These filters can be combined with other conditions using
      +`AND`.
      +
      +See the R-tree section of https://docs.lancedb.com/indexing/scalar-index
      +for storing geometry, the other spatial functions, and spatial filters on
      +vector search.
      +
      +Remote tables send the `RTREE` index type to the server, which must
      +support it.
      +
      +#### Parameters
      +
      +* **options?**: `Partial`<[`RTreeOptions`](../interfaces/RTreeOptions.md)>
      +
      +#### Returns
      +
      +[`Index`](Index.md)
      +
      +#### Example
      +
      +```ts
      +await table.createIndex("geom", { config: Index.rtree() });
      +await table
      +  .query()
      +  .where("ST_Intersects(geom, ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))'))")
      +  .toArray();
      +```
      diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md
      index 0a0742389..2aab45c12 100644
      --- a/docs/src/js/globals.md
      +++ b/docs/src/js/globals.md
      @@ -137,6 +137,7 @@
       - [QueryExecutionOptions](interfaces/QueryExecutionOptions.md)
       - [RTEStats](interfaces/RTEStats.md)
       - [RTEWriteSpec](interfaces/RTEWriteSpec.md)
      +- [RTreeOptions](interfaces/RTreeOptions.md)
       - [RefreshColumnOptions](interfaces/RefreshColumnOptions.md)
       - [RefreshColumnResult](interfaces/RefreshColumnResult.md)
       - [RefreshMaterializedViewResult](interfaces/RefreshMaterializedViewResult.md)
      diff --git a/docs/src/js/interfaces/RTreeOptions.md b/docs/src/js/interfaces/RTreeOptions.md
      new file mode 100644
      index 000000000..ad0a8d1ce
      --- /dev/null
      +++ b/docs/src/js/interfaces/RTreeOptions.md
      @@ -0,0 +1,21 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / RTreeOptions
      +
      +# Interface: RTreeOptions
      +
      +Options to create an `RTREE` index
      +
      +## Properties
      +
      +### pageSize?
      +
      +```ts
      +optional pageSize: number;
      +```
      +
      +The maximum number of entries in each R-tree page.
      +
      +Must be at least 2. The default is 4096.
      diff --git a/docs/web-tests/py/test_indexing.py b/docs/web-tests/py/test_indexing.py
      index f342f1b3b..bb40283ff 100644
      --- a/docs/web-tests/py/test_indexing.py
      +++ b/docs/web-tests/py/test_indexing.py
      @@ -561,6 +561,83 @@ def test_scalar_index_uuid(tmp_db):
           assert len(result) == n + len(new_users)
       
       
      +def test_scalar_index_rtree(tmp_db):
      +    db = tmp_db
      +
      +    # --8<-- [start:scalar_index_rtree_data]
      +    import pyarrow as pa
      +
      +    point = pa.struct([("x", pa.float64()), ("y", pa.float64())])
      +    schema = pa.schema(
      +        [
      +            pa.field("name", pa.string()),
      +            pa.field(
      +                "location", point, metadata={"ARROW:extension:name": "geoarrow.point"}
      +            ),
      +            pa.field("vector", pa.list_(pa.float32(), 2)),
      +        ]
      +    )
      +    places = [
      +        ("Ferry Building", -122.3937, 37.7955, [0.7, 0.3]),
      +        ("Golden Gate Park", -122.4862, 37.7694, [0.1, 0.9]),
      +        ("Oakland Museum", -122.2638, 37.7987, [1.0, 0.05]),
      +    ]
      +    data = pa.Table.from_pylist(
      +        [
      +            {"name": name, "location": {"x": x, "y": y}, "vector": vector}
      +            for name, x, y, vector in places
      +        ],
      +        schema=schema,
      +    )
      +    table = db.create_table("places", data)
      +    # --8<-- [end:scalar_index_rtree_data]
      +
      +    # --8<-- [start:scalar_index_rtree_create]
      +    from lancedb.index import RTree
      +
      +    table.create_index("location", config=RTree())
      +    # --8<-- [end:scalar_index_rtree_create]
      +
      +    # --8<-- [start:scalar_index_rtree_filter]
      +    san_francisco = (
      +        "ST_GeomFromText('POLYGON ((-122.52 37.70, -122.35 37.70, "
      +        "-122.35 37.83, -122.52 37.83, -122.52 37.70))')"
      +    )
      +    in_san_francisco = f"ST_Within(location, {san_francisco})"
      +
      +    places_in_sf = table.search().where(in_san_francisco).select(["name"]).to_list()
      +    # [{'name': 'Ferry Building'}, {'name': 'Golden Gate Park'}]
      +    # --8<-- [end:scalar_index_rtree_filter]
      +
      +    assert sorted(row["name"] for row in places_in_sf) == [
      +        "Ferry Building",
      +        "Golden Gate Park",
      +    ]
      +
      +    # --8<-- [start:scalar_index_rtree_vector]
      +    # The nearest place overall is in Oakland; the spatial prefilter keeps the
      +    # search inside San Francisco.
      +    nearest_in_sf = (
      +        table.search([1.0, 0.0])
      +        .where(in_san_francisco)
      +        .select(["name", "_distance"])
      +        .limit(1)
      +        .to_list()
      +    )
      +    # [{'name': 'Ferry Building', '_distance': 0.18}]
      +    # --8<-- [end:scalar_index_rtree_vector]
      +
      +    assert nearest_in_sf[0]["name"] == "Ferry Building"
      +    assert nearest_in_sf[0]["_distance"] == pytest.approx(0.18, abs=1e-6)
      +    nearest = table.search([1.0, 0.0]).select(["name", "_distance"]).limit(1)
      +    assert nearest.to_list()[0]["name"] == "Oakland Museum"
      +
      +    # --8<-- [start:scalar_index_rtree_explain]
      +    plan = table.search().where(in_san_francisco).explain_plan(verbose=True)
      +    assert "ScalarIndexQuery" in plan
      +    # --8<-- [end:scalar_index_rtree_explain]
      +
      +
       @pytest.mark.asyncio
       async def test_scalar_index_nested_fields(mem_db_async):
           db = mem_db_async
      diff --git a/docs/web/indexing/scalar-index.mdx b/docs/web/indexing/scalar-index.mdx
      index 3d7b3a864..a3bf06957 100644
      --- a/docs/web/indexing/scalar-index.mdx
      +++ b/docs/web/indexing/scalar-index.mdx
      @@ -20,19 +20,25 @@ import {
           PyScalarIndexUuidWait as ScalarIndexUuidWait,
           PyScalarIndexUuidUpsert as ScalarIndexUuidUpsert,
           PyScalarIndexNestedFields as ScalarIndexNestedFields,
      +    PyScalarIndexRtreeData as ScalarIndexRtreeData,
      +    PyScalarIndexRtreeCreate as ScalarIndexRtreeCreate,
      +    PyScalarIndexRtreeFilter as ScalarIndexRtreeFilter,
      +    PyScalarIndexRtreeVector as ScalarIndexRtreeVector,
      +    PyScalarIndexRtreeExplain as ScalarIndexRtreeExplain,
       } from '/snippets/indexing.mdx';
       
       Scalar indexes accelerate filters on values such as numbers, categories and
       strings. Use them for selective table queries or metadata filters combined
       with vector and full-text search.
       
      -LanceDB supports five types of scalar indexes:
      +LanceDB supports these scalar index types, among others:
       
       - `BTREE`: Stores column data in sorted order for binary search. Best for columns with many unique values.
       - `BITMAP`: Uses bitmaps to track value presence. Ideal for columns with few unique values (e.g., categories, tags).
       - `LABEL_LIST`: Special index for `List` and `LargeList` columns of primitive values supporting `array_has_all` and `array_has_any` queries.
       - `FM`: FM-Index over string or binary columns that accelerates substring search via `contains(col, 'needle')`.
       - `NGRAM`: Trigram index over UTF-8 string columns that accelerates substring search via `contains(col, 'needle')`, along with some `LIKE` and regular-expression filters.
      +- `RTREE`: R-tree over GeoArrow geometry columns that accelerates spatial filters such as `ST_Intersects` and `ST_Within`.
       
       
       Use scalar indexes with:
      @@ -52,6 +58,7 @@ Use scalar indexes with:
       | List of low cardinality of numbers or strings                   | `array_has_any`, `array_has_all`          | `LABEL_LIST` |
       | String or binary (`Utf8`, `LargeUtf8`, `Binary`, `LargeBinary`) | `contains(col, 'needle')`                 | `FM`         |
       | String (`Utf8`, `LargeUtf8`)                                    | `contains(col, 'needle')`, `LIKE`, regex  | `NGRAM`      |
      +| GeoArrow geometry (`geoarrow.point`, `geoarrow.polygon`, `geoarrow.wkb`, ...) | `ST_Intersects`, `ST_Within`, `ST_Contains` and other spatial relationships, `is null` | `RTREE` |
       
       ## Scalar Index Operations
       
      @@ -222,6 +229,139 @@ before consolidating their segments. Consolidation rejects these legacy
       row-ID segments. Tables without stable row IDs retain the earlier index format.
       
       
      +## R-tree index for geospatial filters {#rtree}
      +
      +The `RTREE` index is a scalar index over a column of GeoArrow geometries. It
      +stores the bounding box of every geometry and accelerates spatial filters, on
      +their own or as the prefilter of a vector search. Use it when queries restrict
      +results to a region, such as the scenes over an area of interest, the places
      +inside a city, or the log records along a route.
      +
      +### Store geometry as GeoArrow {#rtree-geoarrow}
      +
      +A column holds geometry when its Arrow field carries GeoArrow extension
      +metadata: `ARROW:extension:name` names the geometry type, such as
      +`geoarrow.point`, `geoarrow.linestring`, `geoarrow.polygon` or
      +`geoarrow.multipolygon` for native coordinates, or `geoarrow.wkb` for
      +well-known binary. LanceDB keeps that metadata when it stores the column.
      +
      +You can build the field with PyArrow alone. A point is a struct of `x` and `y`
      +coordinates:
      +
      +
      +    
      +    {ScalarIndexRtreeData}
      +    
      +
      +
      +Libraries such as [`geoarrow-rust-core`](https://pypi.org/project/geoarrow-rust-core/)
      +(`geoarrow.rust.core`) produce arrays with this metadata already, so a table
      +built from them works the same way.
      +
      +### Create an R-tree index {#rtree-create}
      +
      +Pass the `RTree` config in Python, `Index.rtree()` in TypeScript, or
      +`Index::RTree` in Rust. The optional page size sets the maximum number of
      +entries in each R-tree page; it must be at least 2 and defaults to 4096.
      +
      +
      +    
      +    {ScalarIndexRtreeCreate}
      +    
      +
      +```typescript TypeScript icon="square-js"
      +import { Index } from "@lancedb/lancedb";
      +
      +await table.createIndex("location", { config: Index.rtree() });
      +```
      +
      +```rust Rust icon="rust"
      +use lancedb::index::Index;
      +use lancedb::index::scalar::RTreeIndexBuilder;
      +
      +table
      +    .create_index(&["location"], Index::RTree(RTreeIndexBuilder::default()))
      +    .execute()
      +    .await?;
      +```
      +
      +
      +`list_indices()` reports the index type as `"RTree"`, and `index_stats()`
      +reports it as `"RTREE"`. In the Rust crate, building the index on a local
      +table requires the `geo` feature; the Python and TypeScript packages include
      +it. In the embedded library, `optimize()` adds new rows to the index. Rows
      +that are not indexed yet are still filtered, just without the index.
      +
      +### Filter with spatial predicates {#rtree-filter}
      +
      +Spatial predicates go in `where()` like any other filter. Build constant
      +geometries with `ST_GeomFromText('')` or `ST_Point(x, y)`:
      +
      +
      +    
      +    {ScalarIndexRtreeFilter}
      +    
      +
      +
      +The index answers `ST_Intersects`, `ST_Contains`, `ST_Within`, `ST_Touches`,
      +`ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy` between the
      +indexed column and a constant geometry, in either argument order, as well as
      +`IS NULL` on the column. A spatial predicate combined
      +with other conditions through `AND` still uses the index; one combined through
      +`OR` with a condition on an unindexed column does not.
      +
      +The R-tree compares bounding boxes, so it returns a superset of the answer:
      +every row whose bounding box overlaps the query geometry's bounding box. LanceDB
      +then evaluates the exact predicate on those candidate rows, so the results are
      +the same with or without the index. A point just outside a triangle but inside
      +the triangle's bounding box is read, then discarded.
      +
      +Other spatial functions, such as `ST_Distance(location, ST_Point(x, y)) < d`
      +for a radius filter, work in filters but are evaluated row by row, without the
      +index. `ST_DWithin` is not available. To use the index for a radius filter,
      +pair the distance check with an indexed predicate on a bounding polygon:
      +`ST_Intersects(location, ) AND ST_Distance(location, 
      ) < d`. + +Spatial functions are planar: they treat coordinates as points on a flat +plane, and `ST_Distance` returns a distance in the units of the column's +coordinates. For longitude and latitude, `d` is in degrees, not meters, and a +degree of longitude shrinks toward the poles. Project the data to a metric +coordinate system first if you need distances in meters. + +### Combine with vector search {#rtree-vector-search} + +A spatial filter on a vector search is a prefilter by default: the R-tree +narrows the candidates first, and the nearest neighbors are found among the +rows that match. + + + + {ScalarIndexRtreeVector} + + + +With `prefilter=False` in Python, or `postfilter()` in TypeScript, the filter +is applied to the nearest neighbors instead, without the index, so it can +return fewer rows than the limit. + +### Check that the index is used {#rtree-explain} + +An indexed spatial filter appears as a `ScalarIndexQuery` on the R-tree in the +query plan: + + + + {ScalarIndexRtreeExplain} + + + + +On a remote table, `create_index` sends the request with the `RTREE` index +type, and spatial filters are sent to the server as written. Whether the +server can build the index and evaluate `ST_*` functions depends on its +version. + + ## Index UUID Columns LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)`), enabling efficient lookups and filtering on UUID-based primary keys. diff --git a/docs/web/snippets/indexing.mdx b/docs/web/snippets/indexing.mdx index dfa43b6ce..bd3b7af7f 100644 --- a/docs/web/snippets/indexing.mdx +++ b/docs/web/snippets/indexing.mdx @@ -26,6 +26,16 @@ export const PyScalarIndexOptimize = "table.add([{\"vector\": [7, 8], \"book_id\ export const PyScalarIndexPrefilter = "table = db.open_table(\"book_with_embeddings\")\ntable.search([1.2] * 2).where(\"book_id != 3\").limit(10).to_pandas()\n"; +export const PyScalarIndexRtreeCreate = "from lancedb.index import RTree\n\ntable.create_index(\"location\", config=RTree())\n"; + +export const PyScalarIndexRtreeData = "import pyarrow as pa\n\npoint = pa.struct([(\"x\", pa.float64()), (\"y\", pa.float64())])\nschema = pa.schema(\n [\n pa.field(\"name\", pa.string()),\n pa.field(\n \"location\", point, metadata={\"ARROW:extension:name\": \"geoarrow.point\"}\n ),\n pa.field(\"vector\", pa.list_(pa.float32(), 2)),\n ]\n)\nplaces = [\n (\"Ferry Building\", -122.3937, 37.7955, [0.7, 0.3]),\n (\"Golden Gate Park\", -122.4862, 37.7694, [0.1, 0.9]),\n (\"Oakland Museum\", -122.2638, 37.7987, [1.0, 0.05]),\n]\ndata = pa.Table.from_pylist(\n [\n {\"name\": name, \"location\": {\"x\": x, \"y\": y}, \"vector\": vector}\n for name, x, y, vector in places\n ],\n schema=schema,\n)\ntable = db.create_table(\"places\", data)\n"; + +export const PyScalarIndexRtreeExplain = "plan = table.search().where(in_san_francisco).explain_plan(verbose=True)\nassert \"ScalarIndexQuery\" in plan\n"; + +export const PyScalarIndexRtreeFilter = "san_francisco = (\n \"ST_GeomFromText('POLYGON ((-122.52 37.70, -122.35 37.70, \"\n \"-122.35 37.83, -122.52 37.83, -122.52 37.70))')\"\n)\nin_san_francisco = f\"ST_Within(location, {san_francisco})\"\n\nplaces_in_sf = table.search().where(in_san_francisco).select([\"name\"]).to_list()\n# [{'name': 'Ferry Building'}, {'name': 'Golden Gate Park'}]\n"; + +export const PyScalarIndexRtreeVector = "# The nearest place overall is in Oakland; the spatial prefilter keeps the\n# search inside San Francisco.\nnearest_in_sf = (\n table.search([1.0, 0.0])\n .where(in_san_francisco)\n .select([\"name\", \"_distance\"])\n .limit(1)\n .to_list()\n)\n# [{'name': 'Ferry Building', '_distance': 0.18}]\n"; + export const PyScalarIndexUuidData = "def generate_random_names():\n base_names = [\"Alice\", \"Bob\", \"Carla\", \"David\", \"Eve\", \"Frank\", \"Grace\"]\n letter = random.choice(string.ascii_uppercase)\n return f\"{random.choice(base_names)} {letter}.\"\n\ndef generate_uuids(num_items):\n return [uuid.uuid4().bytes for _ in range(num_items)]\n\n# Generate some UUIDs and random names\nn = 7\nuuids = generate_uuids(n)\nnames = [generate_random_names() for _ in range(n)]\n"; export const PyScalarIndexUuidTable = "table_name = \"index-on-uuid\"\n\nuuid_array = pa.array(uuids, pa.uuid())\nname_array = pa.array(names, pa.string())\nschema = pa.schema(\n [\n pa.field(\"id\", pa.uuid()),\n pa.field(\"name\", pa.string()),\n ]\n)\ndata_table = pa.Table.from_arrays([uuid_array, name_array], schema=schema)\ntable = db.create_table(table_name, data=data_table, mode=\"overwrite\")\n"; diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 6de370ef1..540d53c04 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -46,7 +46,7 @@ aws-lc-rs = "=1.18.1" napi-build = "2.3.1" [features] -default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/goosefs", "lancedb/metrics-otel"] +default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/goosefs", "lancedb/metrics-otel", "lancedb/geo"] fp16kernels = ["lancedb/fp16kernels"] remote = ["lancedb/remote"] experimental-functions = ["lancedb/experimental-functions"] diff --git a/nodejs/RUST_THIRD_PARTY_LICENSES.html b/nodejs/RUST_THIRD_PARTY_LICENSES.html index 461fb2715..d9ca180c5 100644 --- a/nodejs/RUST_THIRD_PARTY_LICENSES.html +++ b/nodejs/RUST_THIRD_PARTY_LICENSES.html @@ -44,19 +44,19 @@

      Overview of licenses:

      All license text:

      @@ -65,230 +65,20 @@

      BSD Zero Clause License

      Used by:

      -
      Copyright (C) 2020 by museun <museun@outlook.com>
      +                
      Copyright (C) Jonas Schievink <jonasschievink@gmail.com>
       
      -Permission to use, copy, modify, and/or distribute this software for any purpose
      -with or without fee is hereby granted.
      +Permission to use, copy, modify, and/or distribute this software for
      +any purpose with or without fee is hereby granted.
       
      -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
      -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
      -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
      -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
      -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
      -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
      -THIS SOFTWARE.
      -
      -
    • -
    • -

      Apache License 2.0

      -

      Used by:

      - -
      -                                 Apache License
      -                           Version 2.0, January 2004
      -                        http://www.apache.org/licenses/
      -
      -   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      -
      -   1. Definitions.
      -
      -      "License" shall mean the terms and conditions for use, reproduction,
      -      and distribution as defined by Sections 1 through 9 of this document.
      -
      -      "Licensor" shall mean the copyright owner or entity authorized by
      -      the copyright owner that is granting the License.
      -
      -      "Legal Entity" shall mean the union of the acting entity and all
      -      other entities that control, are controlled by, or are under common
      -      control with that entity. For the purposes of this definition,
      -      "control" means (i) the power, direct or indirect, to cause the
      -      direction or management of such entity, whether by contract or
      -      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      -      outstanding shares, or (iii) beneficial ownership of such entity.
      -
      -      "You" (or "Your") shall mean an individual or Legal Entity
      -      exercising permissions granted by this License.
      -
      -      "Source" form shall mean the preferred form for making modifications,
      -      including but not limited to software source code, documentation
      -      source, and configuration files.
      -
      -      "Object" form shall mean any form resulting from mechanical
      -      transformation or translation of a Source form, including but
      -      not limited to compiled object code, generated documentation,
      -      and conversions to other media types.
      -
      -      "Work" shall mean the work of authorship, whether in Source or
      -      Object form, made available under the License, as indicated by a
      -      copyright notice that is included in or attached to the work
      -      (an example is provided in the Appendix below).
      -
      -      "Derivative Works" shall mean any work, whether in Source or Object
      -      form, that is based on (or derived from) the Work and for which the
      -      editorial revisions, annotations, elaborations, or other modifications
      -      represent, as a whole, an original work of authorship. For the purposes
      -      of this License, Derivative Works shall not include works that remain
      -      separable from, or merely link (or bind by name) to the interfaces of,
      -      the Work and Derivative Works thereof.
      -
      -      "Contribution" shall mean any work of authorship, including
      -      the original version of the Work and any modifications or additions
      -      to that Work or Derivative Works thereof, that is intentionally
      -      submitted to Licensor for inclusion in the Work by the copyright owner
      -      or by an individual or Legal Entity authorized to submit on behalf of
      -      the copyright owner. For the purposes of this definition, "submitted"
      -      means any form of electronic, verbal, or written communication sent
      -      to the Licensor or its representatives, including but not limited to
      -      communication on electronic mailing lists, source code control systems,
      -      and issue tracking systems that are managed by, or on behalf of, the
      -      Licensor for the purpose of discussing and improving the Work, but
      -      excluding communication that is conspicuously marked or otherwise
      -      designated in writing by the copyright owner as "Not a Contribution."
      -
      -      "Contributor" shall mean Licensor and any individual or Legal Entity
      -      on behalf of whom a Contribution has been received by Licensor and
      -      subsequently incorporated within the Work.
      -
      -   2. Grant of Copyright License. Subject to the terms and conditions of
      -      this License, each Contributor hereby grants to You a perpetual,
      -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      -      copyright license to reproduce, prepare Derivative Works of,
      -      publicly display, publicly perform, sublicense, and distribute the
      -      Work and such Derivative Works in Source or Object form.
      -
      -   3. Grant of Patent License. Subject to the terms and conditions of
      -      this License, each Contributor hereby grants to You a perpetual,
      -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      -      (except as stated in this section) patent license to make, have made,
      -      use, offer to sell, sell, import, and otherwise transfer the Work,
      -      where such license applies only to those patent claims licensable
      -      by such Contributor that are necessarily infringed by their
      -      Contribution(s) alone or by combination of their Contribution(s)
      -      with the Work to which such Contribution(s) was submitted. If You
      -      institute patent litigation against any entity (including a
      -      cross-claim or counterclaim in a lawsuit) alleging that the Work
      -      or a Contribution incorporated within the Work constitutes direct
      -      or contributory patent infringement, then any patent licenses
      -      granted to You under this License for that Work shall terminate
      -      as of the date such litigation is filed.
      -
      -   4. Redistribution. You may reproduce and distribute copies of the
      -      Work or Derivative Works thereof in any medium, with or without
      -      modifications, and in Source or Object form, provided that You
      -      meet the following conditions:
      -
      -      (a) You must give any other recipients of the Work or
      -          Derivative Works a copy of this License; and
      -
      -      (b) You must cause any modified files to carry prominent notices
      -          stating that You changed the files; and
      -
      -      (c) You must retain, in the Source form of any Derivative Works
      -          that You distribute, all copyright, patent, trademark, and
      -          attribution notices from the Source form of the Work,
      -          excluding those notices that do not pertain to any part of
      -          the Derivative Works; and
      -
      -      (d) If the Work includes a "NOTICE" text file as part of its
      -          distribution, then any Derivative Works that You distribute must
      -          include a readable copy of the attribution notices contained
      -          within such NOTICE file, excluding those notices that do not
      -          pertain to any part of the Derivative Works, in at least one
      -          of the following places: within a NOTICE text file distributed
      -          as part of the Derivative Works; within the Source form or
      -          documentation, if provided along with the Derivative Works; or,
      -          within a display generated by the Derivative Works, if and
      -          wherever such third-party notices normally appear. The contents
      -          of the NOTICE file are for informational purposes only and
      -          do not modify the License. You may add Your own attribution
      -          notices within Derivative Works that You distribute, alongside
      -          or as an addendum to the NOTICE text from the Work, provided
      -          that such additional attribution notices cannot be construed
      -          as modifying the License.
      -
      -      You may add Your own copyright statement to Your modifications and
      -      may provide additional or different license terms and conditions
      -      for use, reproduction, or distribution of Your modifications, or
      -      for any such Derivative Works as a whole, provided Your use,
      -      reproduction, and distribution of the Work otherwise complies with
      -      the conditions stated in this License.
      -
      -   5. Submission of Contributions. Unless You explicitly state otherwise,
      -      any Contribution intentionally submitted for inclusion in the Work
      -      by You to the Licensor shall be under the terms and conditions of
      -      this License, without any additional terms or conditions.
      -      Notwithstanding the above, nothing herein shall supersede or modify
      -      the terms of any separate license agreement you may have executed
      -      with Licensor regarding such Contributions.
      -
      -   6. Trademarks. This License does not grant permission to use the trade
      -      names, trademarks, service marks, or product names of the Licensor,
      -      except as required for reasonable and customary use in describing the
      -      origin of the Work and reproducing the content of the NOTICE file.
      -
      -   7. Disclaimer of Warranty. Unless required by applicable law or
      -      agreed to in writing, Licensor provides the Work (and each
      -      Contributor provides its Contributions) on an "AS IS" BASIS,
      -      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      -      implied, including, without limitation, any warranties or conditions
      -      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      -      PARTICULAR PURPOSE. You are solely responsible for determining the
      -      appropriateness of using or redistributing the Work and assume any
      -      risks associated with Your exercise of permissions under this License.
      -
      -   8. Limitation of Liability. In no event and under no legal theory,
      -      whether in tort (including negligence), contract, or otherwise,
      -      unless required by applicable law (such as deliberate and grossly
      -      negligent acts) or agreed to in writing, shall any Contributor be
      -      liable to You for damages, including any direct, indirect, special,
      -      incidental, or consequential damages of any character arising as a
      -      result of this License or out of the use or inability to use the
      -      Work (including but not limited to damages for loss of goodwill,
      -      work stoppage, computer failure or malfunction, or any and all
      -      other commercial damages or losses), even if such Contributor
      -      has been advised of the possibility of such damages.
      -
      -   9. Accepting Warranty or Additional Liability. While redistributing
      -      the Work or Derivative Works thereof, You may choose to offer,
      -      and charge a fee for, acceptance of support, warranty, indemnity,
      -      or other liability obligations and/or rights consistent with this
      -      License. However, in accepting such obligations, You may act only
      -      on Your own behalf and on Your sole responsibility, not on behalf
      -      of any other Contributor, and only if You agree to indemnify,
      -      defend, and hold each Contributor harmless for any liability
      -      incurred by, or claims asserted against, such Contributor by reason
      -      of your accepting any such warranty or additional liability.
      -
      -   END OF TERMS AND CONDITIONS
      -
      -   APPENDIX: How to apply the Apache License to your work.
      -
      -      To apply the Apache License to your work, attach the following
      -      boilerplate notice, with the fields enclosed by brackets "[]"
      -      replaced with your own identifying information. (Don't include
      -      the brackets!)  The text should be enclosed in the appropriate
      -      comment syntax for the file format. We also recommend that a
      -      file or class name and description of purpose be included on the
      -      same "printed page" as the copyright notice for easier
      -      identification within third-party archives.
      -
      -   Copyright 2023 Jacob Pratt
      -
      -   Licensed under the Apache License, Version 2.0 (the "License");
      -   you may not use this file except in compliance with the License.
      -   You may obtain a copy of the License at
      -
      -       http://www.apache.org/licenses/LICENSE-2.0
      -
      -   Unless required by applicable law or agreed to in writing, software
      -   distributed under the License is distributed on an "AS IS" BASIS,
      -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      -   See the License for the specific language governing permissions and
      -   limitations under the License.
      +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
      +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
      +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
      +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
       
    • @@ -505,7 +295,7 @@ THIS SOFTWARE.

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -715,23 +505,224 @@ THIS SOFTWARE.
                       

      Apache License 2.0

      Used by:

      +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + @@ -943,7 +934,8 @@ THIS SOFTWARE.

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -1155,34 +1147,549 @@ THIS SOFTWARE.
                       

      Apache License 2.0

      Used by:

      +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +--- LLVM Exceptions to the Apache 2.0 License ----
      +
      +As an exception, if, as a result of your compiling your source code, portions
      +of this Software are embedded into an Object form of such source code, you
      +may redistribute such embedded portions in such Object form without complying
      +with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
      +
      +In addition, if you combine or link compiled forms of this Software with
      +software that is licensed under the GPLv2 ("Combined Software") and if a
      +court of competent jurisdiction determines that the patent provision (Section
      +3), the indemnity provision (Section 9) or other Section of the License
      +conflicts with the conditions of the GPLv2, you may retroactively and
      +prospectively choose to deem waived or otherwise exclude such Section(s) of
      +the License, but only in their entirety and only with respect to the Combined
      +Software.
      +
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +Licenses for support code
      +-------------------------
      +
      +Parts of the TLS test suite are under the Go license. This code is not included
      +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so
      +distributing code linked against BoringSSL does not trigger this license:
      +
      +Copyright (c) 2009 The Go Authors. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are
      +met:
      +
      +   * Redistributions of source code must retain the above copyright
      +notice, this list of conditions and the following disclaimer.
      +   * Redistributions in binary form must reproduce the above
      +copyright notice, this list of conditions and the following disclaimer
      +in the documentation and/or other materials provided with the
      +distribution.
      +   * Neither the name of Google Inc. nor the names of its
      +contributors may be used to endorse or promote products derived from
      +this software without specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
      +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
      +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
      +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
      +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
      +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
      +BoringSSL uses the Chromium test infrastructure to run a continuous build,
      +trybots etc. The scripts which manage this, and the script for generating build
      +metadata, are under the Chromium license. Distributing code linked against
      +BoringSSL does not trigger this license.
      +
      +Copyright 2015 The Chromium Authors. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are
      +met:
      +
      +   * Redistributions of source code must retain the above copyright
      +notice, this list of conditions and the following disclaimer.
      +   * Redistributions in binary form must reproduce the above
      +copyright notice, this list of conditions and the following disclaimer
      +in the documentation and/or other materials provided with the
      +distribution.
      +   * Neither the name of Google Inc. nor the names of its
      +contributors may be used to endorse or promote products derived from
      +this software without specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
      +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
      +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
      +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
      +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
      +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                        Apache License
      @@ -1396,6 +1903,237 @@ This project includes code from Apache Aurora.
       Copyright: 2016 The Apache Software Foundation.
       Home page: https://aurora.apache.org/
       License: http://www.apache.org/licenses/LICENSE-2.0
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +--------------------------------------------------------------------------------
      +
      +arrow-array/src/delta.rs: MIT
      +
      +This file is derived from the chronoutil crate. The full MIT license
      +text is in arrow-array/LICENSE-MIT.
       
    • @@ -1403,9 +2141,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0

      Used by:

                                        Apache License
      @@ -1615,7 +2351,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -1815,7 +2551,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Used by:

                                        Apache License
      @@ -2025,41 +2760,30 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2268,7 +2992,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2477,7 +3201,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2667,7 +3392,425 @@ License: http://www.apache.org/licenses/LICENSE-2.0
             same "printed page" as the copyright notice for easier
             identification within third-party archives.
       
      -   Copyright 2020 - 2025 Tatsuya Kawano
      +   Copyright 2019 TiKV Project Authors.
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright 2020 - 2026 Tatsuya Kawano
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright 2020 Sébastien Crozet
       
          Licensed under the Apache License, Version 2.0 (the "License");
          you may not use this file except in compliance with the License.
      @@ -2687,7 +3830,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2895,8 +4037,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -3315,7 +4457,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -3524,9 +4666,20 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -3735,7 +4888,455 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

      +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +------------------------------------------------------------------------------------
      +This product bundles third-party components under other open source licenses.
      +This section summarizes those components and their licenses. See the referenced
      +license files for text of these licenses.
      +
      +
      +Creative Commons Zero v1.0 Universal
      +------------------------------------
      +
      +bindings/dotnet/.gitignore
      +
      +The above file is derived from VisualStudio.gitignore in
      +https://github.com/github/gitignore. Its license text is in
      +bindings/dotnet/LICENSE-CC0-1.0.txt.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +   
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                       Apache License
                                  Version 2.0, January 2004
      @@ -3944,6 +5545,218 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

      +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "{}"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright Individual contributors
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                       Apache License
      @@ -4153,22 +5966,28 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -4378,12 +6197,221 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

      +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright 2020 Sébastien Crozet
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                      Apache License
                                  Version 2.0, January 2004
      @@ -4593,7 +6621,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                     Apache License
                                  Version 2.0, January 2004
      @@ -5011,15 +7039,15 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5229,7 +7257,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5437,7 +7465,8 @@ limitations under the License.

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5646,8 +7675,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5856,7 +7884,6 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
      @@ -6066,7 +8093,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -6256,7 +8283,7 @@ APPENDIX: How to apply the Apache License to your work.
          same "printed page" as the copyright notice for easier
          identification within third-party archives.
       
      -Copyright 2018 The pin-utils authors
      +Copyright 2018 Brian Myers
       
       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
      @@ -6275,8 +8302,8 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -6683,6 +8710,215 @@ You may obtain a copy of the License at
       
          http://www.apache.org/licenses/LICENSE-2.0
       
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright 2019 quininer kel
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      @@ -6695,7 +8931,9 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -6905,7 +9143,7 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -7323,7 +9561,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -7532,7 +9770,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -7743,7 +9981,216 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright 2024 Liam Gray <gmail@liamg.me>
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                    Apache License
                               Version 2.0, January 2004
      @@ -7953,7 +10400,8 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -8161,156 +10609,171 @@ limitations under the License.

      Apache License 2.0

      Used by:

        +
      • addr2line 0.25.1
      • ahash 0.8.12
      • -
      • arc-swap 1.7.1
      • -
      • arrayvec 0.7.6
      • +
      • arc-swap 1.9.3
      • +
      • arrayvec 0.7.8
      • async-channel 2.5.0
      • -
      • async-compression 0.4.19
      • -
      • async-lock 3.4.1
      • +
      • async-compression 0.4.42
      • +
      • async-lock 3.4.2
      • atomic-waker 1.1.2
      • autocfg 1.5.0
      • -
      • base64 0.21.7
      • +
      • backtrace 0.3.76
      • base64 0.22.1
      • -
      • bitflags 2.9.4
      • -
      • bumpalo 3.19.0
      • +
      • base64 0.23.1
      • +
      • bitflags 1.3.2
      • +
      • bitflags 2.11.1
      • +
      • bstr 1.12.1
      • +
      • bumpalo 3.20.2
      • bytes-utils 0.1.4
      • -
      • cc 1.2.40
      • -
      • cexpr 0.6.0
      • -
      • cfg-if 1.0.3
      • -
      • cmake 0.1.54
      • +
      • cast 0.3.0
      • +
      • cc 1.2.62
      • +
      • cfg-if 0.1.10
      • +
      • cfg-if 1.0.4
      • +
      • cmake 0.1.58
      • +
      • compression-codecs 0.4.38
      • +
      • compression-core 0.4.32
      • concurrent-queue 2.5.0
      • const-random-macro 0.1.16
      • const-random 0.1.18
      • core-foundation-sys 0.8.7
      • core-foundation 0.10.1
      • core-foundation 0.9.4
      • +
      • cpp_demangle 0.4.5
      • +
      • criterion-plot 0.8.2
      • +
      • criterion 0.8.2
      • crossbeam-channel 0.5.15
      • crossbeam-deque 0.8.6
      • -
      • crossbeam-epoch 0.9.18
      • +
      • crossbeam-epoch 0.9.20
      • crossbeam-queue 0.3.12
      • +
      • crossbeam-skiplist 0.1.3
      • crossbeam-utils 0.8.21
      • +
      • debugid 0.8.0
      • displaydoc 0.2.5
      • either 1.15.0
      • +
      • encoding_rs_io 0.1.7
      • equivalent 1.0.2
      • errno 0.3.14
      • event-listener-strategy 0.5.4
      • -
      • event-listener 5.4.1
      • -
      • fastrand 2.3.0
      • -
      • find-msvc-tools 0.1.3
      • +
      • event-listener 5.4.2
      • +
      • fastrand 2.4.1
      • +
      • find-msvc-tools 0.1.9
      • +
      • findshlibs 0.10.2
      • fixedbitset 0.5.7
      • +
      • flate2 1.1.9
      • fnv 1.0.7
      • form_urlencoded 1.2.2
      • -
      • fs4 0.8.4
      • +
      • foyer-intrusive-collections 0.10.0-dev
      • +
      • fs4 0.13.1
      • futures-timer 3.0.3
      • -
      • geohash 0.13.1
      • +
      • geohash 0.13.2
      • +
      • gimli 0.32.3
      • glob 0.3.3
      • -
      • group 0.12.1
      • +
      • group 0.14.0
      • hash32 0.3.1
      • hashbrown 0.14.5
      • hashbrown 0.15.5
      • -
      • hashbrown 0.16.0
      • +
      • hashbrown 0.16.1
      • +
      • hashbrown 0.17.1
      • heapless 0.8.0
      • heck 0.5.0
      • hermit-abi 0.5.2
      • httparse 1.10.1
      • -
      • hyper-rustls 0.24.2
      • -
      • hyper-rustls 0.27.7
      • +
      • hyper-rustls 0.27.9
      • +
      • hyper-timeout 0.5.2
      • idna 1.1.0
      • -
      • idna_adapter 1.2.1
      • -
      • indexmap 2.12.0
      • -
      • itertools 0.11.0
      • -
      • itertools 0.12.1
      • +
      • idna_adapter 1.2.2
      • +
      • indexmap 2.14.0
      • itertools 0.13.0
      • itertools 0.14.0
      • +
      • itertools 0.15.0
      • jobserver 0.1.34
      • -
      • js-sys 0.3.81
      • +
      • js-sys 0.3.107
      • lazy_static 1.5.0
      • -
      • lazycell 1.3.0
      • -
      • linux-raw-sys 0.11.0
      • -
      • linux-raw-sys 0.4.15
      • +
      • linux-raw-sys 0.12.1
      • lock_api 0.4.14
      • -
      • log 0.4.28
      • +
      • log 0.4.34
      • lzma-sys 0.1.20
      • matrixmultiply 0.3.10
      • mime 0.3.17
      • -
      • multimap 0.10.1
      • ndarray 0.16.1
      • -
      • num-bigint-dig 0.8.4
      • +
      • num-bigint-dig 0.8.6
      • num-bigint 0.4.6
      • +
      • num-bigint 0.5.1
      • num-complex 0.4.6
      • num-integer 0.1.46
      • num-iter 0.1.45
      • +
      • num-rational 0.4.2
      • num-traits 0.2.19
      • num_cpus 1.17.0
      • -
      • once_cell 1.21.3
      • -
      • openssl-probe 0.1.6
      • +
      • oauth2 5.0.0
      • +
      • object 0.37.3
      • +
      • once_cell 1.21.4
      • +
      • openssl-probe 0.2.1
      • parking 2.2.1
      • parking_lot 0.12.5
      • parking_lot_core 0.9.12
      • percent-encoding 2.3.2
      • petgraph 0.8.3
      • -
      • pkg-config 0.3.32
      • -
      • prost-build 0.14.3
      • -
      • prost-derive 0.14.3
      • +
      • pkg-config 0.3.33
      • +
      • prost-derive 0.14.4
      • prost-types 0.14.3
      • -
      • prost 0.14.3
      • +
      • prost 0.14.4
      • +
      • rand_xoshiro 0.6.0
      • rawpointer 0.2.1
      • rayon-core 1.13.0
      • -
      • rayon 1.11.0
      • -
      • regex-automata 0.4.13
      • -
      • regex-lite 0.1.7
      • -
      • regex-syntax 0.8.6
      • -
      • regex 1.12.2
      • +
      • rayon 1.12.0
      • +
      • regex-automata 0.4.16
      • +
      • regex-lite 0.1.9
      • +
      • regex-syntax 0.8.11
      • +
      • regex 1.13.1
      • ring 0.17.14
      • +
      • roaring 0.11.5
      • robust 1.2.0
      • -
      • rustc-hash 1.1.0
      • +
      • rustc-demangle 0.1.27
      • rustc_version 0.4.1
      • -
      • rustix 0.38.44
      • -
      • rustix 1.1.2
      • -
      • rustls-native-certs 0.6.3
      • -
      • rustls-native-certs 0.8.1
      • -
      • rustls-pemfile 1.0.4
      • -
      • rustls-pemfile 2.2.0
      • -
      • rustls 0.21.12
      • -
      • rustls 0.23.31
      • +
      • rustix 1.1.4
      • +
      • rustls-native-certs 0.8.3
      • +
      • rustls 0.23.46
      • scoped-tls 1.0.1
      • scopeguard 1.2.0
      • -
      • sct 0.7.1
      • -
      • security-framework-sys 2.15.0
      • -
      • security-framework 2.11.1
      • -
      • security-framework 3.5.1
      • -
      • serde_with 3.15.0
      • -
      • serde_with_macros 3.15.0
      • -
      • shellexpand 3.1.1
      • -
      • signal-hook-registry 1.4.6
      • -
      • smallvec 1.15.1
      • -
      • socket2 0.5.10
      • -
      • socket2 0.6.0
      • -
      • sqlparser 0.59.0
      • -
      • sqlparser_derive 0.3.0
      • -
      • stable_deref_trait 1.2.0
      • -
      • syn 1.0.109
      • +
      • security-framework-sys 2.17.0
      • +
      • security-framework 3.7.0
      • +
      • serde_with 3.24.0
      • +
      • serde_with_macros 3.24.0
      • +
      • shellexpand 3.1.2
      • +
      • signal-hook-registry 1.4.8
      • +
      • simd_cesu8 1.1.1
      • +
      • smallvec 1.16.5
      • +
      • socket2 0.6.3
      • +
      • sqlparser 0.62.0
      • +
      • sqlparser_derive 0.5.0
      • +
      • stable_deref_trait 1.2.1
      • +
      • str_stack 0.1.1
      • +
      • symlink 0.1.0
      • system-configuration-sys 0.6.0
      • -
      • system-configuration 0.6.1
      • -
      • tempfile 3.23.0
      • +
      • system-configuration 0.7.0
      • +
      • tempfile 3.27.0
      • thread-tree 0.3.3
      • -
      • thread_local 1.1.9
      • -
      • unicase 2.8.1
      • -
      • unicode-segmentation 1.12.0
      • -
      • unicode-width 0.2.2
      • -
      • url 2.5.7
      • -
      • uuid 1.18.1
      • +
      • thread_local 1.1.10
      • +
      • tinytemplate 1.2.1
      • +
      • unicase 2.9.0
      • +
      • unicode-normalization 0.1.25
      • +
      • unicode-segmentation 1.13.2
      • +
      • unicode-width 0.2.3
      • +
      • url 2.5.8
      • +
      • uuid 1.29.0
      • version_check 0.9.5
      • wasi 0.11.1+wasi-snapshot-preview1
      • wasi 0.14.7+wasi-0.2.4
      • -
      • wasm-bindgen-backend 0.2.104
      • -
      • wasm-bindgen-futures 0.4.54
      • -
      • wasm-bindgen-macro-support 0.2.104
      • -
      • wasm-bindgen-macro 0.2.104
      • -
      • wasm-bindgen-shared 0.2.104
      • -
      • wasm-bindgen 0.2.104
      • -
      • web-sys 0.3.81
      • -
      • wit-bindgen 0.46.0
      • +
      • wasip2 1.0.3+wasi-0.2.9
      • +
      • wasm-bindgen-futures 0.4.80
      • +
      • wasm-bindgen-macro-support 0.2.130
      • +
      • wasm-bindgen-macro 0.2.130
      • +
      • wasm-bindgen-shared 0.2.130
      • +
      • wasm-bindgen 0.2.130
      • +
      • web-sys 0.3.107
      • +
      • wit-bindgen 0.57.1
      • wkb 0.9.2
      • wkt 0.14.0
      • xmlparser 0.13.6
      • @@ -8522,7 +10985,7 @@ limitations under the License.

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -8732,14 +11195,12 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -8949,41 +11410,55 @@ limitations under the License.
                         

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -9192,10 +11667,209 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        +
                                      Apache License
        +                        Version 2.0, January 2004
        +                     http://www.apache.org/licenses/
        +
        +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +1. Definitions.
        +
        +   "License" shall mean the terms and conditions for use, reproduction,
        +   and distribution as defined by Sections 1 through 9 of this document.
        +
        +   "Licensor" shall mean the copyright owner or entity authorized by
        +   the copyright owner that is granting the License.
        +
        +   "Legal Entity" shall mean the union of the acting entity and all
        +   other entities that control, are controlled by, or are under common
        +   control with that entity. For the purposes of this definition,
        +   "control" means (i) the power, direct or indirect, to cause the
        +   direction or management of such entity, whether by contract or
        +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +   outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +   "You" (or "Your") shall mean an individual or Legal Entity
        +   exercising permissions granted by this License.
        +
        +   "Source" form shall mean the preferred form for making modifications,
        +   including but not limited to software source code, documentation
        +   source, and configuration files.
        +
        +   "Object" form shall mean any form resulting from mechanical
        +   transformation or translation of a Source form, including but
        +   not limited to compiled object code, generated documentation,
        +   and conversions to other media types.
        +
        +   "Work" shall mean the work of authorship, whether in Source or
        +   Object form, made available under the License, as indicated by a
        +   copyright notice that is included in or attached to the work
        +   (an example is provided in the Appendix below).
        +
        +   "Derivative Works" shall mean any work, whether in Source or Object
        +   form, that is based on (or derived from) the Work and for which the
        +   editorial revisions, annotations, elaborations, or other modifications
        +   represent, as a whole, an original work of authorship. For the purposes
        +   of this License, Derivative Works shall not include works that remain
        +   separable from, or merely link (or bind by name) to the interfaces of,
        +   the Work and Derivative Works thereof.
        +
        +   "Contribution" shall mean any work of authorship, including
        +   the original version of the Work and any modifications or additions
        +   to that Work or Derivative Works thereof, that is intentionally
        +   submitted to Licensor for inclusion in the Work by the copyright owner
        +   or by an individual or Legal Entity authorized to submit on behalf of
        +   the copyright owner. For the purposes of this definition, "submitted"
        +   means any form of electronic, verbal, or written communication sent
        +   to the Licensor or its representatives, including but not limited to
        +   communication on electronic mailing lists, source code control systems,
        +   and issue tracking systems that are managed by, or on behalf of, the
        +   Licensor for the purpose of discussing and improving the Work, but
        +   excluding communication that is conspicuously marked or otherwise
        +   designated in writing by the copyright owner as "Not a Contribution."
        +
        +   "Contributor" shall mean Licensor and any individual or Legal Entity
        +   on behalf of whom a Contribution has been received by Licensor and
        +   subsequently incorporated within the Work.
        +
        +2. Grant of Copyright License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   copyright license to reproduce, prepare Derivative Works of,
        +   publicly display, publicly perform, sublicense, and distribute the
        +   Work and such Derivative Works in Source or Object form.
        +
        +3. Grant of Patent License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   (except as stated in this section) patent license to make, have made,
        +   use, offer to sell, sell, import, and otherwise transfer the Work,
        +   where such license applies only to those patent claims licensable
        +   by such Contributor that are necessarily infringed by their
        +   Contribution(s) alone or by combination of their Contribution(s)
        +   with the Work to which such Contribution(s) was submitted. If You
        +   institute patent litigation against any entity (including a
        +   cross-claim or counterclaim in a lawsuit) alleging that the Work
        +   or a Contribution incorporated within the Work constitutes direct
        +   or contributory patent infringement, then any patent licenses
        +   granted to You under this License for that Work shall terminate
        +   as of the date such litigation is filed.
        +
        +4. Redistribution. You may reproduce and distribute copies of the
        +   Work or Derivative Works thereof in any medium, with or without
        +   modifications, and in Source or Object form, provided that You
        +   meet the following conditions:
        +
        +   (a) You must give any other recipients of the Work or
        +       Derivative Works a copy of this License; and
        +
        +   (b) You must cause any modified files to carry prominent notices
        +       stating that You changed the files; and
        +
        +   (c) You must retain, in the Source form of any Derivative Works
        +       that You distribute, all copyright, patent, trademark, and
        +       attribution notices from the Source form of the Work,
        +       excluding those notices that do not pertain to any part of
        +       the Derivative Works; and
        +
        +   (d) If the Work includes a "NOTICE" text file as part of its
        +       distribution, then any Derivative Works that You distribute must
        +       include a readable copy of the attribution notices contained
        +       within such NOTICE file, excluding those notices that do not
        +       pertain to any part of the Derivative Works, in at least one
        +       of the following places: within a NOTICE text file distributed
        +       as part of the Derivative Works; within the Source form or
        +       documentation, if provided along with the Derivative Works; or,
        +       within a display generated by the Derivative Works, if and
        +       wherever such third-party notices normally appear. The contents
        +       of the NOTICE file are for informational purposes only and
        +       do not modify the License. You may add Your own attribution
        +       notices within Derivative Works that You distribute, alongside
        +       or as an addendum to the NOTICE text from the Work, provided
        +       that such additional attribution notices cannot be construed
        +       as modifying the License.
        +
        +   You may add Your own copyright statement to Your modifications and
        +   may provide additional or different license terms and conditions
        +   for use, reproduction, or distribution of Your modifications, or
        +   for any such Derivative Works as a whole, provided Your use,
        +   reproduction, and distribution of the Work otherwise complies with
        +   the conditions stated in this License.
        +
        +5. Submission of Contributions. Unless You explicitly state otherwise,
        +   any Contribution intentionally submitted for inclusion in the Work
        +   by You to the Licensor shall be under the terms and conditions of
        +   this License, without any additional terms or conditions.
        +   Notwithstanding the above, nothing herein shall supersede or modify
        +   the terms of any separate license agreement you may have executed
        +   with Licensor regarding such Contributions.
        +
        +6. Trademarks. This License does not grant permission to use the trade
        +   names, trademarks, service marks, or product names of the Licensor,
        +   except as required for reasonable and customary use in describing the
        +   origin of the Work and reproducing the content of the NOTICE file.
        +
        +7. Disclaimer of Warranty. Unless required by applicable law or
        +   agreed to in writing, Licensor provides the Work (and each
        +   Contributor provides its Contributions) on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +   implied, including, without limitation, any warranties or conditions
        +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +   PARTICULAR PURPOSE. You are solely responsible for determining the
        +   appropriateness of using or redistributing the Work and assume any
        +   risks associated with Your exercise of permissions under this License.
        +
        +8. Limitation of Liability. In no event and under no legal theory,
        +   whether in tort (including negligence), contract, or otherwise,
        +   unless required by applicable law (such as deliberate and grossly
        +   negligent acts) or agreed to in writing, shall any Contributor be
        +   liable to You for damages, including any direct, indirect, special,
        +   incidental, or consequential damages of any character arising as a
        +   result of this License or out of the use or inability to use the
        +   Work (including but not limited to damages for loss of goodwill,
        +   work stoppage, computer failure or malfunction, or any and all
        +   other commercial damages or losses), even if such Contributor
        +   has been advised of the possibility of such damages.
        +
        +9. Accepting Warranty or Additional Liability. While redistributing
        +   the Work or Derivative Works thereof, You may choose to offer,
        +   and charge a fee for, acceptance of support, warranty, indemnity,
        +   or other liability obligations and/or rights consistent with this
        +   License. However, in accepting such obligations, You may act only
        +   on Your own behalf and on Your sole responsibility, not on behalf
        +   of any other Contributor, and only if You agree to indemnify,
        +   defend, and hold each Contributor harmless for any liability
        +   incurred by, or claims asserted against, such Contributor by reason
        +   of your accepting any such warranty or additional liability.
        +
        +END OF TERMS AND CONDITIONS
        +
        +Copyright (c) 2015-2022 Amod Malviya
        +
        +Licensed under the Apache License, Version 2.0 (the "License");
        +you may not use this file except in compliance with the License.
        +You may obtain a copy of the License at
        +
        +	http://www.apache.org/licenses/LICENSE-2.0
        +
        +Unless required by applicable law or agreed to in writing, software
        +distributed under the License is distributed on an "AS IS" BASIS,
        +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +See the License for the specific language governing permissions and
        +limitations under the License.
        +
        + +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                      Apache License
                                 Version 2.0, January 2004
        @@ -9390,11 +12064,13 @@ APPENDIX: How to apply the Apache License to your work.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -9603,8 +12279,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -9813,7 +12488,9 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Apache License
                                    Version 2.0, January 2004
        @@ -10022,7 +12699,9 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Apache License
         Version 2.0, January 2004
        @@ -10301,128 +12980,169 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Apache License
         Version 2.0, January 2004
        @@ -10739,10 +13459,10 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Rust-chrono is dual-licensed under The MIT License [1] and
        -Apache 2.0 License [2]. Copyright (c) 2014--2025, Kang Seonghoon and
        +Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and
         contributors.
         
         Nota Bene: This is same as the Rust Project's own license.
        @@ -10981,6 +13701,40 @@ See the License for the specific language governing permissions and
         limitations under the License.
         ~~~~
         
        +
        +
      • +
      • +

        BSD 2-Clause "Simplified" License

        +

        Used by:

        + +
        Copyright (c) 2013-2014, Naoki Yoshinaga, Paul Meng
        +All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions are
        +met:
        +
        +1. Redistributions of source code must retain the above copyright
        +   notice, this list of conditions and the following disclaimer.
        +
        +2. Redistributions in binary form must reproduce the above copyright
        +   notice, this list of conditions and the following disclaimer in the
        +   documentation and/or other materials provided with the
        +   distribution.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
        +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
        +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
        +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
        +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
        +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
        +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
        +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
        +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
         
      • @@ -11015,6 +13769,99 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
      • + +
      • +

        BSD 2-Clause "Simplified" License

        +

        Used by:

        + +
        Copyright (c) 2017-2020
        +All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions are met:
        +
        +1. Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
        +2. Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
        +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        + +
        // Copyright © WHATWG (Apple, Google, Mozilla, Microsoft).
        +//
        +// Redistribution and use in source and binary forms, with or without
        +// modification, are permitted provided that the following conditions are met:
        +//
        +// 1. Redistributions of source code must retain the above copyright notice, this
        +//    list of conditions and the following disclaimer.
        +//
        +// 2. Redistributions in binary form must reproduce the above copyright notice,
        +//    this list of conditions and the following disclaimer in the documentation
        +//    and/or other materials provided with the distribution.
        +//
        +// 3. Neither the name of the copyright holder nor the names of its
        +//    contributors may be used to endorse or promote products derived from
        +//    this software without specific prior written permission.
        +//
        +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
        +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
        +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
        +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
        +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
        +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +/// The PUA code points special-cased in the GB18030 encoder.
        +pub(crate) static GB18030_2022_OVERRIDE_PUA: [u16; 18] = [
        +    0xE78D, 0xE78E, 0xE78F, 0xE790, 0xE791, 0xE792, 0xE793, 0xE794, 0xE795, 0xE796, 0xE81E, 0xE826,
        +    0xE82B, 0xE82C, 0xE832, 0xE843, 0xE854, 0xE864,
        +];
        +
        +/// The bytes corresponding to the PUA code points special-cased in the GB18030 encoder.
        +pub(crate) static GB18030_2022_OVERRIDE_BYTES: [[u8; 2]; 18] = [
        +    [0xA6, 0xD9],
        +    [0xA6, 0xDA],
        +    [0xA6, 0xDB],
        +    [0xA6, 0xDC],
        +    [0xA6, 0xDD],
        +    [0xA6, 0xDE],
        +    [0xA6, 0xDF],
        +    [0xA6, 0xEC],
        +    [0xA6, 0xED],
        +    [0xA6, 0xF3],
        +    [0xFE, 0x59],
        +    [0xFE, 0x61],
        +    [0xFE, 0x66],
        +    [0xFE, 0x67],
        +    [0xFE, 0x6D],
        +    [0xFE, 0x7E],
        +    [0xFE, 0x90],
        +    [0xFE, 0xA0],
        +];
         
      • @@ -11022,6 +13869,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

        Used by:

        BSD 3-Clause License
         
        @@ -11058,26 +13906,27 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                         

        BSD 3-Clause "New" or "Revised" License

        Used by:

        BSD 3-Clause License
         
        -Copyright (c) 2013, Jyun-Yan You
        -All rights reserved.
        +Copyright (c) 2026, Alexandre Bury
         
         Redistribution and use in source and binary forms, with or without
         modification, are permitted provided that the following conditions are met:
         
        -* Redistributions of source code must retain the above copyright notice, this
        -  list of conditions and the following disclaimer.
        +1. Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
         
        -* Redistributions in binary form must reproduce the above copyright notice,
        -  this list of conditions and the following disclaimer in the documentation
        -  and/or other materials provided with the distribution.
        +2. Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
         
        -* Neither the name of the copyright holder nor the names of its
        -  contributors may be used to endorse or promote products derived from
        -  this software without specific prior written permission.
        +3. Neither the name of the copyright holder nor the names of its
        +   contributors may be used to endorse or promote products derived from
        +   this software without specific prior written permission.
         
         THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
         AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        @@ -11095,10 +13944,50 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                         

        BSD 3-Clause "New" or "Revised" License

        Used by:

        +
        BSD License
        +
        +For Zstandard software
        +
        +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without modification,
        +are permitted provided that the following conditions are met:
        +
        + * Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
        +
        + * Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
        +
        + * Neither the name Facebook, nor Meta, nor the names of its contributors may
        +   be used to endorse or promote products derived from this software without
        +   specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
        +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        +
        Copyright (c) 2001, Dr Martin Porter
         Copyright (c) 2004,2005, Richard Boulton
        +Copyright (c) 2013, Yoshiki Shibukawa
        +Copyright (c) 2006-2025, Olly Betts
         All rights reserved.
         
         Redistribution and use in source and binary forms, with or without
        @@ -11123,16 +14012,16 @@ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
         LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
         ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
         (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
      • BSD 3-Clause "New" or "Revised" License

        Used by:

        Copyright (c) 2016 Dropbox, Inc.
         All rights reserved.
        @@ -11189,8 +14078,47 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                         

        BSD 3-Clause "New" or "Revised" License

        Used by:

        +
        Copyright (c) 2026, frostem contributors
        +Copyright (c) 2001, Dr Martin Porter
        +Copyright (c) 2004,2005, Richard Boulton
        +Copyright (c) 2013, Yoshiki Shibukawa
        +Copyright (c) 2006-2025, Olly Betts
        +All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions
        +are met:
        +
        +  1. Redistributions of source code must retain the above copyright notice,
        +     this list of conditions and the following disclaimer.
        +  2. Redistributions in binary form must reproduce the above copyright notice,
        +     this list of conditions and the following disclaimer in the documentation
        +     and/or other materials provided with the distribution.
        +  3. Neither the name of the Snowball project nor the names of its contributors
        +     may be used to endorse or promote products derived from this software
        +     without specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
        +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        +
        Copyright (c) <year> <owner>. 
         
        @@ -11237,13 +14165,53 @@ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
         CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
         OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
         OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        + +
        The auto-generated bindings are under the 3-clause BSD license:
        +
        +BSD License
        +
        +For Zstandard software
        +
        +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without modification,
        +are permitted provided that the following conditions are met:
        +
        + * Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
        +
        + * Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
        +
        + * Neither the name Facebook, nor Meta, nor the names of its contributors may
        +   be used to endorse or promote products derived from this software without
        +   specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
        +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
         
      • Boost Software License 1.0

        Used by:

        Boost Software License - Version 1.0 - August 17th, 2003
         
        @@ -11397,13 +14365,405 @@ express Statement of Purpose.
          d. Affirmer understands and acknowledges that Creative Commons is not a
             party to this document and has no duty or obligation with respect to
             this CC0 or use of the Work.
        +
        +
      • +
      • +

        Common Development and Distribution License 1.0

        +

        Used by:

        + +
        Unless otherwise noted, all files in this distribution are released
        +under the Common Development and Distribution License (CDDL).
        +Exceptions are noted within the associated source files.
        +
        +--------------------------------------------------------------------
        +
        +
        +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE Version 1.0
        +
        +1. Definitions.
        +
        +    1.1. "Contributor" means each individual or entity that creates
        +         or contributes to the creation of Modifications.
        +
        +    1.2. "Contributor Version" means the combination of the Original
        +         Software, prior Modifications used by a Contributor (if any),
        +         and the Modifications made by that particular Contributor.
        +
        +    1.3. "Covered Software" means (a) the Original Software, or (b)
        +         Modifications, or (c) the combination of files containing
        +         Original Software with files containing Modifications, in
        +         each case including portions thereof.
        +
        +    1.4. "Executable" means the Covered Software in any form other
        +         than Source Code.
        +
        +    1.5. "Initial Developer" means the individual or entity that first
        +         makes Original Software available under this License.
        +
        +    1.6. "Larger Work" means a work which combines Covered Software or
        +         portions thereof with code not governed by the terms of this
        +         License.
        +
        +    1.7. "License" means this document.
        +
        +    1.8. "Licensable" means having the right to grant, to the maximum
        +         extent possible, whether at the time of the initial grant or
        +         subsequently acquired, any and all of the rights conveyed
        +         herein.
        +
        +    1.9. "Modifications" means the Source Code and Executable form of
        +         any of the following:
        +
        +        A. Any file that results from an addition to, deletion from or
        +           modification of the contents of a file containing Original
        +           Software or previous Modifications;
        +
        +        B. Any new file that contains any part of the Original
        +           Software or previous Modifications; or
        +
        +        C. Any new file that is contributed or otherwise made
        +           available under the terms of this License.
        +
        +    1.10. "Original Software" means the Source Code and Executable
        +          form of computer software code that is originally released
        +          under this License.
        +
        +    1.11. "Patent Claims" means any patent claim(s), now owned or
        +          hereafter acquired, including without limitation, method,
        +          process, and apparatus claims, in any patent Licensable by
        +          grantor.
        +
        +    1.12. "Source Code" means (a) the common form of computer software
        +          code in which modifications are made and (b) associated
        +          documentation included in or with such code.
        +
        +    1.13. "You" (or "Your") means an individual or a legal entity
        +          exercising rights under, and complying with all of the terms
        +          of, this License.  For legal entities, "You" includes any
        +          entity which controls, is controlled by, or is under common
        +          control with You.  For purposes of this definition,
        +          "control" means (a) the power, direct or indirect, to cause
        +          the direction or management of such entity, whether by
        +          contract or otherwise, or (b) ownership of more than fifty
        +          percent (50%) of the outstanding shares or beneficial
        +          ownership of such entity.
        +
        +2. License Grants.
        +
        +    2.1. The Initial Developer Grant.
        +
        +    Conditioned upon Your compliance with Section 3.1 below and
        +    subject to third party intellectual property claims, the Initial
        +    Developer hereby grants You a world-wide, royalty-free,
        +    non-exclusive license:
        +
        +        (a) under intellectual property rights (other than patent or
        +            trademark) Licensable by Initial Developer, to use,
        +            reproduce, modify, display, perform, sublicense and
        +            distribute the Original Software (or portions thereof),
        +            with or without Modifications, and/or as part of a Larger
        +            Work; and
        +
        +        (b) under Patent Claims infringed by the making, using or
        +            selling of Original Software, to make, have made, use,
        +            practice, sell, and offer for sale, and/or otherwise
        +            dispose of the Original Software (or portions thereof).
        +
        +        (c) The licenses granted in Sections 2.1(a) and (b) are
        +            effective on the date Initial Developer first distributes
        +            or otherwise makes the Original Software available to a
        +            third party under the terms of this License.
        +
        +        (d) Notwithstanding Section 2.1(b) above, no patent license is
        +            granted: (1) for code that You delete from the Original
        +            Software, or (2) for infringements caused by: (i) the
        +            modification of the Original Software, or (ii) the
        +            combination of the Original Software with other software
        +            or devices.
        +
        +    2.2. Contributor Grant.
        +
        +    Conditioned upon Your compliance with Section 3.1 below and
        +    subject to third party intellectual property claims, each
        +    Contributor hereby grants You a world-wide, royalty-free,
        +    non-exclusive license:
        +
        +        (a) under intellectual property rights (other than patent or
        +            trademark) Licensable by Contributor to use, reproduce,
        +            modify, display, perform, sublicense and distribute the
        +            Modifications created by such Contributor (or portions
        +            thereof), either on an unmodified basis, with other
        +            Modifications, as Covered Software and/or as part of a
        +            Larger Work; and
        +
        +        (b) under Patent Claims infringed by the making, using, or
        +            selling of Modifications made by that Contributor either
        +            alone and/or in combination with its Contributor Version
        +            (or portions of such combination), to make, use, sell,
        +            offer for sale, have made, and/or otherwise dispose of:
        +            (1) Modifications made by that Contributor (or portions
        +            thereof); and (2) the combination of Modifications made by
        +            that Contributor with its Contributor Version (or portions
        +            of such combination).
        +
        +        (c) The licenses granted in Sections 2.2(a) and 2.2(b) are
        +            effective on the date Contributor first distributes or
        +            otherwise makes the Modifications available to a third
        +            party.
        +
        +        (d) Notwithstanding Section 2.2(b) above, no patent license is
        +            granted: (1) for any code that Contributor has deleted
        +            from the Contributor Version; (2) for infringements caused
        +            by: (i) third party modifications of Contributor Version,
        +            or (ii) the combination of Modifications made by that
        +            Contributor with other software (except as part of the
        +            Contributor Version) or other devices; or (3) under Patent
        +            Claims infringed by Covered Software in the absence of
        +            Modifications made by that Contributor.
        +
        +3. Distribution Obligations.
        +
        +    3.1. Availability of Source Code.
        +
        +    Any Covered Software that You distribute or otherwise make
        +    available in Executable form must also be made available in Source
        +    Code form and that Source Code form must be distributed only under
        +    the terms of this License.  You must include a copy of this
        +    License with every copy of the Source Code form of the Covered
        +    Software You distribute or otherwise make available.  You must
        +    inform recipients of any such Covered Software in Executable form
        +    as to how they can obtain such Covered Software in Source Code
        +    form in a reasonable manner on or through a medium customarily
        +    used for software exchange.
        +
        +    3.2. Modifications.
        +
        +    The Modifications that You create or to which You contribute are
        +    governed by the terms of this License.  You represent that You
        +    believe Your Modifications are Your original creation(s) and/or
        +    You have sufficient rights to grant the rights conveyed by this
        +    License.
        +
        +    3.3. Required Notices.
        +
        +    You must include a notice in each of Your Modifications that
        +    identifies You as the Contributor of the Modification.  You may
        +    not remove or alter any copyright, patent or trademark notices
        +    contained within the Covered Software, or any notices of licensing
        +    or any descriptive text giving attribution to any Contributor or
        +    the Initial Developer.
        +
        +    3.4. Application of Additional Terms.
        +
        +    You may not offer or impose any terms on any Covered Software in
        +    Source Code form that alters or restricts the applicable version
        +    of this License or the recipients' rights hereunder.  You may
        +    choose to offer, and to charge a fee for, warranty, support,
        +    indemnity or liability obligations to one or more recipients of
        +    Covered Software.  However, you may do so only on Your own behalf,
        +    and not on behalf of the Initial Developer or any Contributor.
        +    You must make it absolutely clear that any such warranty, support,
        +    indemnity or liability obligation is offered by You alone, and You
        +    hereby agree to indemnify the Initial Developer and every
        +    Contributor for any liability incurred by the Initial Developer or
        +    such Contributor as a result of warranty, support, indemnity or
        +    liability terms You offer.
        +
        +    3.5. Distribution of Executable Versions.
        +
        +    You may distribute the Executable form of the Covered Software
        +    under the terms of this License or under the terms of a license of
        +    Your choice, which may contain terms different from this License,
        +    provided that You are in compliance with the terms of this License
        +    and that the license for the Executable form does not attempt to
        +    limit or alter the recipient's rights in the Source Code form from
        +    the rights set forth in this License.  If You distribute the
        +    Covered Software in Executable form under a different license, You
        +    must make it absolutely clear that any terms which differ from
        +    this License are offered by You alone, not by the Initial
        +    Developer or Contributor.  You hereby agree to indemnify the
        +    Initial Developer and every Contributor for any liability incurred
        +    by the Initial Developer or such Contributor as a result of any
        +    such terms You offer.
        +
        +    3.6. Larger Works.
        +
        +    You may create a Larger Work by combining Covered Software with
        +    other code not governed by the terms of this License and
        +    distribute the Larger Work as a single product.  In such a case,
        +    You must make sure the requirements of this License are fulfilled
        +    for the Covered Software.
        +
        +4. Versions of the License.
        +
        +    4.1. New Versions.
        +
        +    Sun Microsystems, Inc. is the initial license steward and may
        +    publish revised and/or new versions of this License from time to
        +    time.  Each version will be given a distinguishing version number.
        +    Except as provided in Section 4.3, no one other than the license
        +    steward has the right to modify this License.
        +
        +    4.2. Effect of New Versions.
        +
        +    You may always continue to use, distribute or otherwise make the
        +    Covered Software available under the terms of the version of the
        +    License under which You originally received the Covered Software.
        +    If the Initial Developer includes a notice in the Original
        +    Software prohibiting it from being distributed or otherwise made
        +    available under any subsequent version of the License, You must
        +    distribute and make the Covered Software available under the terms
        +    of the version of the License under which You originally received
        +    the Covered Software.  Otherwise, You may also choose to use,
        +    distribute or otherwise make the Covered Software available under
        +    the terms of any subsequent version of the License published by
        +    the license steward.
        +
        +    4.3. Modified Versions.
        +
        +    When You are an Initial Developer and You want to create a new
        +    license for Your Original Software, You may create and use a
        +    modified version of this License if You: (a) rename the license
        +    and remove any references to the name of the license steward
        +    (except to note that the license differs from this License); and
        +    (b) otherwise make it clear that the license contains terms which
        +    differ from this License.
        +
        +5. DISCLAIMER OF WARRANTY.
        +
        +    COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS"
        +    BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
        +    INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED
        +    SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR
        +    PURPOSE OR NON-INFRINGING.  THE ENTIRE RISK AS TO THE QUALITY AND
        +    PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU.  SHOULD ANY
        +    COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
        +    INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
        +    NECESSARY SERVICING, REPAIR OR CORRECTION.  THIS DISCLAIMER OF
        +    WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.  NO USE OF
        +    ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS
        +    DISCLAIMER.
        +
        +6. TERMINATION.
        +
        +    6.1. This License and the rights granted hereunder will terminate
        +    automatically if You fail to comply with terms herein and fail to
        +    cure such breach within 30 days of becoming aware of the breach.
        +    Provisions which, by their nature, must remain in effect beyond
        +    the termination of this License shall survive.
        +
        +    6.2. If You assert a patent infringement claim (excluding
        +    declaratory judgment actions) against Initial Developer or a
        +    Contributor (the Initial Developer or Contributor against whom You
        +    assert such claim is referred to as "Participant") alleging that
        +    the Participant Software (meaning the Contributor Version where
        +    the Participant is a Contributor or the Original Software where
        +    the Participant is the Initial Developer) directly or indirectly
        +    infringes any patent, then any and all rights granted directly or
        +    indirectly to You by such Participant, the Initial Developer (if
        +    the Initial Developer is not the Participant) and all Contributors
        +    under Sections 2.1 and/or 2.2 of this License shall, upon 60 days
        +    notice from Participant terminate prospectively and automatically
        +    at the expiration of such 60 day notice period, unless if within
        +    such 60 day period You withdraw Your claim with respect to the
        +    Participant Software against such Participant either unilaterally
        +    or pursuant to a written agreement with Participant.
        +
        +    6.3. In the event of termination under Sections 6.1 or 6.2 above,
        +    all end user licenses that have been validly granted by You or any
        +    distributor hereunder prior to termination (excluding licenses
        +    granted to You by any distributor) shall survive termination.
        +
        +7. LIMITATION OF LIABILITY.
        +
        +    UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
        +    (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE
        +    INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF
        +    COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE
        +    LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
        +    CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT
        +    LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK
        +    STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
        +    COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
        +    INFORMED OF THE POSSIBILITY OF SUCH DAMAGES.  THIS LIMITATION OF
        +    LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL
        +    INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT
        +    APPLICABLE LAW PROHIBITS SUCH LIMITATION.  SOME JURISDICTIONS DO
        +    NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR
        +    CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT
        +    APPLY TO YOU.
        +
        +8. U.S. GOVERNMENT END USERS.
        +
        +    The Covered Software is a "commercial item," as that term is
        +    defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial
        +    computer software" (as that term is defined at 48
        +    C.F.R. 252.227-7014(a)(1)) and "commercial computer software
        +    documentation" as such terms are used in 48 C.F.R. 12.212
        +    (Sept. 1995).  Consistent with 48 C.F.R. 12.212 and 48
        +    C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all
        +    U.S. Government End Users acquire Covered Software with only those
        +    rights set forth herein.  This U.S. Government Rights clause is in
        +    lieu of, and supersedes, any other FAR, DFAR, or other clause or
        +    provision that addresses Government rights in computer software
        +    under this License.
        +
        +9. MISCELLANEOUS.
        +
        +    This License represents the complete agreement concerning subject
        +    matter hereof.  If any provision of this License is held to be
        +    unenforceable, such provision shall be reformed only to the extent
        +    necessary to make it enforceable.  This License shall be governed
        +    by the law of the jurisdiction specified in a notice contained
        +    within the Original Software (except to the extent applicable law,
        +    if any, provides otherwise), excluding such jurisdiction's
        +    conflict-of-law provisions.  Any litigation relating to this
        +    License shall be subject to the jurisdiction of the courts located
        +    in the jurisdiction and venue specified in a notice contained
        +    within the Original Software, with the losing party responsible
        +    for costs, including, without limitation, court costs and
        +    reasonable attorneys' fees and expenses.  The application of the
        +    United Nations Convention on Contracts for the International Sale
        +    of Goods is expressly excluded.  Any law or regulation which
        +    provides that the language of a contract shall be construed
        +    against the drafter shall not apply to this License.  You agree
        +    that You alone are responsible for compliance with the United
        +    States export administration regulations (and the export control
        +    laws and regulation of any other countries) when You use,
        +    distribute or otherwise make available any Covered Software.
        +
        +10. RESPONSIBILITY FOR CLAIMS.
        +
        +    As between Initial Developer and the Contributors, each party is
        +    responsible for claims and damages arising, directly or
        +    indirectly, out of its utilization of rights under this License
        +    and You agree to work with Initial Developer and Contributors to
        +    distribute such responsibility on an equitable basis.  Nothing
        +    herein is intended or shall be deemed to constitute any admission
        +    of liability.
        +
        +--------------------------------------------------------------------
        +
        +NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND
        +DISTRIBUTION LICENSE (CDDL)
        +
        +For Covered Software in this distribution, this License shall
        +be governed by the laws of the State of California (excluding
        +conflict-of-law provisions).
        +
        +Any litigation relating to this License shall be subject to the
        +jurisdiction of the Federal Courts of the Northern District of
        +California and the state courts of the State of California, with
        +venue lying in Santa Clara County, California.
         
      • Community Data License Agreement Permissive 2.0

        Used by:

        # Community Data License Agreement - Permissive - Version 2.0
         
        @@ -11472,9 +14832,9 @@ insights.
                         

        ISC License

        Used by:

        -
        /* Copyright (c) 2018, Google Inc.
        +                
        /* Copyright (c) 2014, Intel Corporation.
          *
          * Permission to use, copy, modify, and/or distribute this software for any
          * purpose with or without fee is hereby granted, provided that the above
        @@ -11488,15 +14848,65 @@ insights.
          * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
         
        -#include <openssl/crypto.h>
        +#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H
        +#define OPENSSL_HEADER_EC_ECP_NISTZ384_H
         
        -#include <gtest/gtest.h>
        +#include "../../limbs/limbs.h"
        +
        +#define P384_LIMBS (384u / LIMB_BITS)
        +
        +typedef struct {
        +  Limb X[P384_LIMBS];
        +  Limb Y[P384_LIMBS];
        +  Limb Z[P384_LIMBS];
        +} P384_POINT;
        +
        +typedef struct {
        +  Limb X[P384_LIMBS];
        +  Limb Y[P384_LIMBS];
        +} P384_POINT_AFFINE;
         
         
        -TEST(SelfTests, KAT) {
        -#if !defined(_MSC_VER)
        -  EXPECT_TRUE(BORINGSSL_self_test());
        -#endif
        +#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2015-2016 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! EdDSA Signatures.
        +
        +use super::ops::ELEM_LEN;
        +use crate::digest;
        +
        +pub mod signing;
        +pub mod verification;
        +
        +/// The length of an Ed25519 public key.
        +pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN;
        +
        +pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest {
        +    let mut ctx = digest::Context::new(&digest::SHA512);
        +    ctx.update(signature_r);
        +    ctx.update(public_key);
        +    ctx.update(msg);
        +    ctx.finish()
         }
         
      • @@ -11526,29 +14936,44 @@ TEST(SelfTests, KAT) {

        ISC License

        Used by:

        -
        // Copyright 2021 Brian Smith.
        +                
        // Copyright 2015-2022 Brian Smith.
         //
         // Permission to use, copy, modify, and/or distribute this software for any
         // purpose with or without fee is hereby granted, provided that the above
         // copyright notice and this permission notice appear in all copies.
         //
        -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
         // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
        -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
        -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
        -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
         
        -#[test]
        -fn cert_without_extensions_test() {
        -    // Check the certificate is valid with
        -    // `openssl x509 -in cert_without_extensions.der -inform DER -text -noout`
        -    const CERT_WITHOUT_EXTENSIONS_DER: &[u8] = include_bytes!("cert_without_extensions.der");
        +use crate::limb::Limb;
         
        -    assert!(webpki::EndEntityCert::try_from(CERT_WITHOUT_EXTENSIONS_DER).is_ok());
        +#[derive(Clone, Copy)]
        +#[repr(transparent)]
        +pub struct N0([Limb; 2]);
        +
        +impl N0 {
        +    #[cfg(feature = "alloc")]
        +    pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS;
        +
        +    #[inline]
        +    pub const fn precalculated(n0: u64) -> Self {
        +        #[cfg(target_pointer_width = "64")]
        +        {
        +            Self([n0, 0])
        +        }
        +
        +        #[cfg(target_pointer_width = "32")]
        +        {
        +            Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb])
        +        }
        +    }
         }
         
        @@ -11556,21 +14981,372 @@ fn cert_without_extensions_test() {

        ISC License

        Used by:

        -
        Copyright (c) 2017 Adam Wick
        +                
        // Copyright 2015-2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
         
        -Permission to use, copy, modify, and/or distribute this software for any purpose
        -with or without fee is hereby granted, provided that the above copyright notice
        -and this permission notice appear in all copies.
        +use crate::{bb, error};
         
        -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
        -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
        -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
        -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
        -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
        -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
        -THIS SOFTWARE.
        +#[deprecated(
        +    note = "To be removed. Internal function not intended for external use with no promises regarding side channels."
        +)]
        +pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
        +    bb::verify_slices_are_equal(a, b)
        +}
        +
        + +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2016 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! Elliptic curve operations and schemes using Curve25519.
        +
        +pub mod ed25519;
        +
        +pub mod x25519;
        +
        +mod ops;
        +mod scalar;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2016-2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +use crate::error::{KeyRejected, Unspecified};
        +
        +impl From<untrusted::EndOfInput> for Unspecified {
        +    fn from(source: untrusted::EndOfInput) -> Self {
        +        super::erase(source)
        +    }
        +}
        +
        +impl From<core::array::TryFromSliceError> for Unspecified {
        +    fn from(source: core::array::TryFromSliceError) -> Self {
        +        super::erase(source)
        +    }
        +}
        +
        +impl From<KeyRejected> for Unspecified {
        +    fn from(source: KeyRejected) -> Self {
        +        super::erase(source)
        +    }
        +}
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2018 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! Serialization and deserialization.
        +
        +#[doc(hidden)]
        +pub mod der;
        +
        +#[cfg(feature = "alloc")]
        +mod writer;
        +
        +#[cfg(feature = "alloc")]
        +pub(crate) mod der_writer;
        +
        +pub(crate) mod positive;
        +
        +pub use self::positive::Positive;
        +
        +#[cfg(feature = "alloc")]
        +pub(crate) use self::writer::TooLongError;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2019-2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +use super::BlockLen;
        +
        +pub(super) use self::{
        +    sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN},
        +    sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN},
        +};
        +
        +pub(super) const CHAINING_WORDS: usize = 8;
        +
        +#[cfg(any(
        +    all(target_arch = "aarch64", target_endian = "little"),
        +    all(target_arch = "arm", target_endian = "little"),
        +    target_arch = "x86_64"
        +))]
        +#[macro_use]
        +mod ffi;
        +
        +pub(super) mod fallback;
        +mod sha2_32;
        +mod sha2_64;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`.
        +#[allow(dead_code)]
        +#[inline(always)]
        +pub fn from_mut<T: ?Sized>(r: &mut T) -> *mut T {
        +    r
        +}
        +
        +// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`.
        +#[allow(dead_code)]
        +#[inline(always)]
        +pub const fn from_ref<T: ?Sized>(r: &T) -> *const T {
        +    r
        +}
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! Integration tests for non-public APIs.
        +
        +mod bits_tests;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +pub use self::{
        +    array::Array,
        +    base::{IndexError, Overlapping},
        +    partial_block::PartialBlock,
        +};
        +
        +mod array;
        +mod base;
        +mod partial_block;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +#![cfg(all(target_arch = "aarch64", target_endian = "little"))]
        +
        +pub(in super::super) mod mont;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +#![cfg(target_arch = "x86_64")]
        +
        +pub(in super::super::super) mod mont;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +mod storage;
        +
        +pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK};
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +pub(super) mod aarch64;
        +pub(super) mod x86_64;
         
      • @@ -11598,7 +15374,7 @@ CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

        ISC License

        Used by:

        Copyright © 2015, Simonas Kazlauskas
         
        @@ -11618,7 +15394,7 @@ THIS SOFTWARE.
                         

        ISC License

        Used by:

        Except as otherwise noted, this project is licensed under the following
         (ISC-style) terms:
        @@ -11645,12 +15421,12 @@ third-party/chromium/LICENSE.
                         

        ISC License

        Used by:

        ISC License
         
         Copyright (c) 2016, Mapbox
        -Copyright (c) 2018, Tree Cricket
        +Copyright (c) 2023, Taku Fukada
         
         Permission to use, copy, modify, and/or distribute this software for any purpose
         with or without fee is hereby granted, provided that the above copyright notice
        @@ -11669,7 +15445,8 @@ THIS SOFTWARE.
                         

        ISC License

        Used by:

        ISC License:
         
        @@ -11685,7 +15462,580 @@ THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
                         

        MIT License

        Used by:

        +
                                          MIT License
        +
        +Copyright 2024 Antoine Catton
        +Copyright 2016-2024 David Tolnay
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy of
        +this software and associated documentation files (the “Software”), to deal in
        +the Software without restriction, including without limitation the rights to
        +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
        +of the Software, and to permit persons to whom the Software is furnished to do
        +so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        # 3rd Party Notices
        +
        +The `cfg_aliases!` macro uses a lot of the code from [`tectonic_cfg_support::target_cfg!`] macro which is under the following license:
        +
        +[`tectonic_cfg_support::target_cfg!`]: https://github.com/tectonic-typesetting/tectonic/blob/f2439b936470ad27bdf92882064bc4702ee01899/cfg_support/src/lib.rs#L166
        +
        +    tectonic_cfg_support is licensed under the MIT License.
        +
        +    Permission is hereby granted, free of charge, to any person obtaining a copy
        +    of this software and associated documentation files (the “Software”), to deal
        +    in the Software without restriction, including without limitation the rights
        +    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +    copies of the Software, and to permit persons to whom the Software is
        +    furnished to do so, subject to the following conditions:
        +
        +    The above copyright notice and this permission notice shall be included in all
        +    copies or substantial portions of the Software.
        +
        +    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +    SOFTWARE.
        +---
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * Permission is hereby granted, free of charge, to any person obtaining a copy
        + * of this software and associated documentation files (the "Software"), to
        + * deal in the Software without restriction, including without limitation the
        + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
        + * sell copies of the Software, and to permit persons to whom the Software is
        + * furnished to do so, subject to the following conditions:
        + *
        + * The above copyright notice and this permission notice shall be included in
        + * all copies or substantial portions of the Software.
        + *
        + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
        + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
        + * IN THE SOFTWARE.
        + *
        + */
        +
        +//! Codegen exports used by `tonic-build`.
        +
        +pub use async_trait::async_trait;
        +pub use tokio_stream;
        +
        +pub use std::future::Future;
        +pub use std::pin::Pin;
        +pub use std::sync::Arc;
        +pub use std::task::{Context, Poll};
        +pub use tower_service::Service;
        +pub type StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
        +pub use crate::codec::{CompressionEncoding, EnabledCompressionEncodings};
        +pub use crate::extensions::GrpcMethod;
        +pub use crate::service::interceptor::InterceptedService;
        +pub use bytes::Bytes;
        +pub use http;
        +pub use http_body::Body;
        +
        +pub type BoxFuture<T, E> = self::Pin<Box<dyn self::Future<Output = Result<T, E>> + Send + 'static>>;
        +pub type BoxStream<T> =
        +    self::Pin<Box<dyn tokio_stream::Stream<Item = Result<T, crate::Status>> + Send + 'static>>;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * Permission is hereby granted, free of charge, to any person obtaining a copy
        + * of this software and associated documentation files (the "Software"), to
        + * deal in the Software without restriction, including without limitation the
        + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
        + * sell copies of the Software, and to permit persons to whom the Software is
        + * furnished to do so, subject to the following conditions:
        + *
        + * The above copyright notice and this permission notice shall be included in
        + * all copies or substantial portions of the Software.
        + *
        + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
        + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
        + * IN THE SOFTWARE.
        + *
        + */
        +
        +//! Utilities for using Tower services with Tonic.
        +
        +pub mod interceptor;
        +pub(crate) mod layered;
        +#[cfg(feature = "router")]
        +pub(crate) mod router;
        +
        +#[doc(inline)]
        +pub use self::interceptor::{Interceptor, InterceptorLayer};
        +pub use self::layered::{LayerExt, Layered};
        +#[doc(inline)]
        +#[cfg(feature = "router")]
        +pub use self::router::{Routes, RoutesBuilder};
        +#[cfg(feature = "router")]
        +pub use axum::{Router as AxumRouter, body::Body as AxumBody};
        +
        +pub mod recover_error;
        +pub use self::recover_error::{RecoverError, RecoverErrorLayer};
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * Permission is hereby granted, free of charge, to any person obtaining a copy
        + * of this software and associated documentation files (the "Software"), to
        + * deal in the Software without restriction, including without limitation the
        + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
        + * sell copies of the Software, and to permit persons to whom the Software is
        + * furnished to do so, subject to the following conditions:
        + *
        + * The above copyright notice and this permission notice shall be included in
        + * all copies or substantial portions of the Software.
        + *
        + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
        + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
        + * IN THE SOFTWARE.
        + *
        + */
        +
        +//! Various utilities used throughout tonic.
        +
        +// some combinations of features might cause things here not to be used
        +#![allow(dead_code)]
        +
        +pub(crate) mod base64 {
        +    use base64::{
        +        alphabet,
        +        engine::{
        +            DecodePaddingMode,
        +            general_purpose::{GeneralPurpose, GeneralPurposeConfig},
        +        },
        +    };
        +
        +    pub(crate) const STANDARD: GeneralPurpose = GeneralPurpose::new(
        +        &alphabet::STANDARD,
        +        GeneralPurposeConfig::new()
        +            .with_encode_padding(true)
        +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
        +    );
        +
        +    pub(crate) const STANDARD_NO_PAD: GeneralPurpose = GeneralPurpose::new(
        +        &alphabet::STANDARD,
        +        GeneralPurposeConfig::new()
        +            .with_encode_padding(false)
        +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
        +    );
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * Permission is hereby granted, free of charge, to any person obtaining a copy
        + * of this software and associated documentation files (the "Software"), to
        + * deal in the Software without restriction, including without limitation the
        + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
        + * sell copies of the Software, and to permit persons to whom the Software is
        + * furnished to do so, subject to the following conditions:
        + *
        + * The above copyright notice and this permission notice shall be included in
        + * all copies or substantial portions of the Software.
        + *
        + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
        + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
        + * IN THE SOFTWARE.
        + *
        + */
        +
        +/// A gRPC Method info extension.
        +#[derive(Debug, Clone)]
        +pub struct GrpcMethod<'a> {
        +    service: &'a str,
        +    method: &'a str,
        +}
        +
        +impl<'a> GrpcMethod<'a> {
        +    /// Create a new `GrpcMethod` extension.
        +    #[doc(hidden)]
        +    pub fn new(service: &'a str, method: &'a str) -> Self {
        +        Self { service, method }
        +    }
        +
        +    /// gRPC service name
        +    pub fn service(&self) -> &str {
        +        self.service
        +    }
        +    /// gRPC method name
        +    pub fn method(&self) -> &str {
        +        self.method
        +    }
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * Permission is hereby granted, free of charge, to any person obtaining a copy
        + * of this software and associated documentation files (the "Software"), to
        + * deal in the Software without restriction, including without limitation the
        + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
        + * sell copies of the Software, and to permit persons to whom the Software is
        + * furnished to do so, subject to the following conditions:
        + *
        + * The above copyright notice and this permission notice shall be included in
        + * all copies or substantial portions of the Software.
        + *
        + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
        + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
        + * IN THE SOFTWARE.
        + *
        + */
        +
        +mod add_origin;
        +use self::add_origin::AddOrigin;
        +
        +mod user_agent;
        +use self::user_agent::UserAgent;
        +
        +mod reconnect;
        +use self::reconnect::Reconnect;
        +
        +mod connection;
        +pub(super) use self::connection::Connection;
        +
        +mod discover;
        +pub use self::discover::Change;
        +pub(super) use self::discover::DynamicServiceStream;
        +
        +mod io;
        +use self::io::BoxedIo;
        +
        +mod connector;
        +pub(crate) use self::connector::Connector;
        +
        +mod executor;
        +pub(super) use self::executor::{Executor, SharedExec};
        +
        +#[cfg(feature = "_tls-any")]
        +mod tls;
        +#[cfg(feature = "_tls-any")]
        +pub(super) use self::tls::TlsConnector;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * Permission is hereby granted, free of charge, to any person obtaining a copy
        + * of this software and associated documentation files (the "Software"), to
        + * deal in the Software without restriction, including without limitation the
        + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
        + * sell copies of the Software, and to permit persons to whom the Software is
        + * furnished to do so, subject to the following conditions:
        + *
        + * The above copyright notice and this permission notice shall be included in
        + * all copies or substantial portions of the Software.
        + *
        + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
        + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
        + * IN THE SOFTWARE.
        + *
        + */
        +
        +mod io;
        +pub(crate) use self::io::{ConnectInfoLayer, ServerIo};
        +
        +#[cfg(feature = "_tls-any")]
        +mod tls;
        +#[cfg(feature = "_tls-any")]
        +pub(crate) use self::tls::TlsAcceptor;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * Permission is hereby granted, free of charge, to any person obtaining a copy
        + * of this software and associated documentation files (the "Software"), to
        + * deal in the Software without restriction, including without limitation the
        + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
        + * sell copies of the Software, and to permit persons to whom the Software is
        + * furnished to do so, subject to the following conditions:
        + *
        + * The above copyright notice and this permission notice shall be included in
        + * all copies or substantial portions of the Software.
        + *
        + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
        + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
        + * IN THE SOFTWARE.
        + *
        + */
        +
        +pub(crate) mod grpc_timeout;
        +#[cfg(feature = "_tls-any")]
        +pub(crate) mod tls;
        +
        +pub(crate) use self::grpc_timeout::GrpcTimeout;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * Permission is hereby granted, free of charge, to any person obtaining a copy
        + * of this software and associated documentation files (the "Software"), to
        + * deal in the Software without restriction, including without limitation the
        + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
        + * sell copies of the Software, and to permit persons to whom the Software is
        + * furnished to do so, subject to the following conditions:
        + *
        + * The above copyright notice and this permission notice shall be included in
        + * all copies or substantial portions of the Software.
        + *
        + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
        + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
        + * IN THE SOFTWARE.
        + *
        + */
        +
        +use crate::transport::channel::BoxFuture;
        +use hyper_util::rt::TokioExecutor;
        +use std::{future::Future, sync::Arc};
        +
        +pub(crate) use hyper::rt::Executor;
        +
        +#[derive(Clone)]
        +pub(crate) struct SharedExec {
        +    inner: Arc<dyn Executor<BoxFuture<'static, ()>> + Send + Sync + 'static>,
        +}
        +
        +impl SharedExec {
        +    pub(crate) fn new<E>(exec: E) -> Self
        +    where
        +        E: Executor<BoxFuture<'static, ()>> + Send + Sync + 'static,
        +    {
        +        Self {
        +            inner: Arc::new(exec),
        +        }
        +    }
        +
        +    pub(crate) fn tokio() -> Self {
        +        Self::new(TokioExecutor::new())
        +    }
        +}
        +
        +impl<F> Executor<F> for SharedExec
        +where
        +    F: Future<Output = ()> + Send + 'static,
        +{
        +    fn execute(&self, fut: F) {
        +        self.inner.execute(Box::pin(fut))
        +    }
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * Permission is hereby granted, free of charge, to any person obtaining a copy
        + * of this software and associated documentation files (the "Software"), to
        + * deal in the Software without restriction, including without limitation the
        + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
        + * sell copies of the Software, and to permit persons to whom the Software is
        + * furnished to do so, subject to the following conditions:
        + *
        + * The above copyright notice and this permission notice shall be included in
        + * all copies or substantial portions of the Software.
        + *
        + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
        + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
        + * IN THE SOFTWARE.
        + *
        + */
        +
        +use super::Connected;
        +use std::sync::Arc;
        +
        +/// Connection info for Unix domain socket streams.
        +///
        +/// This type will be accessible through [request extensions][ext] if you're using
        +/// a unix stream.
        +///
        +/// See [Connected] for more details.
        +///
        +/// [ext]: crate::Request::extensions
        +#[derive(Clone, Debug)]
        +pub struct UdsConnectInfo {
        +    /// Peer address. This will be "unnamed" for client unix sockets.
        +    pub peer_addr: Option<Arc<tokio::net::unix::SocketAddr>>,
        +    /// Process credentials for the unix socket.
        +    pub peer_cred: Option<tokio::net::unix::UCred>,
        +}
        +
        +impl Connected for tokio::net::UnixStream {
        +    type ConnectInfo = UdsConnectInfo;
        +
        +    fn connect_info(&self) -> Self::ConnectInfo {
        +        UdsConnectInfo {
        +            peer_addr: self.peer_addr().ok().map(Arc::new),
        +            peer_cred: self.peer_cred().ok(),
        +        }
        +    }
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        // Copyright (c) 2019 Nuclear Furnace
        +//
        +// Permission is hereby granted, free of charge, to any person obtaining a copy
        +// of this software and associated documentation files (the "Software"), to deal
        +// in the Software without restriction, including without limitation the rights
        +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +// copies of the Software, and to permit persons to whom the Software is
        +// furnished to do so, subject to the following conditions:
        +//
        +// The above copyright notice and this permission notice shall be included in all
        +// copies or substantial portions of the Software.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +// SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
         
        @@ -11712,7 +16062,7 @@ THE SOFTWARE.
                         

        MIT License

        Used by:

        Copyright (c) 2014 Carl Lerche and other MIO contributors
         
        @@ -11739,7 +16089,6 @@ THE SOFTWARE.
                         

        MIT License

        Used by:

        Copyright (c) 2014-2019 Geoffroy Couprie
        @@ -11768,9 +16117,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2014-2021 Sean McArthur
        +                
        Copyright (c) 2014-2026 Sean McArthur
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -11795,34 +16144,8 @@ THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2014-2025 Sean McArthur
        -
        -Permission is hereby granted, free of charge, to any person obtaining a copy
        -of this software and associated documentation files (the "Software"), to deal
        -in the Software without restriction, including without limitation the rights
        -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        -copies of the Software, and to permit persons to whom the Software is
        -furnished to do so, subject to the following conditions:
        -
        -The above copyright notice and this permission notice shall be included in
        -all copies or substantial portions of the Software.
        -
        -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        -THE SOFTWARE.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2015 Jonathan Reem
         
        @@ -11855,34 +16178,7 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2015 fangyuanziti
        -
        -Permission is hereby granted, free of charge, to any person obtaining a copy
        -of this software and associated documentation files (the "Software"), to deal
        -in the Software without restriction, including without limitation the rights
        -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        -copies of the Software, and to permit persons to whom the Software is
        -furnished to do so, subject to the following conditions:
        -
        -The above copyright notice and this permission notice shall be included in
        -all copies or substantial portions of the Software.
        -
        -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        -THE SOFTWARE.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2015 steffengy
         
        @@ -11897,16 +16193,27 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES
                         

        MIT License

        Used by:

        -
        Copyright (c) 2016 Paul Masurel
        +                
        Copyright (c) 2017 Gilad Naaman
         
        -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
         
        -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
         
        -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        -
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.
      • MIT License

        @@ -11942,8 +16249,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

        MIT License

        Used by:

        Copyright (c) 2017 h2 authors
         
        @@ -11976,7 +16282,7 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        Copyright (c) 2018 Carl Lerche
         
        @@ -12009,52 +16315,34 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2018 Paul Masurel
        +                
        Copyright (c) 2018 Tom Parker-Shemilt
         
        -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
         
        -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
         
        -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        -
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.
      • MIT License

        Used by:

        -
        Copyright (c) 2018 by Quickwit, Inc. 
        -
        -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        -
        -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        -
        -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        - -
        Copyright (c) 2018 by the project authors, as listed in the AUTHORS file. 
        -
        -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        -
        -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        -
        -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2018-2019 Sean McArthur
         
        @@ -12145,7 +16433,7 @@ DEALINGS IN THE SOFTWARE.
                         

        Used by:

        Copyright (c) 2019 Carl Lerche
         
        @@ -12232,44 +16520,13 @@ SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2019 Hyper Contributors
        -
        -Permission is hereby granted, free of charge, to any
        -person obtaining a copy of this software and associated
        -documentation files (the "Software"), to deal in the
        -Software without restriction, including without
        -limitation the rights to use, copy, modify, merge,
        -publish, distribute, sublicense, and/or sell copies of
        -the Software, and to permit persons to whom the Software
        -is furnished to do so, subject to the following
        -conditions:
        -
        -The above copyright notice and this permission notice
        -shall be included in all copies or substantial portions
        -of the Software.
        -
        -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
        -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
        -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
        -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
        -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
        -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
        -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
        -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
        -DEALINGS IN THE SOFTWARE.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2019 Tokio Contributors
         
        @@ -12304,7 +16561,7 @@ DEALINGS IN THE SOFTWARE.
                         
                         
        Copyright (c) 2019 Tower Contributors
         
        @@ -12337,10 +16594,9 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2019-2021 Tower Contributors
        +                
        Copyright (c) 2019 axum Contributors
         
         Permission is hereby granted, free of charge, to any
         person obtaining a copy of this software and associated
        @@ -12371,9 +16627,10 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2019-2024 Sean McArthur & Hyper Contributors
        +                
        Copyright (c) 2019-2021 Tower Contributors
         
         Permission is hereby granted, free of charge, to any
         person obtaining a copy of this software and associated
        @@ -12437,7 +16694,68 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        +
        Copyright (c) 2019-2026 Sean McArthur & Hyper Contributors
        +
        +Permission is hereby granted, free of charge, to any
        +person obtaining a copy of this software and associated
        +documentation files (the "Software"), to deal in the
        +Software without restriction, including without
        +limitation the rights to use, copy, modify, merge,
        +publish, distribute, sublicense, and/or sell copies of
        +the Software, and to permit persons to whom the Software
        +is furnished to do so, subject to the following
        +conditions:
        +
        +The above copyright notice and this permission notice
        +shall be included in all copies or substantial portions
        +of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
        +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
        +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
        +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
        +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
        +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
        +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
        +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
        +DEALINGS IN THE SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright (c) 2021 Metrics Contributors
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        Copyright (c) 2023-2025 Sean McArthur
         
        @@ -12458,36 +16776,6 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
         LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
         THE SOFTWARE.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        - -
        Copyright (c) 2024 by Quickwit Inc.
        -
        -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        -
        -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        -
        -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        - -
        Copyright (c) 2024-Present Paul Masurel
        -
        -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        -
        -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        -
        -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
         
      • @@ -12495,6 +16783,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

        Used by:

        Copyright 2016 Nika Layzell
         
        @@ -12502,6 +16791,48 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
         
         The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
         
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2019 gRPC authors.
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in
        +all copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        +THE SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2020 David Koloski
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        +
         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
         
      • @@ -12524,25 +16855,73 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

        MIT License

        Used by:

        -
        Includes portions of humantime
        -Copyright (c) 2016 The humantime Developers
        +                
        Copyright 2021 David Koloski
         
         Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
         
         The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
         
         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        -
        -
         
      • MIT License

        Used by:

        +
        Copyright 2023 David Koloski
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2023 David Koloski
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2024 David Koloski
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12565,6 +16944,65 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
         LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
         SOFTWARE.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2016 Michael Ma
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2016 fengcen
        +Copyright (c) 2019 svartalf
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
      • MIT License

        @@ -12687,9 +17125,41 @@ SOFTWARE.

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2017 Sam Rijs
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12748,7 +17218,36 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2018 sgodwincs
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12777,7 +17276,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -12806,36 +17305,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        -
        MIT License
        -
        -Copyright (c) 2019 Aeledfyr
        -
        -Permission is hereby granted, free of charge, to any person obtaining a copy
        -of this software and associated documentation files (the "Software"), to deal
        -in the Software without restriction, including without limitation the rights
        -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        -copies of the Software, and to permit persons to whom the Software is
        -furnished to do so, subject to the following conditions:
        -
        -The above copyright notice and this permission notice shall be included in all
        -copies or substantial portions of the Software.
        -
        -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        -SOFTWARE.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        MIT License
         
        @@ -12864,8 +17334,37 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2019 Kornel
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12894,7 +17393,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -12948,6 +17447,40 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
         SOFTWARE.
         
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2019–2025 axum Contributors
        +
        +Permission is hereby granted, free of charge, to any
        +person obtaining a copy of this software and associated
        +documentation files (the "Software"), to deal in the
        +Software without restriction, including without
        +limitation the rights to use, copy, modify, merge,
        +publish, distribute, sublicense, and/or sell copies of
        +the Software, and to permit persons to whom the Software
        +is furnished to do so, subject to the following
        +conditions:
        +
        +The above copyright notice and this permission notice
        +shall be included in all copies or substantial portions
        +of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
        +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
        +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
        +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
        +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
        +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
        +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
        +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
        +DEALINGS IN THE SOFTWARE.
      • MIT License

        @@ -12982,11 +17515,30 @@ SOFTWARE.

        MIT License

        Used by:

        MIT License
         
        -Copyright (c) 2020 David Purdum
        +Copyright (c) 2020 Katharos Technology
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2020 Scripta Qumranica Electronica
        +
        +Created by Bronson Brown-deVost
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13011,13 +17563,11 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        -Copyright (c) 2020 Scripta Qumranica Electronica
        -
        -Created by Bronson Brown-deVost
        +Copyright (c) 2020 magiclen.org (Ron Li)
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13058,6 +17608,93 @@ furnished to do so, subject to the following conditions:
         The above copyright notice and this permission notice shall be included in all
         copies or substantial portions of the Software.
         
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2020-2022 Oliver Margetts
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2020-2026 Nugine
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2021 Adel Prokurov
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
         IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
         FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        @@ -13087,6 +17724,35 @@ furnished to do so, subject to the following conditions:
         The above copyright notice and this permission notice shall be included in all
         copies or substantial portions of the Software.
         
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2022 Arthur Silva
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
         IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
         FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        @@ -13101,6 +17767,7 @@ SOFTWARE.
                         

        Used by:

        MIT License
         
        @@ -13116,6 +17783,35 @@ furnished to do so, subject to the following conditions:
         The above copyright notice and this permission notice shall be included in all
         copies or substantial portions of the Software.
         
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2022 Jeroen Van Der Donckt
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
         IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
         FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        @@ -13157,7 +17853,36 @@ SOFTWARE.

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2022 sarah
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -13186,8 +17911,8 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -13216,8 +17941,66 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2023 sarah
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2024 Spire Team
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -13241,30 +18024,64 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
         SOFTWARE.
         
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2025 rutrum
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
      • MIT License

        Used by:

        MIT License
        @@ -13291,9 +18108,9 @@ USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -13322,7 +18139,99 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) [2021] [Marvin Countryman]
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Permission is hereby granted, free of charge, to any
        +person obtaining a copy of this software and associated
        +documentation files (the "Software"), to deal in the
        +Software without restriction, including without
        +limitation the rights to use, copy, modify, merge,
        +publish, distribute, sublicense, and/or sell copies of
        +the Software, and to permit persons to whom the Software
        +is furnished to do so, subject to the following
        +conditions:
        +
        +The above copyright notice and this permission notice
        +shall be included in all copies or substantial portions
        +of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
        +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
        +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
        +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
        +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
        +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
        +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
        +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
        +DEALINGS IN THE SOFTWARE.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Permission is hereby granted, free of charge, to any
        +person obtaining a copy of this software and associated
        +documentation files (the "Software"), to deal in the
        +Software without restriction, including without
        +limitation the rights to use, copy, modify, merge,
        +publish, distribute, sublicense, and/or sell copies of
        +the Software, and to permit persons to whom the Software
        +is furnished to do so, subject to the following
        +conditions:
        +
        +The above copyright notice and this permission notice
        +shall be included in all copies or substantial portions
        +of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
        +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
        +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
        +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
        +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
        +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
        +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
        +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
        +DEALINGS IN THE SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        Permission is hereby granted, free of charge, to any person obtaining
         a copy of this software and associated documentation files (the
        @@ -13348,37 +18257,39 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        The MIT License (MIT)
        +                
        Portions of this project are derived from atty, which bears the following
        +copyright notice and permission notice:
         
        -Copyright (c) 2014 Benjamin Sago
        -Copyright (c) 2021-2022 The Nushell Project Developers
        +Copyright (c) 2015-2019 Doug Tangren
         
        -Permission is hereby granted, free of charge, to any person obtaining a copy
        -of this software and associated documentation files (the "Software"), to deal
        -in the Software without restriction, including without limitation the rights
        -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        -copies of the Software, and to permit persons to whom the Software is
        -furnished to do so, subject to the following conditions:
        +Permission is hereby granted, free of charge, to any person obtaining
        +a copy of this software and associated documentation files (the
        +"Software"), to deal in the Software without restriction, including
        +without limitation the rights to use, copy, modify, merge, publish,
        +distribute, sublicense, and/or sell copies of the Software, and to
        +permit persons to whom the Software is furnished to do so, subject to
        +the following conditions:
         
        -The above copyright notice and this permission notice shall be included in all
        -copies or substantial portions of the Software.
        +The above copyright notice and this permission notice shall be
        +included in all copies or substantial portions of the Software.
         
        -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        -SOFTWARE.
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
        +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
        +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
        +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
        +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
        +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
        +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
         
      • MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13401,13 +18312,63 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
         LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
         SOFTWARE.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2014 Mathijs van de Nes
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2014 Y. T. CHUNG
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        +
      • MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13435,21 +18396,11 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        The MIT License (MIT)
         
        -Copyright (c) 2015 Andrew Gallant
        +Copyright (c) 2015 
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13458,28 +18409,39 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
         copies of the Software, and to permit persons to whom the Software is
         furnished to do so, subject to the following conditions:
         
        -The above copyright notice and this permission notice shall be included in
        -all copies or substantial portions of the Software.
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
         
         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
         IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
         FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
         AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
         LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        -THE SOFTWARE.
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
         
      • MIT License

        Used by:

        The MIT License (MIT)
         
         Copyright (c) 2015 Andrew Gallant
        -Copyright (c) 2019 Paul Masurel
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13529,6 +18491,36 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
         SOFTWARE.
         
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Carl Lerche + nix-rust Authors
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in
        +all copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        +THE SOFTWARE.
         
      • @@ -13560,6 +18552,64 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +
      • + +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Gerd Zellweger
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in
        +all copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        +THE SOFTWARE.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Guillaume Gomez
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
         
      • @@ -13595,11 +18645,72 @@ SOFTWARE.

        MIT License

        Used by:

        The MIT License (MIT)
         
        -Copyright (c) 2015 Vincent Prouillet
        +Copyright (c) 2015 Markus Westerlind
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in
        +all copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        +THE SOFTWARE.
        +
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Michael Sproul
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in
        +all copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        +THE SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015-2020 the fiat-crypto authors (see
        +https://github.com/mit-plv/fiat-crypto/blob/master/AUTHORS).
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13624,7 +18735,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13640,6 +18751,35 @@ furnished to do so, subject to the following conditions:
         The above copyright notice and this permission notice shall be included in all
         copies or substantial portions of the Software.
         
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2016 nabijaczleweli
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
         IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
         FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        @@ -13713,8 +18853,36 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        The MIT License (MIT)
        +
        +Copyright (c) 2019 Simon Heath
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        The MIT License (MIT)
         
        @@ -13781,6 +18949,36 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
         The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
         
         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2014 Benjamin Sago
        +Copyright (c) 2021-2022 The Nushell Project Developers
        +
        +Permission is hereby granted, free of charge, to any person obtaining a copy
        +of this software and associated documentation files (the "Software"), to deal
        +in the Software without restriction, including without limitation the rights
        +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        +copies of the Software, and to permit persons to whom the Software is
        +furnished to do so, subject to the following conditions:
        +
        +The above copyright notice and this permission notice shall be included in all
        +copies or substantial portions of the Software.
        +
        +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
         
      • @@ -13845,8 +19043,9 @@ SOFTWARE.
      • MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13899,6 +19098,387 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
         LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
         THE SOFTWARE.
        +
        + +
      • +

        Mozilla Public License 2.0

        +

        Used by:

        + +
        Mozilla Public License Version 2.0
        +==================================
        +
        +1. Definitions
        +--------------
        +
        +1.1. "Contributor"
        +    means each individual or legal entity that creates, contributes to
        +    the creation of, or owns Covered Software.
        +
        +1.2. "Contributor Version"
        +    means the combination of the Contributions of others (if any) used
        +    by a Contributor and that particular Contributor's Contribution.
        +
        +1.3. "Contribution"
        +    means Covered Software of a particular Contributor.
        +
        +1.4. "Covered Software"
        +    means Source Code Form to which the initial Contributor has attached
        +    the notice in Exhibit A, the Executable Form of such Source Code
        +    Form, and Modifications of such Source Code Form, in each case
        +    including portions thereof.
        +
        +1.5. "Incompatible With Secondary Licenses"
        +    means
        +
        +    (a) that the initial Contributor has attached the notice described
        +        in Exhibit B to the Covered Software; or
        +
        +    (b) that the Covered Software was made available under the terms of
        +        version 1.1 or earlier of the License, but not also under the
        +        terms of a Secondary License.
        +
        +1.6. "Executable Form"
        +    means any form of the work other than Source Code Form.
        +
        +1.7. "Larger Work"
        +    means a work that combines Covered Software with other material, in 
        +    a separate file or files, that is not Covered Software.
        +
        +1.8. "License"
        +    means this document.
        +
        +1.9. "Licensable"
        +    means having the right to grant, to the maximum extent possible,
        +    whether at the time of the initial grant or subsequently, any and
        +    all of the rights conveyed by this License.
        +
        +1.10. "Modifications"
        +    means any of the following:
        +
        +    (a) any file in Source Code Form that results from an addition to,
        +        deletion from, or modification of the contents of Covered
        +        Software; or
        +
        +    (b) any new file in Source Code Form that contains any Covered
        +        Software.
        +
        +1.11. "Patent Claims" of a Contributor
        +    means any patent claim(s), including without limitation, method,
        +    process, and apparatus claims, in any patent Licensable by such
        +    Contributor that would be infringed, but for the grant of the
        +    License, by the making, using, selling, offering for sale, having
        +    made, import, or transfer of either its Contributions or its
        +    Contributor Version.
        +
        +1.12. "Secondary License"
        +    means either the GNU General Public License, Version 2.0, the GNU
        +    Lesser General Public License, Version 2.1, the GNU Affero General
        +    Public License, Version 3.0, or any later versions of those
        +    licenses.
        +
        +1.13. "Source Code Form"
        +    means the form of the work preferred for making modifications.
        +
        +1.14. "You" (or "Your")
        +    means an individual or a legal entity exercising rights under this
        +    License. For legal entities, "You" includes any entity that
        +    controls, is controlled by, or is under common control with You. For
        +    purposes of this definition, "control" means (a) the power, direct
        +    or indirect, to cause the direction or management of such entity,
        +    whether by contract or otherwise, or (b) ownership of more than
        +    fifty percent (50%) of the outstanding shares or beneficial
        +    ownership of such entity.
        +
        +2. License Grants and Conditions
        +--------------------------------
        +
        +2.1. Grants
        +
        +Each Contributor hereby grants You a world-wide, royalty-free,
        +non-exclusive license:
        +
        +(a) under intellectual property rights (other than patent or trademark)
        +    Licensable by such Contributor to use, reproduce, make available,
        +    modify, display, perform, distribute, and otherwise exploit its
        +    Contributions, either on an unmodified basis, with Modifications, or
        +    as part of a Larger Work; and
        +
        +(b) under Patent Claims of such Contributor to make, use, sell, offer
        +    for sale, have made, import, and otherwise transfer either its
        +    Contributions or its Contributor Version.
        +
        +2.2. Effective Date
        +
        +The licenses granted in Section 2.1 with respect to any Contribution
        +become effective for each Contribution on the date the Contributor first
        +distributes such Contribution.
        +
        +2.3. Limitations on Grant Scope
        +
        +The licenses granted in this Section 2 are the only rights granted under
        +this License. No additional rights or licenses will be implied from the
        +distribution or licensing of Covered Software under this License.
        +Notwithstanding Section 2.1(b) above, no patent license is granted by a
        +Contributor:
        +
        +(a) for any code that a Contributor has removed from Covered Software;
        +    or
        +
        +(b) for infringements caused by: (i) Your and any other third party's
        +    modifications of Covered Software, or (ii) the combination of its
        +    Contributions with other software (except as part of its Contributor
        +    Version); or
        +
        +(c) under Patent Claims infringed by Covered Software in the absence of
        +    its Contributions.
        +
        +This License does not grant any rights in the trademarks, service marks,
        +or logos of any Contributor (except as may be necessary to comply with
        +the notice requirements in Section 3.4).
        +
        +2.4. Subsequent Licenses
        +
        +No Contributor makes additional grants as a result of Your choice to
        +distribute the Covered Software under a subsequent version of this
        +License (see Section 10.2) or under the terms of a Secondary License (if
        +permitted under the terms of Section 3.3).
        +
        +2.5. Representation
        +
        +Each Contributor represents that the Contributor believes its
        +Contributions are its original creation(s) or it has sufficient rights
        +to grant the rights to its Contributions conveyed by this License.
        +
        +2.6. Fair Use
        +
        +This License is not intended to limit any rights You have under
        +applicable copyright doctrines of fair use, fair dealing, or other
        +equivalents.
        +
        +2.7. Conditions
        +
        +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
        +in Section 2.1.
        +
        +3. Responsibilities
        +-------------------
        +
        +3.1. Distribution of Source Form
        +
        +All distribution of Covered Software in Source Code Form, including any
        +Modifications that You create or to which You contribute, must be under
        +the terms of this License. You must inform recipients that the Source
        +Code Form of the Covered Software is governed by the terms of this
        +License, and how they can obtain a copy of this License. You may not
        +attempt to alter or restrict the recipients' rights in the Source Code
        +Form.
        +
        +3.2. Distribution of Executable Form
        +
        +If You distribute Covered Software in Executable Form then:
        +
        +(a) such Covered Software must also be made available in Source Code
        +    Form, as described in Section 3.1, and You must inform recipients of
        +    the Executable Form how they can obtain a copy of such Source Code
        +    Form by reasonable means in a timely manner, at a charge no more
        +    than the cost of distribution to the recipient; and
        +
        +(b) You may distribute such Executable Form under the terms of this
        +    License, or sublicense it under different terms, provided that the
        +    license for the Executable Form does not attempt to limit or alter
        +    the recipients' rights in the Source Code Form under this License.
        +
        +3.3. Distribution of a Larger Work
        +
        +You may create and distribute a Larger Work under terms of Your choice,
        +provided that You also comply with the requirements of this License for
        +the Covered Software. If the Larger Work is a combination of Covered
        +Software with a work governed by one or more Secondary Licenses, and the
        +Covered Software is not Incompatible With Secondary Licenses, this
        +License permits You to additionally distribute such Covered Software
        +under the terms of such Secondary License(s), so that the recipient of
        +the Larger Work may, at their option, further distribute the Covered
        +Software under the terms of either this License or such Secondary
        +License(s).
        +
        +3.4. Notices
        +
        +You may not remove or alter the substance of any license notices
        +(including copyright notices, patent notices, disclaimers of warranty,
        +or limitations of liability) contained within the Source Code Form of
        +the Covered Software, except that You may alter any license notices to
        +the extent required to remedy known factual inaccuracies.
        +
        +3.5. Application of Additional Terms
        +
        +You may choose to offer, and to charge a fee for, warranty, support,
        +indemnity or liability obligations to one or more recipients of Covered
        +Software. However, You may do so only on Your own behalf, and not on
        +behalf of any Contributor. You must make it absolutely clear that any
        +such warranty, support, indemnity, or liability obligation is offered by
        +You alone, and You hereby agree to indemnify every Contributor for any
        +liability incurred by such Contributor as a result of warranty, support,
        +indemnity or liability terms You offer. You may include additional
        +disclaimers of warranty and limitations of liability specific to any
        +jurisdiction.
        +
        +4. Inability to Comply Due to Statute or Regulation
        +---------------------------------------------------
        +
        +If it is impossible for You to comply with any of the terms of this
        +License with respect to some or all of the Covered Software due to
        +statute, judicial order, or regulation then You must: (a) comply with
        +the terms of this License to the maximum extent possible; and (b)
        +describe the limitations and the code they affect. Such description must
        +be placed in a text file included with all distributions of the Covered
        +Software under this License. Except to the extent prohibited by statute
        +or regulation, such description must be sufficiently detailed for a
        +recipient of ordinary skill to be able to understand it.
        +
        +5. Termination
        +--------------
        +
        +5.1. The rights granted under this License will terminate automatically
        +if You fail to comply with any of its terms. However, if You become
        +compliant, then the rights granted under this License from a particular
        +Contributor are reinstated (a) provisionally, unless and until such
        +Contributor explicitly and finally terminates Your grants, and (b) on an
        +ongoing basis, if such Contributor fails to notify You of the
        +non-compliance by some reasonable means prior to 60 days after You have
        +come back into compliance. Moreover, Your grants from a particular
        +Contributor are reinstated on an ongoing basis if such Contributor
        +notifies You of the non-compliance by some reasonable means, this is the
        +first time You have received notice of non-compliance with this License
        +from such Contributor, and You become compliant prior to 30 days after
        +Your receipt of the notice.
        +
        +5.2. If You initiate litigation against any entity by asserting a patent
        +infringement claim (excluding declaratory judgment actions,
        +counter-claims, and cross-claims) alleging that a Contributor Version
        +directly or indirectly infringes any patent, then the rights granted to
        +You by any and all Contributors for the Covered Software under Section
        +2.1 of this License shall terminate.
        +
        +5.3. In the event of termination under Sections 5.1 or 5.2 above, all
        +end user license agreements (excluding distributors and resellers) which
        +have been validly granted by You or Your distributors under this License
        +prior to termination shall survive termination.
        +
        +************************************************************************
        +*                                                                      *
        +*  6. Disclaimer of Warranty                                           *
        +*  -------------------------                                           *
        +*                                                                      *
        +*  Covered Software is provided under this License on an "as is"       *
        +*  basis, without warranty of any kind, either expressed, implied, or  *
        +*  statutory, including, without limitation, warranties that the       *
        +*  Covered Software is free of defects, merchantable, fit for a        *
        +*  particular purpose or non-infringing. The entire risk as to the     *
        +*  quality and performance of the Covered Software is with You.        *
        +*  Should any Covered Software prove defective in any respect, You     *
        +*  (not any Contributor) assume the cost of any necessary servicing,   *
        +*  repair, or correction. This disclaimer of warranty constitutes an   *
        +*  essential part of this License. No use of any Covered Software is   *
        +*  authorized under this License except under this disclaimer.         *
        +*                                                                      *
        +************************************************************************
        +
        +************************************************************************
        +*                                                                      *
        +*  7. Limitation of Liability                                          *
        +*  --------------------------                                          *
        +*                                                                      *
        +*  Under no circumstances and under no legal theory, whether tort      *
        +*  (including negligence), contract, or otherwise, shall any           *
        +*  Contributor, or anyone who distributes Covered Software as          *
        +*  permitted above, be liable to You for any direct, indirect,         *
        +*  special, incidental, or consequential damages of any character      *
        +*  including, without limitation, damages for lost profits, loss of    *
        +*  goodwill, work stoppage, computer failure or malfunction, or any    *
        +*  and all other commercial damages or losses, even if such party      *
        +*  shall have been informed of the possibility of such damages. This   *
        +*  limitation of liability shall not apply to liability for death or   *
        +*  personal injury resulting from such party's negligence to the       *
        +*  extent applicable law prohibits such limitation. Some               *
        +*  jurisdictions do not allow the exclusion or limitation of           *
        +*  incidental or consequential damages, so this exclusion and          *
        +*  limitation may not apply to You.                                    *
        +*                                                                      *
        +************************************************************************
        +
        +8. Litigation
        +-------------
        +
        +Any litigation relating to this License may be brought only in the
        +courts of a jurisdiction where the defendant maintains its principal
        +place of business and such litigation shall be governed by laws of that
        +jurisdiction, without reference to its conflict-of-law provisions.
        +Nothing in this Section shall prevent a party's ability to bring
        +cross-claims or counter-claims.
        +
        +9. Miscellaneous
        +----------------
        +
        +This License represents the complete agreement concerning the subject
        +matter hereof. If any provision of this License is held to be
        +unenforceable, such provision shall be reformed only to the extent
        +necessary to make it enforceable. Any law or regulation which provides
        +that the language of a contract shall be construed against the drafter
        +shall not be used to construe this License against a Contributor.
        +
        +10. Versions of the License
        +---------------------------
        +
        +10.1. New Versions
        +
        +Mozilla Foundation is the license steward. Except as provided in Section
        +10.3, no one other than the license steward has the right to modify or
        +publish new versions of this License. Each version will be given a
        +distinguishing version number.
        +
        +10.2. Effect of New Versions
        +
        +You may distribute the Covered Software under the terms of the version
        +of the License under which You originally received the Covered Software,
        +or under the terms of any subsequent version published by the license
        +steward.
        +
        +10.3. Modified Versions
        +
        +If you create software not governed by this License, and you want to
        +create a new license for such software, you may create and use a
        +modified version of this License if you rename the license and remove
        +any references to the name of the license steward (except to note that
        +such modified license differs from this License).
        +
        +10.4. Distributing Source Code Form that is Incompatible With Secondary
        +Licenses
        +
        +If You choose to distribute Source Code Form that is Incompatible With
        +Secondary Licenses under the terms of this version of the License, the
        +notice described in Exhibit B of this License must be attached.
        +
        +Exhibit A - Source Code Form License Notice
        +-------------------------------------------
        +
        +  This Source Code Form is subject to the terms of the Mozilla Public
        +  License, v. 2.0. If a copy of the MPL was not distributed with this
        +  file, You can obtain one at http://mozilla.org/MPL/2.0/.
        +
        +If it is not possible or desirable to put the notice in a particular
        +file, then You may include the notice in a location (such as a LICENSE
        +file in a relevant directory) where a recipient would be likely to look
        +for such a notice.
        +
        +You may add additional accurate notices of copyright ownership.
        +
        +Exhibit B - "Incompatible With Secondary Licenses" Notice
        +---------------------------------------------------------
        +
        +  This Source Code Form is "Incompatible With Secondary Licenses", as
        +  defined by the Mozilla Public License, v. 2.0.
         
      • @@ -14280,187 +19860,13 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. -
      • - -
      • -

        OpenSSL License

        -

        Used by:

        - -
        /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
        - * All rights reserved.
        - *
        - * This package is an SSL implementation written
        - * by Eric Young (eay@cryptsoft.com).
        - * The implementation was written so as to conform with Netscapes SSL.
        - *
        - * This library is free for commercial and non-commercial use as long as
        - * the following conditions are aheared to.  The following conditions
        - * apply to all code found in this distribution, be it the RC4, RSA,
        - * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
        - * included with this distribution is covered by the same copyright terms
        - * except that the holder is Tim Hudson (tjh@cryptsoft.com).
        - *
        - * Copyright remains Eric Young's, and as such any Copyright notices in
        - * the code are not to be removed.
        - * If this package is used in a product, Eric Young should be given attribution
        - * as the author of the parts of the library used.
        - * This can be in the form of a textual message at program startup or
        - * in documentation (online or textual) provided with the package.
        - *
        - * Redistribution and use in source and binary forms, with or without
        - * modification, are permitted provided that the following conditions
        - * are met:
        - * 1. Redistributions of source code must retain the copyright
        - *    notice, this list of conditions and the following disclaimer.
        - * 2. Redistributions in binary form must reproduce the above copyright
        - *    notice, this list of conditions and the following disclaimer in the
        - *    documentation and/or other materials provided with the distribution.
        - * 3. All advertising materials mentioning features or use of this software
        - *    must display the following acknowledgement:
        - *    "This product includes cryptographic software written by
        - *     Eric Young (eay@cryptsoft.com)"
        - *    The word 'cryptographic' can be left out if the rouines from the library
        - *    being used are not cryptographic related :-).
        - * 4. If you include any Windows specific code (or a derivative thereof) from
        - *    the apps directory (application code) you must include an acknowledgement:
        - *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
        - *
        - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
        - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
        - * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
        - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
        - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
        - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
        - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
        - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
        - * SUCH DAMAGE.
        - *
        - * The licence and distribution terms for any publically available version or
        - * derivative of this code cannot be changed.  i.e. this code cannot simply be
        - * copied and put under another distribution licence
        - * [including the GNU Public Licence.]
        - */
        -/* ====================================================================
        - * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
        - *
        - * Redistribution and use in source and binary forms, with or without
        - * modification, are permitted provided that the following conditions
        - * are met:
        - *
        - * 1. Redistributions of source code must retain the above copyright
        - *    notice, this list of conditions and the following disclaimer.
        - *
        - * 2. Redistributions in binary form must reproduce the above copyright
        - *    notice, this list of conditions and the following disclaimer in
        - *    the documentation and/or other materials provided with the
        - *    distribution.
        - *
        - * 3. All advertising materials mentioning features or use of this
        - *    software must display the following acknowledgment:
        - *    "This product includes software developed by the OpenSSL Project
        - *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
        - *
        - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
        - *    endorse or promote products derived from this software without
        - *    prior written permission. For written permission, please contact
        - *    openssl-core@openssl.org.
        - *
        - * 5. Products derived from this software may not be called "OpenSSL"
        - *    nor may "OpenSSL" appear in their names without prior written
        - *    permission of the OpenSSL Project.
        - *
        - * 6. Redistributions of any form whatsoever must retain the following
        - *    acknowledgment:
        - *    "This product includes software developed by the OpenSSL Project
        - *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
        - *
        - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
        - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
        - * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
        - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
        - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
        - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
        - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
        - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
        - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
        - * OF THE POSSIBILITY OF SUCH DAMAGE.
        - * ====================================================================
        - *
        - * This product includes cryptographic software written by Eric Young
        - * (eay@cryptsoft.com).  This product includes software written by Tim
        - * Hudson (tjh@cryptsoft.com).
        - *
        - */
        -
        -#include <openssl/ssl.h>
        -
        -#if !defined(OPENSSL_WINDOWS) && !defined(OPENSSL_PNACL) && \
        -    !defined(OPENSSL_NO_FILESYSTEM)
        -
        -#include <dirent.h>
        -#include <errno.h>
        -#include <string.h>
        -
        -#include <openssl/err.h>
        -#include <openssl/mem.h>
        -
        -
        -int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
        -                                       const char *path) {
        -  DIR *dir = opendir(path);
        -  if (dir == NULL) {
        -    OPENSSL_PUT_ERROR(SSL, ERR_R_SYS_LIB);
        -    ERR_add_error_data(3, "opendir('", dir, "')");
        -    return 0;
        -  }
        -
        -  int ret = 0;
        -  for (;;) {
        -    // |readdir| may fail with or without setting |errno|.
        -    errno = 0;
        -    struct dirent *dirent = readdir(dir);
        -    if (dirent == NULL) {
        -      if (errno) {
        -        OPENSSL_PUT_ERROR(SSL, ERR_R_SYS_LIB);
        -        ERR_add_error_data(3, "readdir('", path, "')");
        -      } else {
        -        ret = 1;
        -      }
        -      break;
        -    }
        -
        -    char buf[1024];
        -    if (strlen(path) + strlen(dirent->d_name) + 2 > sizeof(buf)) {
        -      OPENSSL_PUT_ERROR(SSL, SSL_R_PATH_TOO_LONG);
        -      break;
        -    }
        -
        -    int r = snprintf(buf, sizeof(buf), "%s/%s", path, dirent->d_name);
        -    if (r <= 0 ||
        -        r >= (int)sizeof(buf) ||
        -        !SSL_add_file_cert_subjects_to_stack(stack, buf)) {
        -      break;
        -    }
        -  }
        -
        -  closedir(dir);
        -  return ret;
        -}
        -
        -#endif  // !WINDOWS && !PNACL && !OPENSSL_NO_FILESYSTEM
         
      • Unicode License v3

        Used by:

        UNICODE LICENSE V3
         
        @@ -14507,24 +19913,28 @@ authorization of the copyright holder.
                         

        Unicode License v3

        Used by:

        UNICODE LICENSE V3
         
        @@ -14573,12 +19983,63 @@ SPDX-License-Identifier: Unicode-3.0
         Portions of ICU4X may have been adapted from ICU4C and/or ICU4J.
         ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others.
         
        +
      • +
      • +

        zlib License

        +

        Used by:

        + +
        Copyright (c) 2021 Matias Rodriguez.
        +
        +This software is provided 'as-is', without any express or implied
        +warranty. In no event will the authors be held liable for any damages
        +arising from the use of this software.
        +
        +Permission is granted to anyone to use this software for any purpose,
        +including commercial applications, and to alter it and redistribute it
        +freely, subject to the following restrictions:
        +
        +1. The origin of this software must not be misrepresented; you must not
        +   claim that you wrote the original software. If you use this software
        +   in a product, an acknowledgment in the product documentation would be
        +   appreciated but is not required.
        +2. Altered source versions must be plainly marked as such, and must not be
        +   misrepresented as being the original software.
        +3. This notice may not be removed or altered from any source distribution.
        +
      • +
      • +

        zlib License

        +

        Used by:

        + +
        Copyright (c) 2023 Matias Rodriguez.
        +
        +This software is provided 'as-is', without any express or implied
        +warranty. In no event will the authors be held liable for any damages
        +arising from the use of this software.
        +
        +Permission is granted to anyone to use this software for any purpose,
        +including commercial applications, and to alter it and redistribute it
        +freely, subject to the following restrictions:
        +
        +1. The origin of this software must not be misrepresented; you must not
        +   claim that you wrote the original software. If you use this software
        +   in a product, an acknowledgment in the product documentation would be
        +   appreciated but is not required.
        +2. Altered source versions must be plainly marked as such, and must not be
        +   misrepresented as being the original software.
        +3. This notice may not be removed or altered from any source distribution.
      • zlib License

        Used by:

        Copyright (c) 2024 Orson Peters
         
        diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts
        index 18bf0f1ce..eccfb9ffd 100644
        --- a/nodejs/__test__/remote.test.ts
        +++ b/nodejs/__test__/remote.test.ts
        @@ -1435,6 +1435,87 @@ describe("remote connection", () => {
             expect(createIndexBody?.["custom_stop_words"]).toEqual(["the"]);
           });
         
        +  it("sends RTree options to remote tables", async () => {
        +    const createIndexBodies: Record[] = [];
        +
        +    await withMockDatabase(
        +      (req, res) => {
        +        const path = req.url ?? "";
        +        if (path.endsWith("/describe/")) {
        +          res.writeHead(200, { "Content-Type": "application/json" }).end(
        +            JSON.stringify({
        +              name: "t",
        +              version: 1,
        +              schema: {
        +                fields: [
        +                  {
        +                    name: "geom",
        +                    type: {
        +                      type: "struct",
        +                      fields: [
        +                        {
        +                          name: "x",
        +                          type: { type: "double" },
        +                          nullable: false,
        +                        },
        +                        {
        +                          name: "y",
        +                          type: { type: "double" },
        +                          nullable: false,
        +                        },
        +                      ],
        +                    },
        +                    nullable: true,
        +                    metadata: { "ARROW:extension:name": "geoarrow.point" },
        +                  },
        +                ],
        +              },
        +            }),
        +          );
        +          return;
        +        }
        +
        +        if (path.endsWith("/create_index/")) {
        +          let raw = "";
        +          req.on("data", (chunk) => {
        +            raw += chunk;
        +          });
        +          req.on("end", () => {
        +            createIndexBodies.push(JSON.parse(raw));
        +            res.writeHead(200).end();
        +          });
        +          return;
        +        }
        +
        +        res.writeHead(404).end();
        +      },
        +      async (db) => {
        +        const table = await db.openTable("t");
        +        await table.createIndex("geom", { config: Index.rtree() });
        +        await table.createIndex("geom", {
        +          config: Index.rtree({ pageSize: 1024 }),
        +          name: "geom_rtree",
        +        });
        +      },
        +    );
        +
        +    expect(createIndexBodies).toEqual([
        +      {
        +        column: "geom",
        +        // biome-ignore lint/style/useNamingConvention: server wire format
        +        index_type: "RTREE",
        +      },
        +      {
        +        column: "geom",
        +        // biome-ignore lint/style/useNamingConvention: server wire format
        +        index_type: "RTREE",
        +        name: "geom_rtree",
        +        // biome-ignore lint/style/useNamingConvention: server wire format
        +        page_size: 1024,
        +      },
        +    ]);
        +  });
        +
           it("diffs and cherry-picks remote branches", async () => {
             const sampleDiff = {
               fromBranch: "exp",
        diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts
        index bfe69e931..7aac3864c 100644
        --- a/nodejs/__test__/table.test.ts
        +++ b/nodejs/__test__/table.test.ts
        @@ -1833,6 +1833,104 @@ describe("When creating an index", () => {
             expect(fs.readdirSync(indexDir)).toHaveLength(1);
           });
         
        +  describe("on a GeoArrow column", () => {
        +    // Row `10 * y + x` sits at (x, y). The triangle's bounding box covers the
        +    // 25 points with x <= 4 and y <= 4, but only the 15 with x + y <= 4
        +    // intersect the triangle itself.
        +    const inTriangle =
        +      "ST_Intersects(geom, ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))'))";
        +    const triangleIds = [0, 1, 2, 3, 4, 10, 11, 12, 13, 20, 21, 22, 30, 31, 40];
        +    let geoTbl: Table;
        +
        +    beforeEach(async () => {
        +      const point = new Struct([
        +        new Field("x", new Float64(), false),
        +        new Field("y", new Float64(), false),
        +      ]);
        +      const geoSchema = new Schema([
        +        new Field("id", new Int32(), false),
        +        new Field(
        +          "geom",
        +          point,
        +          true,
        +          new Map([
        +            ["ARROW:extension:name", "geoarrow.point"],
        +            ["ARROW:extension:metadata", "{}"],
        +          ]),
        +        ),
        +        new Field(
        +          "vec",
        +          new FixedSizeList(2, new Field("item", new Float32())),
        +        ),
        +      ]);
        +      const data = makeArrowTable(
        +        Array.from({ length: 100 }, (_, i) => ({
        +          id: i,
        +          geom: { x: i % 10, y: Math.floor(i / 10) },
        +          vec: [i, i],
        +        })),
        +        { schema: geoSchema },
        +      );
        +      const db = await connect(tmpDir.name);
        +      geoTbl = await db.createTable("points", data);
        +    });
        +
        +    const ids = (rows: { id: number }[]) => rows.map((row) => row.id);
        +
        +    test("create an RTree index and filter with it", async () => {
        +      await geoTbl.createIndex("geom", { config: Index.rtree() });
        +      expect(await geoTbl.listIndices()).toEqual([
        +        expect.objectContaining({
        +          name: "geom_idx",
        +          indexType: "RTree",
        +          columns: ["geom"],
        +        }),
        +      ]);
        +      const stats = await geoTbl.indexStats("geom_idx");
        +      expect(stats?.indexType).toEqual("RTREE");
        +      expect(stats?.numIndexedRows).toEqual(100);
        +
        +      const query = geoTbl.query().where(inTriangle);
        +      expect(await query.explainPlan(true)).toContain("ScalarIndexQuery");
        +      expect(ids(await query.toArray()).sort((a, b) => a - b)).toEqual(
        +        triangleIds,
        +      );
        +    });
        +
        +    test("prefilter a vector search with an RTree index", async () => {
        +      await geoTbl.createIndex("geom", {
        +        config: Index.rtree({ pageSize: 16 }),
        +      });
        +      // Row 99 sits outside the triangle; its nearest vectors are 98, 97, ...
        +      const prefiltered = geoTbl
        +        .query()
        +        .nearestTo([99, 99])
        +        .where(inTriangle)
        +        .limit(5);
        +      expect(await prefiltered.explainPlan(true)).toContain("ScalarIndexQuery");
        +      expect(ids(await prefiltered.toArray())).toEqual([40, 31, 30, 22, 21]);
        +
        +      const postfiltered = geoTbl
        +        .query()
        +        .nearestTo([99, 99])
        +        .where(inTriangle)
        +        .postfilter()
        +        .limit(5);
        +      expect(await postfiltered.toArray()).toEqual([]);
        +    });
        +
        +    test("reject invalid RTree options", async () => {
        +      for (const pageSize of [1, 0, -1, 2.5, Number.NaN, 2 ** 32]) {
        +        expect(() => Index.rtree({ pageSize })).toThrow(
        +          "page_size must be at least 2",
        +        );
        +      }
        +      await expect(
        +        geoTbl.createIndex("id", { config: Index.rtree() }),
        +      ).rejects.toThrow("GeoArrow");
        +    });
        +  });
        +
           test("should be able to get index stats", async () => {
             await tbl.createIndex("id");
         
        diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts
        index b99d856cc..aa51c2b56 100644
        --- a/nodejs/lancedb/index.ts
        +++ b/nodejs/lancedb/index.ts
        @@ -153,6 +153,7 @@ export {
           HnswPqOptions,
           HnswSqOptions,
           FtsOptions,
        +  RTreeOptions,
           BaseTokenizer,
         } from "./indices";
         
        diff --git a/nodejs/lancedb/indices.ts b/nodejs/lancedb/indices.ts
        index 53cbf8a4d..d743827da 100644
        --- a/nodejs/lancedb/indices.ts
        +++ b/nodejs/lancedb/indices.ts
        @@ -678,6 +678,18 @@ export interface FtsOptions {
           blockSize?: 128 | 256;
         }
         
        +/**
        + * Options to create an `RTREE` index
        + */
        +export interface RTreeOptions {
        +  /**
        +   * The maximum number of entries in each R-tree page.
        +   *
        +   * Must be at least 2. The default is 4096.
        +   */
        +  pageSize?: number;
        +}
        +
         export class Index {
           private readonly inner: LanceDbIndex;
           private constructor(inner: LanceDbIndex) {
        @@ -834,6 +846,53 @@ export class Index {
             return new Index(LanceDbIndex.fm());
           }
         
        +  /**
        +   * Create an RTree index.
        +   *
        +   * An RTree index is a scalar index on a GeoArrow geometry column, that is, a
        +   * column whose Arrow field metadata sets `ARROW:extension:name` to a GeoArrow
        +   * type such as `geoarrow.point`, `geoarrow.polygon` or `geoarrow.wkb`. It
        +   * stores the bounding box of each geometry and accelerates spatial filters.
        +   *
        +   * The index accelerates `ST_Intersects`, `ST_Contains`, `ST_Within`,
        +   * `ST_Touches`, `ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy`
        +   * between the indexed column and a constant geometry, in either argument
        +   * order, for example
        +   * `ST_Within(geom, ST_GeomFromText('POLYGON ((...))'))`, as well as
        +   * `geom IS NULL`. These filters can be combined with other conditions using
        +   * `AND`.
        +   *
        +   * See the R-tree section of https://docs.lancedb.com/indexing/scalar-index
        +   * for storing geometry, the other spatial functions, and spatial filters on
        +   * vector search.
        +   *
        +   * Remote tables send the `RTREE` index type to the server, which must
        +   * support it.
        +   *
        +   * @example
        +   * ```ts
        +   * await table.createIndex("geom", { config: Index.rtree() });
        +   * await table
        +   *   .query()
        +   *   .where("ST_Intersects(geom, ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))'))")
        +   *   .toArray();
        +   * ```
        +   */
        +  static rtree(options?: Partial) {
        +    const pageSize = options?.pageSize;
        +    // napi converts a number to u32 by wrapping, so -1 would arrive as
        +    // 4294967295; reject anything that is not a valid page size first.
        +    if (
        +      pageSize !== undefined &&
        +      !(Number.isInteger(pageSize) && pageSize >= 2 && pageSize <= 0xffffffff)
        +    ) {
        +      throw new Error(
        +        `RTree page_size must be at least 2, at most 4294967295, and an integer, got ${pageSize}`,
        +      );
        +    }
        +    return new Index(LanceDbIndex.rtree(pageSize));
        +  }
        +
           /**
            * Create a full text search index
            *
        diff --git a/nodejs/src/index.rs b/nodejs/src/index.rs
        index 39aa6f8b8..80107b0b4 100644
        --- a/nodejs/src/index.rs
        +++ b/nodejs/src/index.rs
        @@ -4,7 +4,9 @@
         use std::sync::Mutex;
         
         use lancedb::index::Index as LanceDbIndex;
        -use lancedb::index::scalar::{BTreeIndexBuilder, FmIndexBuilder, FtsIndexBuilder};
        +use lancedb::index::scalar::{
        +    BTreeIndexBuilder, FmIndexBuilder, FtsIndexBuilder, RTreeIndexBuilder,
        +};
         use lancedb::index::vector::{
             IvfFlatIndexBuilder, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder, IvfPqIndexBuilder,
             IvfRqIndexBuilder,
        @@ -226,6 +228,17 @@ impl Index {
                 }
             }
         
        +    #[napi(factory)]
        +    pub fn rtree(page_size: Option) -> napi::Result {
        +        let mut builder = RTreeIndexBuilder::default();
        +        if let Some(page_size) = page_size {
        +            builder = builder.page_size(page_size).default_error()?;
        +        }
        +        Ok(Self {
        +            inner: Mutex::new(Some(LanceDbIndex::RTree(builder))),
        +        })
        +    }
        +
             #[napi(factory)]
             #[allow(clippy::too_many_arguments)]
             pub fn fts(
        diff --git a/python/Cargo.toml b/python/Cargo.toml
        index 8604daabf..631340ce2 100644
        --- a/python/Cargo.toml
        +++ b/python/Cargo.toml
        @@ -51,7 +51,7 @@ libc = "0.2"
         pyo3-build-config = "0.29"
         
         [features]
        -default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel"]
        +default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel", "lancedb/geo"]
         fp16kernels = ["lancedb/fp16kernels"]
         remote = ["lancedb/remote"]
         experimental-functions = ["lancedb/experimental-functions"]
        diff --git a/python/RUST_THIRD_PARTY_LICENSES.html b/python/RUST_THIRD_PARTY_LICENSES.html
        index f5e8197fd..2e0c1f20c 100644
        --- a/python/RUST_THIRD_PARTY_LICENSES.html
        +++ b/python/RUST_THIRD_PARTY_LICENSES.html
        @@ -44,18 +44,19 @@
             
                 

        Overview of licenses:

        All license text:

        @@ -64,230 +65,20 @@

        BSD Zero Clause License

        Used by:

        -
        Copyright (C) 2020 by museun <museun@outlook.com>
        +                
        Copyright (C) Jonas Schievink <jonasschievink@gmail.com>
         
        -Permission to use, copy, modify, and/or distribute this software for any purpose
        -with or without fee is hereby granted.
        +Permission to use, copy, modify, and/or distribute this software for
        +any purpose with or without fee is hereby granted.
         
        -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
        -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
        -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
        -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
        -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
        -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
        -THIS SOFTWARE.
        -
        -
      • -
      • -

        Apache License 2.0

        -

        Used by:

        - -
        -                                 Apache License
        -                           Version 2.0, January 2004
        -                        http://www.apache.org/licenses/
        -
        -   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        -
        -   1. Definitions.
        -
        -      "License" shall mean the terms and conditions for use, reproduction,
        -      and distribution as defined by Sections 1 through 9 of this document.
        -
        -      "Licensor" shall mean the copyright owner or entity authorized by
        -      the copyright owner that is granting the License.
        -
        -      "Legal Entity" shall mean the union of the acting entity and all
        -      other entities that control, are controlled by, or are under common
        -      control with that entity. For the purposes of this definition,
        -      "control" means (i) the power, direct or indirect, to cause the
        -      direction or management of such entity, whether by contract or
        -      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        -      outstanding shares, or (iii) beneficial ownership of such entity.
        -
        -      "You" (or "Your") shall mean an individual or Legal Entity
        -      exercising permissions granted by this License.
        -
        -      "Source" form shall mean the preferred form for making modifications,
        -      including but not limited to software source code, documentation
        -      source, and configuration files.
        -
        -      "Object" form shall mean any form resulting from mechanical
        -      transformation or translation of a Source form, including but
        -      not limited to compiled object code, generated documentation,
        -      and conversions to other media types.
        -
        -      "Work" shall mean the work of authorship, whether in Source or
        -      Object form, made available under the License, as indicated by a
        -      copyright notice that is included in or attached to the work
        -      (an example is provided in the Appendix below).
        -
        -      "Derivative Works" shall mean any work, whether in Source or Object
        -      form, that is based on (or derived from) the Work and for which the
        -      editorial revisions, annotations, elaborations, or other modifications
        -      represent, as a whole, an original work of authorship. For the purposes
        -      of this License, Derivative Works shall not include works that remain
        -      separable from, or merely link (or bind by name) to the interfaces of,
        -      the Work and Derivative Works thereof.
        -
        -      "Contribution" shall mean any work of authorship, including
        -      the original version of the Work and any modifications or additions
        -      to that Work or Derivative Works thereof, that is intentionally
        -      submitted to Licensor for inclusion in the Work by the copyright owner
        -      or by an individual or Legal Entity authorized to submit on behalf of
        -      the copyright owner. For the purposes of this definition, "submitted"
        -      means any form of electronic, verbal, or written communication sent
        -      to the Licensor or its representatives, including but not limited to
        -      communication on electronic mailing lists, source code control systems,
        -      and issue tracking systems that are managed by, or on behalf of, the
        -      Licensor for the purpose of discussing and improving the Work, but
        -      excluding communication that is conspicuously marked or otherwise
        -      designated in writing by the copyright owner as "Not a Contribution."
        -
        -      "Contributor" shall mean Licensor and any individual or Legal Entity
        -      on behalf of whom a Contribution has been received by Licensor and
        -      subsequently incorporated within the Work.
        -
        -   2. Grant of Copyright License. Subject to the terms and conditions of
        -      this License, each Contributor hereby grants to You a perpetual,
        -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        -      copyright license to reproduce, prepare Derivative Works of,
        -      publicly display, publicly perform, sublicense, and distribute the
        -      Work and such Derivative Works in Source or Object form.
        -
        -   3. Grant of Patent License. Subject to the terms and conditions of
        -      this License, each Contributor hereby grants to You a perpetual,
        -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        -      (except as stated in this section) patent license to make, have made,
        -      use, offer to sell, sell, import, and otherwise transfer the Work,
        -      where such license applies only to those patent claims licensable
        -      by such Contributor that are necessarily infringed by their
        -      Contribution(s) alone or by combination of their Contribution(s)
        -      with the Work to which such Contribution(s) was submitted. If You
        -      institute patent litigation against any entity (including a
        -      cross-claim or counterclaim in a lawsuit) alleging that the Work
        -      or a Contribution incorporated within the Work constitutes direct
        -      or contributory patent infringement, then any patent licenses
        -      granted to You under this License for that Work shall terminate
        -      as of the date such litigation is filed.
        -
        -   4. Redistribution. You may reproduce and distribute copies of the
        -      Work or Derivative Works thereof in any medium, with or without
        -      modifications, and in Source or Object form, provided that You
        -      meet the following conditions:
        -
        -      (a) You must give any other recipients of the Work or
        -          Derivative Works a copy of this License; and
        -
        -      (b) You must cause any modified files to carry prominent notices
        -          stating that You changed the files; and
        -
        -      (c) You must retain, in the Source form of any Derivative Works
        -          that You distribute, all copyright, patent, trademark, and
        -          attribution notices from the Source form of the Work,
        -          excluding those notices that do not pertain to any part of
        -          the Derivative Works; and
        -
        -      (d) If the Work includes a "NOTICE" text file as part of its
        -          distribution, then any Derivative Works that You distribute must
        -          include a readable copy of the attribution notices contained
        -          within such NOTICE file, excluding those notices that do not
        -          pertain to any part of the Derivative Works, in at least one
        -          of the following places: within a NOTICE text file distributed
        -          as part of the Derivative Works; within the Source form or
        -          documentation, if provided along with the Derivative Works; or,
        -          within a display generated by the Derivative Works, if and
        -          wherever such third-party notices normally appear. The contents
        -          of the NOTICE file are for informational purposes only and
        -          do not modify the License. You may add Your own attribution
        -          notices within Derivative Works that You distribute, alongside
        -          or as an addendum to the NOTICE text from the Work, provided
        -          that such additional attribution notices cannot be construed
        -          as modifying the License.
        -
        -      You may add Your own copyright statement to Your modifications and
        -      may provide additional or different license terms and conditions
        -      for use, reproduction, or distribution of Your modifications, or
        -      for any such Derivative Works as a whole, provided Your use,
        -      reproduction, and distribution of the Work otherwise complies with
        -      the conditions stated in this License.
        -
        -   5. Submission of Contributions. Unless You explicitly state otherwise,
        -      any Contribution intentionally submitted for inclusion in the Work
        -      by You to the Licensor shall be under the terms and conditions of
        -      this License, without any additional terms or conditions.
        -      Notwithstanding the above, nothing herein shall supersede or modify
        -      the terms of any separate license agreement you may have executed
        -      with Licensor regarding such Contributions.
        -
        -   6. Trademarks. This License does not grant permission to use the trade
        -      names, trademarks, service marks, or product names of the Licensor,
        -      except as required for reasonable and customary use in describing the
        -      origin of the Work and reproducing the content of the NOTICE file.
        -
        -   7. Disclaimer of Warranty. Unless required by applicable law or
        -      agreed to in writing, Licensor provides the Work (and each
        -      Contributor provides its Contributions) on an "AS IS" BASIS,
        -      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        -      implied, including, without limitation, any warranties or conditions
        -      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        -      PARTICULAR PURPOSE. You are solely responsible for determining the
        -      appropriateness of using or redistributing the Work and assume any
        -      risks associated with Your exercise of permissions under this License.
        -
        -   8. Limitation of Liability. In no event and under no legal theory,
        -      whether in tort (including negligence), contract, or otherwise,
        -      unless required by applicable law (such as deliberate and grossly
        -      negligent acts) or agreed to in writing, shall any Contributor be
        -      liable to You for damages, including any direct, indirect, special,
        -      incidental, or consequential damages of any character arising as a
        -      result of this License or out of the use or inability to use the
        -      Work (including but not limited to damages for loss of goodwill,
        -      work stoppage, computer failure or malfunction, or any and all
        -      other commercial damages or losses), even if such Contributor
        -      has been advised of the possibility of such damages.
        -
        -   9. Accepting Warranty or Additional Liability. While redistributing
        -      the Work or Derivative Works thereof, You may choose to offer,
        -      and charge a fee for, acceptance of support, warranty, indemnity,
        -      or other liability obligations and/or rights consistent with this
        -      License. However, in accepting such obligations, You may act only
        -      on Your own behalf and on Your sole responsibility, not on behalf
        -      of any other Contributor, and only if You agree to indemnify,
        -      defend, and hold each Contributor harmless for any liability
        -      incurred by, or claims asserted against, such Contributor by reason
        -      of your accepting any such warranty or additional liability.
        -
        -   END OF TERMS AND CONDITIONS
        -
        -   APPENDIX: How to apply the Apache License to your work.
        -
        -      To apply the Apache License to your work, attach the following
        -      boilerplate notice, with the fields enclosed by brackets "[]"
        -      replaced with your own identifying information. (Don't include
        -      the brackets!)  The text should be enclosed in the appropriate
        -      comment syntax for the file format. We also recommend that a
        -      file or class name and description of purpose be included on the
        -      same "printed page" as the copyright notice for easier
        -      identification within third-party archives.
        -
        -   Copyright 2023 Jacob Pratt
        -
        -   Licensed under the Apache License, Version 2.0 (the "License");
        -   you may not use this file except in compliance with the License.
        -   You may obtain a copy of the License at
        -
        -       http://www.apache.org/licenses/LICENSE-2.0
        -
        -   Unless required by applicable law or agreed to in writing, software
        -   distributed under the License is distributed on an "AS IS" BASIS,
        -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        -   See the License for the specific language governing permissions and
        -   limitations under the License.
        +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
        +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
        +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
        +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
         
      • @@ -504,7 +295,7 @@ THIS SOFTWARE.

        Apache License 2.0

        Used by:

                                          Apache License
        @@ -714,7 +505,8 @@ THIS SOFTWARE.
                         

        Apache License 2.0

        Used by:

                                          Apache License
        @@ -923,24 +715,18 @@ THIS SOFTWARE.
                         

        Apache License 2.0

        Used by:

        @@ -1151,7 +937,8 @@ THIS SOFTWARE.
                         

        Apache License 2.0

        Used by:

                                          Apache License
        @@ -1363,7 +1150,13 @@ THIS SOFTWARE.
                         

        Apache License 2.0

        Used by:

                                          Apache License
        @@ -1591,34 +1384,316 @@ Software.
                         

        Apache License 2.0

        Used by:

        +
        +                                 Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright [yyyy] [name of copyright owner]
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +
        +Licenses for support code
        +-------------------------
        +
        +Parts of the TLS test suite are under the Go license. This code is not included
        +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so
        +distributing code linked against BoringSSL does not trigger this license:
        +
        +Copyright (c) 2009 The Go Authors. All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions are
        +met:
        +
        +   * Redistributions of source code must retain the above copyright
        +notice, this list of conditions and the following disclaimer.
        +   * Redistributions in binary form must reproduce the above
        +copyright notice, this list of conditions and the following disclaimer
        +in the documentation and/or other materials provided with the
        +distribution.
        +   * Neither the name of Google Inc. nor the names of its
        +contributors may be used to endorse or promote products derived from
        +this software without specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
        +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
        +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
        +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
        +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
        +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
        +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
        +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
        +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
        +BoringSSL uses the Chromium test infrastructure to run a continuous build,
        +trybots etc. The scripts which manage this, and the script for generating build
        +metadata, are under the Chromium license. Distributing code linked against
        +BoringSSL does not trigger this license.
        +
        +Copyright 2015 The Chromium Authors. All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions are
        +met:
        +
        +   * Redistributions of source code must retain the above copyright
        +notice, this list of conditions and the following disclaimer.
        +   * Redistributions in binary form must reproduce the above
        +copyright notice, this list of conditions and the following disclaimer
        +in the documentation and/or other materials provided with the
        +distribution.
        +   * Neither the name of Google Inc. nor the names of its
        +contributors may be used to endorse or promote products derived from
        +this software without specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
        +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
        +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
        +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
        +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
        +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
        +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
        +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
        +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                          Apache License
        @@ -1832,6 +1907,238 @@ This project includes code from Apache Aurora.
         Copyright: 2016 The Apache Software Foundation.
         Home page: https://aurora.apache.org/
         License: http://www.apache.org/licenses/LICENSE-2.0
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        + +
        +                                 Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright [yyyy] [name of copyright owner]
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +--------------------------------------------------------------------------------
        +
        +arrow-array/src/delta.rs: MIT
        +
        +This file is derived from the chronoutil crate. The full MIT license
        +text is in arrow-array/LICENSE-MIT.
         
      • @@ -1839,9 +2146,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0

        Used by:

                                          Apache License
        @@ -2051,7 +2356,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                          Apache License
        @@ -2460,41 +2765,30 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -2703,7 +2997,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -2912,7 +3206,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -3102,7 +3397,425 @@ License: http://www.apache.org/licenses/LICENSE-2.0
               same "printed page" as the copyright notice for easier
               identification within third-party archives.
         
        -   Copyright 2020 - 2025 Tatsuya Kawano
        +   Copyright 2019 TiKV Project Authors.
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        + +
                                         Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright 2020 - 2026 Tatsuya Kawano
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        + +
                                         Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright 2020 Sébastien Crozet
         
            Licensed under the Apache License, Version 2.0 (the "License");
            you may not use this file except in compliance with the License.
        @@ -3122,7 +3835,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -3330,8 +4042,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -3750,7 +4462,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -3959,9 +4671,21 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -4170,7 +4894,456 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

        +
                                         Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright [yyyy] [name of copyright owner]
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +
        +------------------------------------------------------------------------------------
        +This product bundles third-party components under other open source licenses.
        +This section summarizes those components and their licenses. See the referenced
        +license files for text of these licenses.
        +
        +
        +Creative Commons Zero v1.0 Universal
        +------------------------------------
        +
        +bindings/dotnet/.gitignore
        +
        +The above file is derived from VisualStudio.gitignore in
        +https://github.com/github/gitignore. Its license text is in
        +bindings/dotnet/LICENSE-CC0-1.0.txt.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        + +
                                         Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright [yyyy] [name of copyright owner]
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +   
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                         Apache License
                                    Version 2.0, January 2004
        @@ -4379,6 +5552,218 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

        +
                                         Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "{}"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright Individual contributors
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                         Apache License
        @@ -4588,22 +5973,28 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -4813,12 +6204,221 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

        +
                                         Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright 2020 Sébastien Crozet
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                        Apache License
                                    Version 2.0, January 2004
        @@ -5028,7 +6628,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                       Apache License
                                    Version 2.0, January 2004
        @@ -5446,15 +7046,15 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -5664,7 +7264,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -5872,7 +7472,8 @@ limitations under the License.

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -6081,8 +7682,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -6291,7 +7891,6 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
        @@ -6501,7 +8100,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -6691,7 +8290,7 @@ APPENDIX: How to apply the Apache License to your work.
            same "printed page" as the copyright notice for easier
            identification within third-party archives.
         
        -Copyright 2018 The pin-utils authors
        +Copyright 2018 Brian Myers
         
         Licensed under the Apache License, Version 2.0 (the "License");
         you may not use this file except in compliance with the License.
        @@ -6710,8 +8309,8 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -7118,6 +8717,215 @@ You may obtain a copy of the License at
         
            http://www.apache.org/licenses/LICENSE-2.0
         
        +Unless required by applicable law or agreed to in writing, software
        +distributed under the License is distributed on an "AS IS" BASIS,
        +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +See the License for the specific language governing permissions and
        +limitations under the License.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        + +
                                      Apache License
        +                        Version 2.0, January 2004
        +                     http://www.apache.org/licenses/
        +
        +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +1. Definitions.
        +
        +   "License" shall mean the terms and conditions for use, reproduction,
        +   and distribution as defined by Sections 1 through 9 of this document.
        +
        +   "Licensor" shall mean the copyright owner or entity authorized by
        +   the copyright owner that is granting the License.
        +
        +   "Legal Entity" shall mean the union of the acting entity and all
        +   other entities that control, are controlled by, or are under common
        +   control with that entity. For the purposes of this definition,
        +   "control" means (i) the power, direct or indirect, to cause the
        +   direction or management of such entity, whether by contract or
        +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +   outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +   "You" (or "Your") shall mean an individual or Legal Entity
        +   exercising permissions granted by this License.
        +
        +   "Source" form shall mean the preferred form for making modifications,
        +   including but not limited to software source code, documentation
        +   source, and configuration files.
        +
        +   "Object" form shall mean any form resulting from mechanical
        +   transformation or translation of a Source form, including but
        +   not limited to compiled object code, generated documentation,
        +   and conversions to other media types.
        +
        +   "Work" shall mean the work of authorship, whether in Source or
        +   Object form, made available under the License, as indicated by a
        +   copyright notice that is included in or attached to the work
        +   (an example is provided in the Appendix below).
        +
        +   "Derivative Works" shall mean any work, whether in Source or Object
        +   form, that is based on (or derived from) the Work and for which the
        +   editorial revisions, annotations, elaborations, or other modifications
        +   represent, as a whole, an original work of authorship. For the purposes
        +   of this License, Derivative Works shall not include works that remain
        +   separable from, or merely link (or bind by name) to the interfaces of,
        +   the Work and Derivative Works thereof.
        +
        +   "Contribution" shall mean any work of authorship, including
        +   the original version of the Work and any modifications or additions
        +   to that Work or Derivative Works thereof, that is intentionally
        +   submitted to Licensor for inclusion in the Work by the copyright owner
        +   or by an individual or Legal Entity authorized to submit on behalf of
        +   the copyright owner. For the purposes of this definition, "submitted"
        +   means any form of electronic, verbal, or written communication sent
        +   to the Licensor or its representatives, including but not limited to
        +   communication on electronic mailing lists, source code control systems,
        +   and issue tracking systems that are managed by, or on behalf of, the
        +   Licensor for the purpose of discussing and improving the Work, but
        +   excluding communication that is conspicuously marked or otherwise
        +   designated in writing by the copyright owner as "Not a Contribution."
        +
        +   "Contributor" shall mean Licensor and any individual or Legal Entity
        +   on behalf of whom a Contribution has been received by Licensor and
        +   subsequently incorporated within the Work.
        +
        +2. Grant of Copyright License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   copyright license to reproduce, prepare Derivative Works of,
        +   publicly display, publicly perform, sublicense, and distribute the
        +   Work and such Derivative Works in Source or Object form.
        +
        +3. Grant of Patent License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   (except as stated in this section) patent license to make, have made,
        +   use, offer to sell, sell, import, and otherwise transfer the Work,
        +   where such license applies only to those patent claims licensable
        +   by such Contributor that are necessarily infringed by their
        +   Contribution(s) alone or by combination of their Contribution(s)
        +   with the Work to which such Contribution(s) was submitted. If You
        +   institute patent litigation against any entity (including a
        +   cross-claim or counterclaim in a lawsuit) alleging that the Work
        +   or a Contribution incorporated within the Work constitutes direct
        +   or contributory patent infringement, then any patent licenses
        +   granted to You under this License for that Work shall terminate
        +   as of the date such litigation is filed.
        +
        +4. Redistribution. You may reproduce and distribute copies of the
        +   Work or Derivative Works thereof in any medium, with or without
        +   modifications, and in Source or Object form, provided that You
        +   meet the following conditions:
        +
        +   (a) You must give any other recipients of the Work or
        +       Derivative Works a copy of this License; and
        +
        +   (b) You must cause any modified files to carry prominent notices
        +       stating that You changed the files; and
        +
        +   (c) You must retain, in the Source form of any Derivative Works
        +       that You distribute, all copyright, patent, trademark, and
        +       attribution notices from the Source form of the Work,
        +       excluding those notices that do not pertain to any part of
        +       the Derivative Works; and
        +
        +   (d) If the Work includes a "NOTICE" text file as part of its
        +       distribution, then any Derivative Works that You distribute must
        +       include a readable copy of the attribution notices contained
        +       within such NOTICE file, excluding those notices that do not
        +       pertain to any part of the Derivative Works, in at least one
        +       of the following places: within a NOTICE text file distributed
        +       as part of the Derivative Works; within the Source form or
        +       documentation, if provided along with the Derivative Works; or,
        +       within a display generated by the Derivative Works, if and
        +       wherever such third-party notices normally appear. The contents
        +       of the NOTICE file are for informational purposes only and
        +       do not modify the License. You may add Your own attribution
        +       notices within Derivative Works that You distribute, alongside
        +       or as an addendum to the NOTICE text from the Work, provided
        +       that such additional attribution notices cannot be construed
        +       as modifying the License.
        +
        +   You may add Your own copyright statement to Your modifications and
        +   may provide additional or different license terms and conditions
        +   for use, reproduction, or distribution of Your modifications, or
        +   for any such Derivative Works as a whole, provided Your use,
        +   reproduction, and distribution of the Work otherwise complies with
        +   the conditions stated in this License.
        +
        +5. Submission of Contributions. Unless You explicitly state otherwise,
        +   any Contribution intentionally submitted for inclusion in the Work
        +   by You to the Licensor shall be under the terms and conditions of
        +   this License, without any additional terms or conditions.
        +   Notwithstanding the above, nothing herein shall supersede or modify
        +   the terms of any separate license agreement you may have executed
        +   with Licensor regarding such Contributions.
        +
        +6. Trademarks. This License does not grant permission to use the trade
        +   names, trademarks, service marks, or product names of the Licensor,
        +   except as required for reasonable and customary use in describing the
        +   origin of the Work and reproducing the content of the NOTICE file.
        +
        +7. Disclaimer of Warranty. Unless required by applicable law or
        +   agreed to in writing, Licensor provides the Work (and each
        +   Contributor provides its Contributions) on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +   implied, including, without limitation, any warranties or conditions
        +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +   PARTICULAR PURPOSE. You are solely responsible for determining the
        +   appropriateness of using or redistributing the Work and assume any
        +   risks associated with Your exercise of permissions under this License.
        +
        +8. Limitation of Liability. In no event and under no legal theory,
        +   whether in tort (including negligence), contract, or otherwise,
        +   unless required by applicable law (such as deliberate and grossly
        +   negligent acts) or agreed to in writing, shall any Contributor be
        +   liable to You for damages, including any direct, indirect, special,
        +   incidental, or consequential damages of any character arising as a
        +   result of this License or out of the use or inability to use the
        +   Work (including but not limited to damages for loss of goodwill,
        +   work stoppage, computer failure or malfunction, or any and all
        +   other commercial damages or losses), even if such Contributor
        +   has been advised of the possibility of such damages.
        +
        +9. Accepting Warranty or Additional Liability. While redistributing
        +   the Work or Derivative Works thereof, You may choose to offer,
        +   and charge a fee for, acceptance of support, warranty, indemnity,
        +   or other liability obligations and/or rights consistent with this
        +   License. However, in accepting such obligations, You may act only
        +   on Your own behalf and on Your sole responsibility, not on behalf
        +   of any other Contributor, and only if You agree to indemnify,
        +   defend, and hold each Contributor harmless for any liability
        +   incurred by, or claims asserted against, such Contributor by reason
        +   of your accepting any such warranty or additional liability.
        +
        +END OF TERMS AND CONDITIONS
        +
        +APPENDIX: How to apply the Apache License to your work.
        +
        +   To apply the Apache License to your work, attach the following
        +   boilerplate notice, with the fields enclosed by brackets "[]"
        +   replaced with your own identifying information. (Don't include
        +   the brackets!)  The text should be enclosed in the appropriate
        +   comment syntax for the file format. We also recommend that a
        +   file or class name and description of purpose be included on the
        +   same "printed page" as the copyright notice for easier
        +   identification within third-party archives.
        +
        +Copyright 2019 quininer kel
        +
        +Licensed under the Apache License, Version 2.0 (the "License");
        +you may not use this file except in compliance with the License.
        +You may obtain a copy of the License at
        +
        +	http://www.apache.org/licenses/LICENSE-2.0
        +
         Unless required by applicable law or agreed to in writing, software
         distributed under the License is distributed on an "AS IS" BASIS,
         WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -7130,7 +8938,9 @@ limitations under the License.
                         

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -7340,7 +9150,7 @@ limitations under the License.
                         

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -7758,7 +9568,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -7967,7 +9777,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -8178,7 +9988,216 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        +
                                      Apache License
        +                        Version 2.0, January 2004
        +                     http://www.apache.org/licenses/
        +
        +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +1. Definitions.
        +
        +   "License" shall mean the terms and conditions for use, reproduction,
        +   and distribution as defined by Sections 1 through 9 of this document.
        +
        +   "Licensor" shall mean the copyright owner or entity authorized by
        +   the copyright owner that is granting the License.
        +
        +   "Legal Entity" shall mean the union of the acting entity and all
        +   other entities that control, are controlled by, or are under common
        +   control with that entity. For the purposes of this definition,
        +   "control" means (i) the power, direct or indirect, to cause the
        +   direction or management of such entity, whether by contract or
        +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +   outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +   "You" (or "Your") shall mean an individual or Legal Entity
        +   exercising permissions granted by this License.
        +
        +   "Source" form shall mean the preferred form for making modifications,
        +   including but not limited to software source code, documentation
        +   source, and configuration files.
        +
        +   "Object" form shall mean any form resulting from mechanical
        +   transformation or translation of a Source form, including but
        +   not limited to compiled object code, generated documentation,
        +   and conversions to other media types.
        +
        +   "Work" shall mean the work of authorship, whether in Source or
        +   Object form, made available under the License, as indicated by a
        +   copyright notice that is included in or attached to the work
        +   (an example is provided in the Appendix below).
        +
        +   "Derivative Works" shall mean any work, whether in Source or Object
        +   form, that is based on (or derived from) the Work and for which the
        +   editorial revisions, annotations, elaborations, or other modifications
        +   represent, as a whole, an original work of authorship. For the purposes
        +   of this License, Derivative Works shall not include works that remain
        +   separable from, or merely link (or bind by name) to the interfaces of,
        +   the Work and Derivative Works thereof.
        +
        +   "Contribution" shall mean any work of authorship, including
        +   the original version of the Work and any modifications or additions
        +   to that Work or Derivative Works thereof, that is intentionally
        +   submitted to Licensor for inclusion in the Work by the copyright owner
        +   or by an individual or Legal Entity authorized to submit on behalf of
        +   the copyright owner. For the purposes of this definition, "submitted"
        +   means any form of electronic, verbal, or written communication sent
        +   to the Licensor or its representatives, including but not limited to
        +   communication on electronic mailing lists, source code control systems,
        +   and issue tracking systems that are managed by, or on behalf of, the
        +   Licensor for the purpose of discussing and improving the Work, but
        +   excluding communication that is conspicuously marked or otherwise
        +   designated in writing by the copyright owner as "Not a Contribution."
        +
        +   "Contributor" shall mean Licensor and any individual or Legal Entity
        +   on behalf of whom a Contribution has been received by Licensor and
        +   subsequently incorporated within the Work.
        +
        +2. Grant of Copyright License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   copyright license to reproduce, prepare Derivative Works of,
        +   publicly display, publicly perform, sublicense, and distribute the
        +   Work and such Derivative Works in Source or Object form.
        +
        +3. Grant of Patent License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   (except as stated in this section) patent license to make, have made,
        +   use, offer to sell, sell, import, and otherwise transfer the Work,
        +   where such license applies only to those patent claims licensable
        +   by such Contributor that are necessarily infringed by their
        +   Contribution(s) alone or by combination of their Contribution(s)
        +   with the Work to which such Contribution(s) was submitted. If You
        +   institute patent litigation against any entity (including a
        +   cross-claim or counterclaim in a lawsuit) alleging that the Work
        +   or a Contribution incorporated within the Work constitutes direct
        +   or contributory patent infringement, then any patent licenses
        +   granted to You under this License for that Work shall terminate
        +   as of the date such litigation is filed.
        +
        +4. Redistribution. You may reproduce and distribute copies of the
        +   Work or Derivative Works thereof in any medium, with or without
        +   modifications, and in Source or Object form, provided that You
        +   meet the following conditions:
        +
        +   (a) You must give any other recipients of the Work or
        +       Derivative Works a copy of this License; and
        +
        +   (b) You must cause any modified files to carry prominent notices
        +       stating that You changed the files; and
        +
        +   (c) You must retain, in the Source form of any Derivative Works
        +       that You distribute, all copyright, patent, trademark, and
        +       attribution notices from the Source form of the Work,
        +       excluding those notices that do not pertain to any part of
        +       the Derivative Works; and
        +
        +   (d) If the Work includes a "NOTICE" text file as part of its
        +       distribution, then any Derivative Works that You distribute must
        +       include a readable copy of the attribution notices contained
        +       within such NOTICE file, excluding those notices that do not
        +       pertain to any part of the Derivative Works, in at least one
        +       of the following places: within a NOTICE text file distributed
        +       as part of the Derivative Works; within the Source form or
        +       documentation, if provided along with the Derivative Works; or,
        +       within a display generated by the Derivative Works, if and
        +       wherever such third-party notices normally appear. The contents
        +       of the NOTICE file are for informational purposes only and
        +       do not modify the License. You may add Your own attribution
        +       notices within Derivative Works that You distribute, alongside
        +       or as an addendum to the NOTICE text from the Work, provided
        +       that such additional attribution notices cannot be construed
        +       as modifying the License.
        +
        +   You may add Your own copyright statement to Your modifications and
        +   may provide additional or different license terms and conditions
        +   for use, reproduction, or distribution of Your modifications, or
        +   for any such Derivative Works as a whole, provided Your use,
        +   reproduction, and distribution of the Work otherwise complies with
        +   the conditions stated in this License.
        +
        +5. Submission of Contributions. Unless You explicitly state otherwise,
        +   any Contribution intentionally submitted for inclusion in the Work
        +   by You to the Licensor shall be under the terms and conditions of
        +   this License, without any additional terms or conditions.
        +   Notwithstanding the above, nothing herein shall supersede or modify
        +   the terms of any separate license agreement you may have executed
        +   with Licensor regarding such Contributions.
        +
        +6. Trademarks. This License does not grant permission to use the trade
        +   names, trademarks, service marks, or product names of the Licensor,
        +   except as required for reasonable and customary use in describing the
        +   origin of the Work and reproducing the content of the NOTICE file.
        +
        +7. Disclaimer of Warranty. Unless required by applicable law or
        +   agreed to in writing, Licensor provides the Work (and each
        +   Contributor provides its Contributions) on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +   implied, including, without limitation, any warranties or conditions
        +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +   PARTICULAR PURPOSE. You are solely responsible for determining the
        +   appropriateness of using or redistributing the Work and assume any
        +   risks associated with Your exercise of permissions under this License.
        +
        +8. Limitation of Liability. In no event and under no legal theory,
        +   whether in tort (including negligence), contract, or otherwise,
        +   unless required by applicable law (such as deliberate and grossly
        +   negligent acts) or agreed to in writing, shall any Contributor be
        +   liable to You for damages, including any direct, indirect, special,
        +   incidental, or consequential damages of any character arising as a
        +   result of this License or out of the use or inability to use the
        +   Work (including but not limited to damages for loss of goodwill,
        +   work stoppage, computer failure or malfunction, or any and all
        +   other commercial damages or losses), even if such Contributor
        +   has been advised of the possibility of such damages.
        +
        +9. Accepting Warranty or Additional Liability. While redistributing
        +   the Work or Derivative Works thereof, You may choose to offer,
        +   and charge a fee for, acceptance of support, warranty, indemnity,
        +   or other liability obligations and/or rights consistent with this
        +   License. However, in accepting such obligations, You may act only
        +   on Your own behalf and on Your sole responsibility, not on behalf
        +   of any other Contributor, and only if You agree to indemnify,
        +   defend, and hold each Contributor harmless for any liability
        +   incurred by, or claims asserted against, such Contributor by reason
        +   of your accepting any such warranty or additional liability.
        +
        +END OF TERMS AND CONDITIONS
        +
        +APPENDIX: How to apply the Apache License to your work.
        +
        +   To apply the Apache License to your work, attach the following
        +   boilerplate notice, with the fields enclosed by brackets "[]"
        +   replaced with your own identifying information. (Don't include
        +   the brackets!)  The text should be enclosed in the appropriate
        +   comment syntax for the file format. We also recommend that a
        +   file or class name and description of purpose be included on the
        +   same "printed page" as the copyright notice for easier
        +   identification within third-party archives.
        +
        +Copyright 2024 Liam Gray <gmail@liamg.me>
        +
        +Licensed under the Apache License, Version 2.0 (the "License");
        +you may not use this file except in compliance with the License.
        +You may obtain a copy of the License at
        +
        +	http://www.apache.org/licenses/LICENSE-2.0
        +
        +Unless required by applicable law or agreed to in writing, software
        +distributed under the License is distributed on an "AS IS" BASIS,
        +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +See the License for the specific language governing permissions and
        +limitations under the License.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                      Apache License
                                 Version 2.0, January 2004
        @@ -8388,7 +10407,8 @@ limitations under the License.
                         

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -8596,150 +10616,170 @@ limitations under the License.

        Apache License 2.0

        Used by:

          +
        • addr2line 0.25.1
        • ahash 0.8.12
        • -
        • arc-swap 1.7.1
        • -
        • arrayvec 0.7.6
        • +
        • arc-swap 1.9.3
        • +
        • arrayvec 0.7.8
        • async-channel 2.5.0
        • -
        • async-compression 0.4.19
        • -
        • async-lock 3.4.1
        • +
        • async-compression 0.4.42
        • +
        • async-lock 3.4.2
        • atomic-waker 1.1.2
        • autocfg 1.5.0
        • -
        • base64 0.21.7
        • +
        • backtrace 0.3.76
        • base64 0.22.1
        • -
        • bitflags 2.9.4
        • -
        • bumpalo 3.19.0
        • +
        • base64 0.23.1
        • +
        • bitflags 1.3.2
        • +
        • bitflags 2.11.1
        • +
        • bstr 1.12.1
        • +
        • bumpalo 3.20.2
        • bytes-utils 0.1.4
        • -
        • cc 1.2.40
        • -
        • cfg-if 1.0.3
        • +
        • cast 0.3.0
        • +
        • cc 1.2.62
        • +
        • cfg-if 0.1.10
        • +
        • cfg-if 1.0.4
        • +
        • cmake 0.1.58
        • +
        • compression-codecs 0.4.38
        • +
        • compression-core 0.4.32
        • concurrent-queue 2.5.0
        • const-random-macro 0.1.16
        • const-random 0.1.18
        • core-foundation-sys 0.8.7
        • core-foundation 0.10.1
        • core-foundation 0.9.4
        • +
        • cpp_demangle 0.4.5
        • +
        • criterion-plot 0.8.2
        • +
        • criterion 0.8.2
        • crossbeam-channel 0.5.15
        • crossbeam-deque 0.8.6
        • -
        • crossbeam-epoch 0.9.18
        • +
        • crossbeam-epoch 0.9.20
        • crossbeam-queue 0.3.12
        • +
        • crossbeam-skiplist 0.1.3
        • crossbeam-utils 0.8.21
        • +
        • debugid 0.8.0
        • displaydoc 0.2.5
        • either 1.15.0
        • +
        • encoding_rs_io 0.1.7
        • equivalent 1.0.2
        • errno 0.3.14
        • event-listener-strategy 0.5.4
        • -
        • event-listener 5.4.1
        • -
        • fastrand 2.3.0
        • -
        • find-msvc-tools 0.1.3
        • +
        • event-listener 5.4.2
        • +
        • fastrand 2.4.1
        • +
        • find-msvc-tools 0.1.9
        • +
        • findshlibs 0.10.2
        • fixedbitset 0.5.7
        • +
        • flate2 1.1.9
        • fnv 1.0.7
        • form_urlencoded 1.2.2
        • -
        • fs4 0.8.4
        • +
        • foyer-intrusive-collections 0.10.0-dev
        • +
        • fs4 0.13.1
        • futures-timer 3.0.3
        • -
        • geohash 0.13.1
        • +
        • geohash 0.13.2
        • +
        • gimli 0.32.3
        • glob 0.3.3
        • -
        • group 0.12.1
        • +
        • group 0.14.0
        • hash32 0.3.1
        • hashbrown 0.14.5
        • hashbrown 0.15.5
        • -
        • hashbrown 0.16.0
        • +
        • hashbrown 0.16.1
        • +
        • hashbrown 0.17.1
        • heapless 0.8.0
        • heck 0.5.0
        • hermit-abi 0.5.2
        • httparse 1.10.1
        • -
        • hyper-rustls 0.24.2
        • -
        • hyper-rustls 0.27.7
        • +
        • hyper-rustls 0.27.9
        • +
        • hyper-timeout 0.5.2
        • idna 1.1.0
        • -
        • idna_adapter 1.2.1
        • -
        • indexmap 2.12.0
        • -
        • itertools 0.11.0
        • +
        • idna_adapter 1.2.2
        • +
        • indexmap 2.14.0
        • itertools 0.13.0
        • itertools 0.14.0
        • +
        • itertools 0.15.0
        • jobserver 0.1.34
        • -
        • js-sys 0.3.81
        • +
        • js-sys 0.3.107
        • lazy_static 1.5.0
        • -
        • linux-raw-sys 0.11.0
        • -
        • linux-raw-sys 0.4.15
        • +
        • linux-raw-sys 0.12.1
        • lock_api 0.4.14
        • -
        • log 0.4.28
        • +
        • log 0.4.34
        • matrixmultiply 0.3.10
        • mime 0.3.17
        • -
        • multimap 0.10.1
        • ndarray 0.16.1
        • -
        • num-bigint-dig 0.8.4
        • +
        • num-bigint-dig 0.8.6
        • num-bigint 0.4.6
        • +
        • num-bigint 0.5.1
        • num-complex 0.4.6
        • num-integer 0.1.46
        • num-iter 0.1.45
        • +
        • num-rational 0.4.2
        • num-traits 0.2.19
        • num_cpus 1.17.0
        • -
        • once_cell 1.21.3
        • -
        • openssl-probe 0.1.6
        • +
        • oauth2 5.0.0
        • +
        • object 0.37.3
        • +
        • once_cell 1.21.4
        • +
        • openssl-probe 0.2.1
        • parking 2.2.1
        • parking_lot 0.12.5
        • parking_lot_core 0.9.12
        • percent-encoding 2.3.2
        • petgraph 0.8.3
        • -
        • pkg-config 0.3.32
        • -
        • prost-build 0.14.3
        • -
        • prost-derive 0.14.3
        • +
        • pkg-config 0.3.33
        • +
        • prost-derive 0.14.4
        • prost-types 0.14.3
        • -
        • prost 0.14.3
        • +
        • prost 0.14.4
        • +
        • rand_xoshiro 0.6.0
        • rawpointer 0.2.1
        • rayon-core 1.13.0
        • -
        • rayon 1.11.0
        • -
        • regex-automata 0.4.13
        • -
        • regex-lite 0.1.7
        • -
        • regex-syntax 0.8.6
        • -
        • regex 1.12.2
        • +
        • rayon 1.12.0
        • +
        • regex-automata 0.4.16
        • +
        • regex-lite 0.1.9
        • +
        • regex-syntax 0.8.11
        • +
        • regex 1.13.1
        • ring 0.17.14
        • +
        • roaring 0.11.5
        • robust 1.2.0
        • +
        • rustc-demangle 0.1.27
        • rustc_version 0.4.1
        • -
        • rustix 0.38.44
        • -
        • rustix 1.1.2
        • -
        • rustls-native-certs 0.6.3
        • -
        • rustls-native-certs 0.8.1
        • -
        • rustls-pemfile 1.0.4
        • -
        • rustls-pemfile 2.2.0
        • -
        • rustls 0.21.12
        • -
        • rustls 0.23.31
        • +
        • rustix 1.1.4
        • +
        • rustls-native-certs 0.8.3
        • +
        • rustls 0.23.46
        • scoped-tls 1.0.1
        • scopeguard 1.2.0
        • -
        • sct 0.7.1
        • -
        • security-framework-sys 2.15.0
        • -
        • security-framework 2.11.1
        • -
        • security-framework 3.5.1
        • -
        • serde_with 3.15.0
        • -
        • serde_with_macros 3.15.0
        • -
        • shellexpand 3.1.1
        • -
        • signal-hook-registry 1.4.6
        • -
        • smallvec 1.15.1
        • -
        • socket2 0.5.10
        • -
        • socket2 0.6.0
        • -
        • sqlparser 0.59.0
        • -
        • sqlparser_derive 0.3.0
        • -
        • stable_deref_trait 1.2.0
        • -
        • syn 1.0.109
        • +
        • security-framework-sys 2.17.0
        • +
        • security-framework 3.7.0
        • +
        • serde_with 3.24.0
        • +
        • serde_with_macros 3.24.0
        • +
        • shellexpand 3.1.2
        • +
        • signal-hook-registry 1.4.8
        • +
        • simd_cesu8 1.1.1
        • +
        • smallvec 1.16.5
        • +
        • socket2 0.6.3
        • +
        • sqlparser 0.62.0
        • +
        • sqlparser_derive 0.5.0
        • +
        • stable_deref_trait 1.2.1
        • +
        • str_stack 0.1.1
        • +
        • symlink 0.1.0
        • system-configuration-sys 0.6.0
        • -
        • system-configuration 0.6.1
        • -
        • tempfile 3.23.0
        • +
        • system-configuration 0.7.0
        • +
        • tempfile 3.27.0
        • thread-tree 0.3.3
        • -
        • thread_local 1.1.9
        • -
        • unicase 2.8.1
        • -
        • unicode-segmentation 1.12.0
        • -
        • unicode-width 0.2.2
        • -
        • url 2.5.7
        • -
        • uuid 1.18.1
        • +
        • thread_local 1.1.10
        • +
        • tinytemplate 1.2.1
        • +
        • unicase 2.9.0
        • +
        • unicode-normalization 0.1.25
        • +
        • unicode-segmentation 1.13.2
        • +
        • unicode-width 0.2.3
        • +
        • url 2.5.8
        • +
        • uuid 1.29.0
        • version_check 0.9.5
        • wasi 0.11.1+wasi-snapshot-preview1
        • wasi 0.14.7+wasi-0.2.4
        • -
        • wasm-bindgen-backend 0.2.104
        • -
        • wasm-bindgen-futures 0.4.54
        • -
        • wasm-bindgen-macro-support 0.2.104
        • -
        • wasm-bindgen-macro 0.2.104
        • -
        • wasm-bindgen-shared 0.2.104
        • -
        • wasm-bindgen 0.2.104
        • -
        • web-sys 0.3.81
        • -
        • wit-bindgen 0.46.0
        • +
        • wasip2 1.0.3+wasi-0.2.9
        • +
        • wasm-bindgen-futures 0.4.80
        • +
        • wasm-bindgen-macro-support 0.2.130
        • +
        • wasm-bindgen-macro 0.2.130
        • +
        • wasm-bindgen-shared 0.2.130
        • +
        • wasm-bindgen 0.2.130
        • +
        • web-sys 0.3.107
        • +
        • wit-bindgen 0.57.1
        • wkb 0.9.2
        • wkt 0.14.0
        • xmlparser 0.13.6
        • @@ -8951,7 +10991,7 @@ limitations under the License.

          Apache License 2.0

          Used by:

                                        Apache License
                                   Version 2.0, January 2004
          @@ -9161,14 +11201,14 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

                                        Apache License
                                   Version 2.0, January 2004
          @@ -9378,41 +11418,56 @@ limitations under the License.
                           

          Used by:

                                        Apache License
                                   Version 2.0, January 2004
          @@ -9621,10 +11676,209 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

          +
                                        Apache License
          +                        Version 2.0, January 2004
          +                     http://www.apache.org/licenses/
          +
          +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
          +
          +1. Definitions.
          +
          +   "License" shall mean the terms and conditions for use, reproduction,
          +   and distribution as defined by Sections 1 through 9 of this document.
          +
          +   "Licensor" shall mean the copyright owner or entity authorized by
          +   the copyright owner that is granting the License.
          +
          +   "Legal Entity" shall mean the union of the acting entity and all
          +   other entities that control, are controlled by, or are under common
          +   control with that entity. For the purposes of this definition,
          +   "control" means (i) the power, direct or indirect, to cause the
          +   direction or management of such entity, whether by contract or
          +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
          +   outstanding shares, or (iii) beneficial ownership of such entity.
          +
          +   "You" (or "Your") shall mean an individual or Legal Entity
          +   exercising permissions granted by this License.
          +
          +   "Source" form shall mean the preferred form for making modifications,
          +   including but not limited to software source code, documentation
          +   source, and configuration files.
          +
          +   "Object" form shall mean any form resulting from mechanical
          +   transformation or translation of a Source form, including but
          +   not limited to compiled object code, generated documentation,
          +   and conversions to other media types.
          +
          +   "Work" shall mean the work of authorship, whether in Source or
          +   Object form, made available under the License, as indicated by a
          +   copyright notice that is included in or attached to the work
          +   (an example is provided in the Appendix below).
          +
          +   "Derivative Works" shall mean any work, whether in Source or Object
          +   form, that is based on (or derived from) the Work and for which the
          +   editorial revisions, annotations, elaborations, or other modifications
          +   represent, as a whole, an original work of authorship. For the purposes
          +   of this License, Derivative Works shall not include works that remain
          +   separable from, or merely link (or bind by name) to the interfaces of,
          +   the Work and Derivative Works thereof.
          +
          +   "Contribution" shall mean any work of authorship, including
          +   the original version of the Work and any modifications or additions
          +   to that Work or Derivative Works thereof, that is intentionally
          +   submitted to Licensor for inclusion in the Work by the copyright owner
          +   or by an individual or Legal Entity authorized to submit on behalf of
          +   the copyright owner. For the purposes of this definition, "submitted"
          +   means any form of electronic, verbal, or written communication sent
          +   to the Licensor or its representatives, including but not limited to
          +   communication on electronic mailing lists, source code control systems,
          +   and issue tracking systems that are managed by, or on behalf of, the
          +   Licensor for the purpose of discussing and improving the Work, but
          +   excluding communication that is conspicuously marked or otherwise
          +   designated in writing by the copyright owner as "Not a Contribution."
          +
          +   "Contributor" shall mean Licensor and any individual or Legal Entity
          +   on behalf of whom a Contribution has been received by Licensor and
          +   subsequently incorporated within the Work.
          +
          +2. Grant of Copyright License. Subject to the terms and conditions of
          +   this License, each Contributor hereby grants to You a perpetual,
          +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          +   copyright license to reproduce, prepare Derivative Works of,
          +   publicly display, publicly perform, sublicense, and distribute the
          +   Work and such Derivative Works in Source or Object form.
          +
          +3. Grant of Patent License. Subject to the terms and conditions of
          +   this License, each Contributor hereby grants to You a perpetual,
          +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          +   (except as stated in this section) patent license to make, have made,
          +   use, offer to sell, sell, import, and otherwise transfer the Work,
          +   where such license applies only to those patent claims licensable
          +   by such Contributor that are necessarily infringed by their
          +   Contribution(s) alone or by combination of their Contribution(s)
          +   with the Work to which such Contribution(s) was submitted. If You
          +   institute patent litigation against any entity (including a
          +   cross-claim or counterclaim in a lawsuit) alleging that the Work
          +   or a Contribution incorporated within the Work constitutes direct
          +   or contributory patent infringement, then any patent licenses
          +   granted to You under this License for that Work shall terminate
          +   as of the date such litigation is filed.
          +
          +4. Redistribution. You may reproduce and distribute copies of the
          +   Work or Derivative Works thereof in any medium, with or without
          +   modifications, and in Source or Object form, provided that You
          +   meet the following conditions:
          +
          +   (a) You must give any other recipients of the Work or
          +       Derivative Works a copy of this License; and
          +
          +   (b) You must cause any modified files to carry prominent notices
          +       stating that You changed the files; and
          +
          +   (c) You must retain, in the Source form of any Derivative Works
          +       that You distribute, all copyright, patent, trademark, and
          +       attribution notices from the Source form of the Work,
          +       excluding those notices that do not pertain to any part of
          +       the Derivative Works; and
          +
          +   (d) If the Work includes a "NOTICE" text file as part of its
          +       distribution, then any Derivative Works that You distribute must
          +       include a readable copy of the attribution notices contained
          +       within such NOTICE file, excluding those notices that do not
          +       pertain to any part of the Derivative Works, in at least one
          +       of the following places: within a NOTICE text file distributed
          +       as part of the Derivative Works; within the Source form or
          +       documentation, if provided along with the Derivative Works; or,
          +       within a display generated by the Derivative Works, if and
          +       wherever such third-party notices normally appear. The contents
          +       of the NOTICE file are for informational purposes only and
          +       do not modify the License. You may add Your own attribution
          +       notices within Derivative Works that You distribute, alongside
          +       or as an addendum to the NOTICE text from the Work, provided
          +       that such additional attribution notices cannot be construed
          +       as modifying the License.
          +
          +   You may add Your own copyright statement to Your modifications and
          +   may provide additional or different license terms and conditions
          +   for use, reproduction, or distribution of Your modifications, or
          +   for any such Derivative Works as a whole, provided Your use,
          +   reproduction, and distribution of the Work otherwise complies with
          +   the conditions stated in this License.
          +
          +5. Submission of Contributions. Unless You explicitly state otherwise,
          +   any Contribution intentionally submitted for inclusion in the Work
          +   by You to the Licensor shall be under the terms and conditions of
          +   this License, without any additional terms or conditions.
          +   Notwithstanding the above, nothing herein shall supersede or modify
          +   the terms of any separate license agreement you may have executed
          +   with Licensor regarding such Contributions.
          +
          +6. Trademarks. This License does not grant permission to use the trade
          +   names, trademarks, service marks, or product names of the Licensor,
          +   except as required for reasonable and customary use in describing the
          +   origin of the Work and reproducing the content of the NOTICE file.
          +
          +7. Disclaimer of Warranty. Unless required by applicable law or
          +   agreed to in writing, Licensor provides the Work (and each
          +   Contributor provides its Contributions) on an "AS IS" BASIS,
          +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
          +   implied, including, without limitation, any warranties or conditions
          +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
          +   PARTICULAR PURPOSE. You are solely responsible for determining the
          +   appropriateness of using or redistributing the Work and assume any
          +   risks associated with Your exercise of permissions under this License.
          +
          +8. Limitation of Liability. In no event and under no legal theory,
          +   whether in tort (including negligence), contract, or otherwise,
          +   unless required by applicable law (such as deliberate and grossly
          +   negligent acts) or agreed to in writing, shall any Contributor be
          +   liable to You for damages, including any direct, indirect, special,
          +   incidental, or consequential damages of any character arising as a
          +   result of this License or out of the use or inability to use the
          +   Work (including but not limited to damages for loss of goodwill,
          +   work stoppage, computer failure or malfunction, or any and all
          +   other commercial damages or losses), even if such Contributor
          +   has been advised of the possibility of such damages.
          +
          +9. Accepting Warranty or Additional Liability. While redistributing
          +   the Work or Derivative Works thereof, You may choose to offer,
          +   and charge a fee for, acceptance of support, warranty, indemnity,
          +   or other liability obligations and/or rights consistent with this
          +   License. However, in accepting such obligations, You may act only
          +   on Your own behalf and on Your sole responsibility, not on behalf
          +   of any other Contributor, and only if You agree to indemnify,
          +   defend, and hold each Contributor harmless for any liability
          +   incurred by, or claims asserted against, such Contributor by reason
          +   of your accepting any such warranty or additional liability.
          +
          +END OF TERMS AND CONDITIONS
          +
          +Copyright (c) 2015-2022 Amod Malviya
          +
          +Licensed under the Apache License, Version 2.0 (the "License");
          +you may not use this file except in compliance with the License.
          +You may obtain a copy of the License at
          +
          +	http://www.apache.org/licenses/LICENSE-2.0
          +
          +Unless required by applicable law or agreed to in writing, software
          +distributed under the License is distributed on an "AS IS" BASIS,
          +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
          +See the License for the specific language governing permissions and
          +limitations under the License.
          +
          + +
        • +

          Apache License 2.0

          +

          Used by:

          +
                                        Apache License
                                   Version 2.0, January 2004
          @@ -9819,11 +12073,13 @@ APPENDIX: How to apply the Apache License to your work.
                           

          Apache License 2.0

          Used by:

                                        Apache License
                                   Version 2.0, January 2004
          @@ -10032,8 +12288,7 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

                                        Apache License
                                   Version 2.0, January 2004
          @@ -10242,7 +12497,217 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

          +
                                        Apache License
          +                        Version 2.0, January 2004
          +                     http://www.apache.org/licenses/
          +
          +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
          +
          +1. Definitions.
          +
          +   "License" shall mean the terms and conditions for use, reproduction,
          +   and distribution as defined by Sections 1 through 9 of this document.
          +
          +   "Licensor" shall mean the copyright owner or entity authorized by
          +   the copyright owner that is granting the License.
          +
          +   "Legal Entity" shall mean the union of the acting entity and all
          +   other entities that control, are controlled by, or are under common
          +   control with that entity. For the purposes of this definition,
          +   "control" means (i) the power, direct or indirect, to cause the
          +   direction or management of such entity, whether by contract or
          +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
          +   outstanding shares, or (iii) beneficial ownership of such entity.
          +
          +   "You" (or "Your") shall mean an individual or Legal Entity
          +   exercising permissions granted by this License.
          +
          +   "Source" form shall mean the preferred form for making modifications,
          +   including but not limited to software source code, documentation
          +   source, and configuration files.
          +
          +   "Object" form shall mean any form resulting from mechanical
          +   transformation or translation of a Source form, including but
          +   not limited to compiled object code, generated documentation,
          +   and conversions to other media types.
          +
          +   "Work" shall mean the work of authorship, whether in Source or
          +   Object form, made available under the License, as indicated by a
          +   copyright notice that is included in or attached to the work
          +   (an example is provided in the Appendix below).
          +
          +   "Derivative Works" shall mean any work, whether in Source or Object
          +   form, that is based on (or derived from) the Work and for which the
          +   editorial revisions, annotations, elaborations, or other modifications
          +   represent, as a whole, an original work of authorship. For the purposes
          +   of this License, Derivative Works shall not include works that remain
          +   separable from, or merely link (or bind by name) to the interfaces of,
          +   the Work and Derivative Works thereof.
          +
          +   "Contribution" shall mean any work of authorship, including
          +   the original version of the Work and any modifications or additions
          +   to that Work or Derivative Works thereof, that is intentionally
          +   submitted to Licensor for inclusion in the Work by the copyright owner
          +   or by an individual or Legal Entity authorized to submit on behalf of
          +   the copyright owner. For the purposes of this definition, "submitted"
          +   means any form of electronic, verbal, or written communication sent
          +   to the Licensor or its representatives, including but not limited to
          +   communication on electronic mailing lists, source code control systems,
          +   and issue tracking systems that are managed by, or on behalf of, the
          +   Licensor for the purpose of discussing and improving the Work, but
          +   excluding communication that is conspicuously marked or otherwise
          +   designated in writing by the copyright owner as "Not a Contribution."
          +
          +   "Contributor" shall mean Licensor and any individual or Legal Entity
          +   on behalf of whom a Contribution has been received by Licensor and
          +   subsequently incorporated within the Work.
          +
          +2. Grant of Copyright License. Subject to the terms and conditions of
          +   this License, each Contributor hereby grants to You a perpetual,
          +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          +   copyright license to reproduce, prepare Derivative Works of,
          +   publicly display, publicly perform, sublicense, and distribute the
          +   Work and such Derivative Works in Source or Object form.
          +
          +3. Grant of Patent License. Subject to the terms and conditions of
          +   this License, each Contributor hereby grants to You a perpetual,
          +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          +   (except as stated in this section) patent license to make, have made,
          +   use, offer to sell, sell, import, and otherwise transfer the Work,
          +   where such license applies only to those patent claims licensable
          +   by such Contributor that are necessarily infringed by their
          +   Contribution(s) alone or by combination of their Contribution(s)
          +   with the Work to which such Contribution(s) was submitted. If You
          +   institute patent litigation against any entity (including a
          +   cross-claim or counterclaim in a lawsuit) alleging that the Work
          +   or a Contribution incorporated within the Work constitutes direct
          +   or contributory patent infringement, then any patent licenses
          +   granted to You under this License for that Work shall terminate
          +   as of the date such litigation is filed.
          +
          +4. Redistribution. You may reproduce and distribute copies of the
          +   Work or Derivative Works thereof in any medium, with or without
          +   modifications, and in Source or Object form, provided that You
          +   meet the following conditions:
          +
          +   (a) You must give any other recipients of the Work or
          +       Derivative Works a copy of this License; and
          +
          +   (b) You must cause any modified files to carry prominent notices
          +       stating that You changed the files; and
          +
          +   (c) You must retain, in the Source form of any Derivative Works
          +       that You distribute, all copyright, patent, trademark, and
          +       attribution notices from the Source form of the Work,
          +       excluding those notices that do not pertain to any part of
          +       the Derivative Works; and
          +
          +   (d) If the Work includes a "NOTICE" text file as part of its
          +       distribution, then any Derivative Works that You distribute must
          +       include a readable copy of the attribution notices contained
          +       within such NOTICE file, excluding those notices that do not
          +       pertain to any part of the Derivative Works, in at least one
          +       of the following places: within a NOTICE text file distributed
          +       as part of the Derivative Works; within the Source form or
          +       documentation, if provided along with the Derivative Works; or,
          +       within a display generated by the Derivative Works, if and
          +       wherever such third-party notices normally appear. The contents
          +       of the NOTICE file are for informational purposes only and
          +       do not modify the License. You may add Your own attribution
          +       notices within Derivative Works that You distribute, alongside
          +       or as an addendum to the NOTICE text from the Work, provided
          +       that such additional attribution notices cannot be construed
          +       as modifying the License.
          +
          +   You may add Your own copyright statement to Your modifications and
          +   may provide additional or different license terms and conditions
          +   for use, reproduction, or distribution of Your modifications, or
          +   for any such Derivative Works as a whole, provided Your use,
          +   reproduction, and distribution of the Work otherwise complies with
          +   the conditions stated in this License.
          +
          +5. Submission of Contributions. Unless You explicitly state otherwise,
          +   any Contribution intentionally submitted for inclusion in the Work
          +   by You to the Licensor shall be under the terms and conditions of
          +   this License, without any additional terms or conditions.
          +   Notwithstanding the above, nothing herein shall supersede or modify
          +   the terms of any separate license agreement you may have executed
          +   with Licensor regarding such Contributions.
          +
          +6. Trademarks. This License does not grant permission to use the trade
          +   names, trademarks, service marks, or product names of the Licensor,
          +   except as required for reasonable and customary use in describing the
          +   origin of the Work and reproducing the content of the NOTICE file.
          +
          +7. Disclaimer of Warranty. Unless required by applicable law or
          +   agreed to in writing, Licensor provides the Work (and each
          +   Contributor provides its Contributions) on an "AS IS" BASIS,
          +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
          +   implied, including, without limitation, any warranties or conditions
          +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
          +   PARTICULAR PURPOSE. You are solely responsible for determining the
          +   appropriateness of using or redistributing the Work and assume any
          +   risks associated with Your exercise of permissions under this License.
          +
          +8. Limitation of Liability. In no event and under no legal theory,
          +   whether in tort (including negligence), contract, or otherwise,
          +   unless required by applicable law (such as deliberate and grossly
          +   negligent acts) or agreed to in writing, shall any Contributor be
          +   liable to You for damages, including any direct, indirect, special,
          +   incidental, or consequential damages of any character arising as a
          +   result of this License or out of the use or inability to use the
          +   Work (including but not limited to damages for loss of goodwill,
          +   work stoppage, computer failure or malfunction, or any and all
          +   other commercial damages or losses), even if such Contributor
          +   has been advised of the possibility of such damages.
          +
          +9. Accepting Warranty or Additional Liability. While redistributing
          +   the Work or Derivative Works thereof, You may choose to offer,
          +   and charge a fee for, acceptance of support, warranty, indemnity,
          +   or other liability obligations and/or rights consistent with this
          +   License. However, in accepting such obligations, You may act only
          +   on Your own behalf and on Your sole responsibility, not on behalf
          +   of any other Contributor, and only if You agree to indemnify,
          +   defend, and hold each Contributor harmless for any liability
          +   incurred by, or claims asserted against, such Contributor by reason
          +   of your accepting any such warranty or additional liability.
          +
          +END OF TERMS AND CONDITIONS
          +
          +APPENDIX: How to apply the Apache License to your work.
          +
          +   To apply the Apache License to your work, attach the following
          +   boilerplate notice, with the fields enclosed by brackets "[]"
          +   replaced with your own identifying information. (Don't include
          +   the brackets!)  The text should be enclosed in the appropriate
          +   comment syntax for the file format. We also recommend that a
          +   file or class name and description of purpose be included on the
          +   same "printed page" as the copyright notice for easier
          +   identification within third-party archives.
          +
          +Copyright [yyyy] [name of copyright owner]
          +
          +Licensed under the Apache License, Version 2.0 (the "License");
          +you may not use this file except in compliance with the License.
          +You may obtain a copy of the License at
          +
          +	http://www.apache.org/licenses/LICENSE-2.0
          +
          +Unless required by applicable law or agreed to in writing, software
          +distributed under the License is distributed on an "AS IS" BASIS,
          +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
          +See the License for the specific language governing permissions and
          +limitations under the License.
          +
          +
        • +
        • +

          Apache License 2.0

          +

          Used by:

          +
             Copyright (c) 2017-present PyO3 Project and Contributors.  https://github.com/PyO3
           
          @@ -10439,7 +12904,220 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

          +
          Apache License
          +                           Version 2.0, January 2004
          +                        http://www.apache.org/licenses/
          +
          +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
          +
          +   1. Definitions.
          +
          +      "License" shall mean the terms and conditions for use, reproduction,
          +      and distribution as defined by Sections 1 through 9 of this document.
          +
          +      "Licensor" shall mean the copyright owner or entity authorized by
          +      the copyright owner that is granting the License.
          +
          +      "Legal Entity" shall mean the union of the acting entity and all
          +      other entities that control, are controlled by, or are under common
          +      control with that entity. For the purposes of this definition,
          +      "control" means (i) the power, direct or indirect, to cause the
          +      direction or management of such entity, whether by contract or
          +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
          +      outstanding shares, or (iii) beneficial ownership of such entity.
          +
          +      "You" (or "Your") shall mean an individual or Legal Entity
          +      exercising permissions granted by this License.
          +
          +      "Source" form shall mean the preferred form for making modifications,
          +      including but not limited to software source code, documentation
          +      source, and configuration files.
          +
          +      "Object" form shall mean any form resulting from mechanical
          +      transformation or translation of a Source form, including but
          +      not limited to compiled object code, generated documentation,
          +      and conversions to other media types.
          +
          +      "Work" shall mean the work of authorship, whether in Source or
          +      Object form, made available under the License, as indicated by a
          +      copyright notice that is included in or attached to the work
          +      (an example is provided in the Appendix below).
          +
          +      "Derivative Works" shall mean any work, whether in Source or Object
          +      form, that is based on (or derived from) the Work and for which the
          +      editorial revisions, annotations, elaborations, or other modifications
          +      represent, as a whole, an original work of authorship. For the purposes
          +      of this License, Derivative Works shall not include works that remain
          +      separable from, or merely link (or bind by name) to the interfaces of,
          +      the Work and Derivative Works thereof.
          +
          +      "Contribution" shall mean any work of authorship, including
          +      the original version of the Work and any modifications or additions
          +      to that Work or Derivative Works thereof, that is intentionally
          +      submitted to Licensor for inclusion in the Work by the copyright owner
          +      or by an individual or Legal Entity authorized to submit on behalf of
          +      the copyright owner. For the purposes of this definition, "submitted"
          +      means any form of electronic, verbal, or written communication sent
          +      to the Licensor or its representatives, including but not limited to
          +      communication on electronic mailing lists, source code control systems,
          +      and issue tracking systems that are managed by, or on behalf of, the
          +      Licensor for the purpose of discussing and improving the Work, but
          +      excluding communication that is conspicuously marked or otherwise
          +      designated in writing by the copyright owner as "Not a Contribution."
          +
          +      "Contributor" shall mean Licensor and any individual or Legal Entity
          +      on behalf of whom a Contribution has been received by Licensor and
          +      subsequently incorporated within the Work.
          +
          +   2. Grant of Copyright License. Subject to the terms and conditions of
          +      this License, each Contributor hereby grants to You a perpetual,
          +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          +      copyright license to reproduce, prepare Derivative Works of,
          +      publicly display, publicly perform, sublicense, and distribute the
          +      Work and such Derivative Works in Source or Object form.
          +
          +   3. Grant of Patent License. Subject to the terms and conditions of
          +      this License, each Contributor hereby grants to You a perpetual,
          +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          +      (except as stated in this section) patent license to make, have made,
          +      use, offer to sell, sell, import, and otherwise transfer the Work,
          +      where such license applies only to those patent claims licensable
          +      by such Contributor that are necessarily infringed by their
          +      Contribution(s) alone or by combination of their Contribution(s)
          +      with the Work to which such Contribution(s) was submitted. If You
          +      institute patent litigation against any entity (including a
          +      cross-claim or counterclaim in a lawsuit) alleging that the Work
          +      or a Contribution incorporated within the Work constitutes direct
          +      or contributory patent infringement, then any patent licenses
          +      granted to You under this License for that Work shall terminate
          +      as of the date such litigation is filed.
          +
          +   4. Redistribution. You may reproduce and distribute copies of the
          +      Work or Derivative Works thereof in any medium, with or without
          +      modifications, and in Source or Object form, provided that You
          +      meet the following conditions:
          +
          +      (a) You must give any other recipients of the Work or
          +          Derivative Works a copy of this License; and
          +
          +      (b) You must cause any modified files to carry prominent notices
          +          stating that You changed the files; and
          +
          +      (c) You must retain, in the Source form of any Derivative Works
          +          that You distribute, all copyright, patent, trademark, and
          +          attribution notices from the Source form of the Work,
          +          excluding those notices that do not pertain to any part of
          +          the Derivative Works; and
          +
          +      (d) If the Work includes a "NOTICE" text file as part of its
          +          distribution, then any Derivative Works that You distribute must
          +          include a readable copy of the attribution notices contained
          +          within such NOTICE file, excluding those notices that do not
          +          pertain to any part of the Derivative Works, in at least one
          +          of the following places: within a NOTICE text file distributed
          +          as part of the Derivative Works; within the Source form or
          +          documentation, if provided along with the Derivative Works; or,
          +          within a display generated by the Derivative Works, if and
          +          wherever such third-party notices normally appear. The contents
          +          of the NOTICE file are for informational purposes only and
          +          do not modify the License. You may add Your own attribution
          +          notices within Derivative Works that You distribute, alongside
          +          or as an addendum to the NOTICE text from the Work, provided
          +          that such additional attribution notices cannot be construed
          +          as modifying the License.
          +
          +      You may add Your own copyright statement to Your modifications and
          +      may provide additional or different license terms and conditions
          +      for use, reproduction, or distribution of Your modifications, or
          +      for any such Derivative Works as a whole, provided Your use,
          +      reproduction, and distribution of the Work otherwise complies with
          +      the conditions stated in this License.
          +
          +   5. Submission of Contributions. Unless You explicitly state otherwise,
          +      any Contribution intentionally submitted for inclusion in the Work
          +      by You to the Licensor shall be under the terms and conditions of
          +      this License, without any additional terms or conditions.
          +      Notwithstanding the above, nothing herein shall supersede or modify
          +      the terms of any separate license agreement you may have executed
          +      with Licensor regarding such Contributions.
          +
          +   6. Trademarks. This License does not grant permission to use the trade
          +      names, trademarks, service marks, or product names of the Licensor,
          +      except as required for reasonable and customary use in describing the
          +      origin of the Work and reproducing the content of the NOTICE file.
          +
          +   7. Disclaimer of Warranty. Unless required by applicable law or
          +      agreed to in writing, Licensor provides the Work (and each
          +      Contributor provides its Contributions) on an "AS IS" BASIS,
          +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
          +      implied, including, without limitation, any warranties or conditions
          +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
          +      PARTICULAR PURPOSE. You are solely responsible for determining the
          +      appropriateness of using or redistributing the Work and assume any
          +      risks associated with Your exercise of permissions under this License.
          +
          +   8. Limitation of Liability. In no event and under no legal theory,
          +      whether in tort (including negligence), contract, or otherwise,
          +      unless required by applicable law (such as deliberate and grossly
          +      negligent acts) or agreed to in writing, shall any Contributor be
          +      liable to You for damages, including any direct, indirect, special,
          +      incidental, or consequential damages of any character arising as a
          +      result of this License or out of the use or inability to use the
          +      Work (including but not limited to damages for loss of goodwill,
          +      work stoppage, computer failure or malfunction, or any and all
          +      other commercial damages or losses), even if such Contributor
          +      has been advised of the possibility of such damages.
          +
          +   9. Accepting Warranty or Additional Liability. While redistributing
          +      the Work or Derivative Works thereof, You may choose to offer,
          +      and charge a fee for, acceptance of support, warranty, indemnity,
          +      or other liability obligations and/or rights consistent with this
          +      License. However, in accepting such obligations, You may act only
          +      on Your own behalf and on Your sole responsibility, not on behalf
          +      of any other Contributor, and only if You agree to indemnify,
          +      defend, and hold each Contributor harmless for any liability
          +      incurred by, or claims asserted against, such Contributor by reason
          +      of your accepting any such warranty or additional liability.
          +
          +   END OF TERMS AND CONDITIONS
          +
          +   APPENDIX: How to apply the Apache License to your work.
          +
          +      To apply the Apache License to your work, attach the following
          +      boilerplate notice, with the fields enclosed by brackets "{}"
          +      replaced with your own identifying information. (Don't include
          +      the brackets!)  The text should be enclosed in the appropriate
          +      comment syntax for the file format. We also recommend that a
          +      file or class name and description of purpose be included on the
          +      same "printed page" as the copyright notice for easier
          +      identification within third-party archives.
          +
          +   Copyright {yyyy} {name of copyright owner}
          +
          +   Licensed under the Apache License, Version 2.0 (the "License");
          +   you may not use this file except in compliance with the License.
          +   You may obtain a copy of the License at
          +
          +       http://www.apache.org/licenses/LICENSE-2.0
          +
          +   Unless required by applicable law or agreed to in writing, software
          +   distributed under the License is distributed on an "AS IS" BASIS,
          +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
          +   See the License for the specific language governing permissions and
          +   limitations under the License.
          +
          +
        • +
        • +

          Apache License 2.0

          +

          Used by:

          +
          Apache License
           Version 2.0, January 2004
          @@ -10718,135 +13396,182 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

          Apache License
           Version 2.0, January 2004
          @@ -11163,10 +13888,10 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

          Rust-chrono is dual-licensed under The MIT License [1] and
          -Apache 2.0 License [2]. Copyright (c) 2014--2025, Kang Seonghoon and
          +Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and
           contributors.
           
           Nota Bene: This is same as the Rust Project's own license.
          @@ -11405,6 +14130,40 @@ See the License for the specific language governing permissions and
           limitations under the License.
           ~~~~
           
          +
          +
        • +
        • +

          BSD 2-Clause "Simplified" License

          +

          Used by:

          + +
          Copyright (c) 2013-2014, Naoki Yoshinaga, Paul Meng
          +All rights reserved.
          +
          +Redistribution and use in source and binary forms, with or without
          +modification, are permitted provided that the following conditions are
          +met:
          +
          +1. Redistributions of source code must retain the above copyright
          +   notice, this list of conditions and the following disclaimer.
          +
          +2. Redistributions in binary form must reproduce the above copyright
          +   notice, this list of conditions and the following disclaimer in the
          +   documentation and/or other materials provided with the
          +   distribution.
          +
          +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
          +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
          +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
          +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
          +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
          +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
          +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
          +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
          +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
          +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
          +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
           
        • @@ -11439,6 +14198,99 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
        • + +
        • +

          BSD 2-Clause "Simplified" License

          +

          Used by:

          + +
          Copyright (c) 2017-2020
          +All rights reserved.
          +
          +Redistribution and use in source and binary forms, with or without
          +modification, are permitted provided that the following conditions are met:
          +
          +1. Redistributions of source code must retain the above copyright notice, this
          +   list of conditions and the following disclaimer.
          +2. Redistributions in binary form must reproduce the above copyright notice,
          +   this list of conditions and the following disclaimer in the documentation
          +   and/or other materials provided with the distribution.
          +
          +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
          +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
          +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
          +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
          +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
          +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
          +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
          +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
          +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
          +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +
          +
        • +
        • +

          BSD 3-Clause "New" or "Revised" License

          +

          Used by:

          + +
          // Copyright © WHATWG (Apple, Google, Mozilla, Microsoft).
          +//
          +// Redistribution and use in source and binary forms, with or without
          +// modification, are permitted provided that the following conditions are met:
          +//
          +// 1. Redistributions of source code must retain the above copyright notice, this
          +//    list of conditions and the following disclaimer.
          +//
          +// 2. Redistributions in binary form must reproduce the above copyright notice,
          +//    this list of conditions and the following disclaimer in the documentation
          +//    and/or other materials provided with the distribution.
          +//
          +// 3. Neither the name of the copyright holder nor the names of its
          +//    contributors may be used to endorse or promote products derived from
          +//    this software without specific prior written permission.
          +//
          +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
          +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
          +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
          +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
          +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
          +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
          +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
          +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
          +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
          +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +
          +/// The PUA code points special-cased in the GB18030 encoder.
          +pub(crate) static GB18030_2022_OVERRIDE_PUA: [u16; 18] = [
          +    0xE78D, 0xE78E, 0xE78F, 0xE790, 0xE791, 0xE792, 0xE793, 0xE794, 0xE795, 0xE796, 0xE81E, 0xE826,
          +    0xE82B, 0xE82C, 0xE832, 0xE843, 0xE854, 0xE864,
          +];
          +
          +/// The bytes corresponding to the PUA code points special-cased in the GB18030 encoder.
          +pub(crate) static GB18030_2022_OVERRIDE_BYTES: [[u8; 2]; 18] = [
          +    [0xA6, 0xD9],
          +    [0xA6, 0xDA],
          +    [0xA6, 0xDB],
          +    [0xA6, 0xDC],
          +    [0xA6, 0xDD],
          +    [0xA6, 0xDE],
          +    [0xA6, 0xDF],
          +    [0xA6, 0xEC],
          +    [0xA6, 0xED],
          +    [0xA6, 0xF3],
          +    [0xFE, 0x59],
          +    [0xFE, 0x61],
          +    [0xFE, 0x66],
          +    [0xFE, 0x67],
          +    [0xFE, 0x6D],
          +    [0xFE, 0x7E],
          +    [0xFE, 0x90],
          +    [0xFE, 0xA0],
          +];
           
        • @@ -11446,6 +14298,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

          Used by:

          BSD 3-Clause License
           
          @@ -11482,10 +14335,88 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                           

          BSD 3-Clause "New" or "Revised" License

          Used by:

          +
          BSD 3-Clause License
          +
          +Copyright (c) 2026, Alexandre Bury
          +
          +Redistribution and use in source and binary forms, with or without
          +modification, are permitted provided that the following conditions are met:
          +
          +1. Redistributions of source code must retain the above copyright notice, this
          +   list of conditions and the following disclaimer.
          +
          +2. Redistributions in binary form must reproduce the above copyright notice,
          +   this list of conditions and the following disclaimer in the documentation
          +   and/or other materials provided with the distribution.
          +
          +3. Neither the name of the copyright holder nor the names of its
          +   contributors may be used to endorse or promote products derived from
          +   this software without specific prior written permission.
          +
          +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
          +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
          +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
          +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
          +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
          +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
          +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
          +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
          +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
          +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +
          +
        • +
        • +

          BSD 3-Clause "New" or "Revised" License

          +

          Used by:

          + +
          BSD License
          +
          +For Zstandard software
          +
          +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
          +
          +Redistribution and use in source and binary forms, with or without modification,
          +are permitted provided that the following conditions are met:
          +
          + * Redistributions of source code must retain the above copyright notice, this
          +   list of conditions and the following disclaimer.
          +
          + * Redistributions in binary form must reproduce the above copyright notice,
          +   this list of conditions and the following disclaimer in the documentation
          +   and/or other materials provided with the distribution.
          +
          + * Neither the name Facebook, nor Meta, nor the names of its contributors may
          +   be used to endorse or promote products derived from this software without
          +   specific prior written permission.
          +
          +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
          +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
          +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
          +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
          +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
          +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
          +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
          +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
          +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
          +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +
          +
        • +
        • +

          BSD 3-Clause "New" or "Revised" License

          +

          Used by:

          +
          Copyright (c) 2001, Dr Martin Porter
           Copyright (c) 2004,2005, Richard Boulton
          +Copyright (c) 2013, Yoshiki Shibukawa
          +Copyright (c) 2006-2025, Olly Betts
           All rights reserved.
           
           Redistribution and use in source and binary forms, with or without
          @@ -11510,16 +14441,16 @@ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
           LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
           ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
           (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
          -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
        • BSD 3-Clause "New" or "Revised" License

          Used by:

          Copyright (c) 2016 Dropbox, Inc.
           All rights reserved.
          @@ -11576,8 +14507,53 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                           

          BSD 3-Clause "New" or "Revised" License

          Used by:

          +
          Copyright (c) 2026, frostem contributors
          +Copyright (c) 2001, Dr Martin Porter
          +Copyright (c) 2004,2005, Richard Boulton
          +Copyright (c) 2013, Yoshiki Shibukawa
          +Copyright (c) 2006-2025, Olly Betts
          +All rights reserved.
          +
          +Redistribution and use in source and binary forms, with or without
          +modification, are permitted provided that the following conditions
          +are met:
          +
          +  1. Redistributions of source code must retain the above copyright notice,
          +     this list of conditions and the following disclaimer.
          +  2. Redistributions in binary form must reproduce the above copyright notice,
          +     this list of conditions and the following disclaimer in the documentation
          +     and/or other materials provided with the distribution.
          +  3. Neither the name of the Snowball project nor the names of its contributors
          +     may be used to endorse or promote products derived from this software
          +     without specific prior written permission.
          +
          +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
          +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
          +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
          +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
          +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
          +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
          +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
          +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
          +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
          +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +
          +
        • +
        • +

          BSD 3-Clause "New" or "Revised" License

          +

          Used by:

          +
          Copyright (c) <year> <owner>. 
           
          @@ -11624,13 +14600,53 @@ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
           CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
           OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
           OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +
          +
        • +
        • +

          BSD 3-Clause "New" or "Revised" License

          +

          Used by:

          + +
          The auto-generated bindings are under the 3-clause BSD license:
          +
          +BSD License
          +
          +For Zstandard software
          +
          +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
          +
          +Redistribution and use in source and binary forms, with or without modification,
          +are permitted provided that the following conditions are met:
          +
          + * Redistributions of source code must retain the above copyright notice, this
          +   list of conditions and the following disclaimer.
          +
          + * Redistributions in binary form must reproduce the above copyright notice,
          +   this list of conditions and the following disclaimer in the documentation
          +   and/or other materials provided with the distribution.
          +
          + * Neither the name Facebook, nor Meta, nor the names of its contributors may
          +   be used to endorse or promote products derived from this software without
          +   specific prior written permission.
          +
          +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
          +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
          +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
          +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
          +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
          +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
          +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
          +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
          +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
          +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
           
        • Boost Software License 1.0

          Used by:

          Boost Software License - Version 1.0 - August 17th, 2003
           
          @@ -11784,13 +14800,405 @@ express Statement of Purpose.
            d. Affirmer understands and acknowledges that Creative Commons is not a
               party to this document and has no duty or obligation with respect to
               this CC0 or use of the Work.
          +
          +
        • +
        • +

          Common Development and Distribution License 1.0

          +

          Used by:

          + +
          Unless otherwise noted, all files in this distribution are released
          +under the Common Development and Distribution License (CDDL).
          +Exceptions are noted within the associated source files.
          +
          +--------------------------------------------------------------------
          +
          +
          +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE Version 1.0
          +
          +1. Definitions.
          +
          +    1.1. "Contributor" means each individual or entity that creates
          +         or contributes to the creation of Modifications.
          +
          +    1.2. "Contributor Version" means the combination of the Original
          +         Software, prior Modifications used by a Contributor (if any),
          +         and the Modifications made by that particular Contributor.
          +
          +    1.3. "Covered Software" means (a) the Original Software, or (b)
          +         Modifications, or (c) the combination of files containing
          +         Original Software with files containing Modifications, in
          +         each case including portions thereof.
          +
          +    1.4. "Executable" means the Covered Software in any form other
          +         than Source Code.
          +
          +    1.5. "Initial Developer" means the individual or entity that first
          +         makes Original Software available under this License.
          +
          +    1.6. "Larger Work" means a work which combines Covered Software or
          +         portions thereof with code not governed by the terms of this
          +         License.
          +
          +    1.7. "License" means this document.
          +
          +    1.8. "Licensable" means having the right to grant, to the maximum
          +         extent possible, whether at the time of the initial grant or
          +         subsequently acquired, any and all of the rights conveyed
          +         herein.
          +
          +    1.9. "Modifications" means the Source Code and Executable form of
          +         any of the following:
          +
          +        A. Any file that results from an addition to, deletion from or
          +           modification of the contents of a file containing Original
          +           Software or previous Modifications;
          +
          +        B. Any new file that contains any part of the Original
          +           Software or previous Modifications; or
          +
          +        C. Any new file that is contributed or otherwise made
          +           available under the terms of this License.
          +
          +    1.10. "Original Software" means the Source Code and Executable
          +          form of computer software code that is originally released
          +          under this License.
          +
          +    1.11. "Patent Claims" means any patent claim(s), now owned or
          +          hereafter acquired, including without limitation, method,
          +          process, and apparatus claims, in any patent Licensable by
          +          grantor.
          +
          +    1.12. "Source Code" means (a) the common form of computer software
          +          code in which modifications are made and (b) associated
          +          documentation included in or with such code.
          +
          +    1.13. "You" (or "Your") means an individual or a legal entity
          +          exercising rights under, and complying with all of the terms
          +          of, this License.  For legal entities, "You" includes any
          +          entity which controls, is controlled by, or is under common
          +          control with You.  For purposes of this definition,
          +          "control" means (a) the power, direct or indirect, to cause
          +          the direction or management of such entity, whether by
          +          contract or otherwise, or (b) ownership of more than fifty
          +          percent (50%) of the outstanding shares or beneficial
          +          ownership of such entity.
          +
          +2. License Grants.
          +
          +    2.1. The Initial Developer Grant.
          +
          +    Conditioned upon Your compliance with Section 3.1 below and
          +    subject to third party intellectual property claims, the Initial
          +    Developer hereby grants You a world-wide, royalty-free,
          +    non-exclusive license:
          +
          +        (a) under intellectual property rights (other than patent or
          +            trademark) Licensable by Initial Developer, to use,
          +            reproduce, modify, display, perform, sublicense and
          +            distribute the Original Software (or portions thereof),
          +            with or without Modifications, and/or as part of a Larger
          +            Work; and
          +
          +        (b) under Patent Claims infringed by the making, using or
          +            selling of Original Software, to make, have made, use,
          +            practice, sell, and offer for sale, and/or otherwise
          +            dispose of the Original Software (or portions thereof).
          +
          +        (c) The licenses granted in Sections 2.1(a) and (b) are
          +            effective on the date Initial Developer first distributes
          +            or otherwise makes the Original Software available to a
          +            third party under the terms of this License.
          +
          +        (d) Notwithstanding Section 2.1(b) above, no patent license is
          +            granted: (1) for code that You delete from the Original
          +            Software, or (2) for infringements caused by: (i) the
          +            modification of the Original Software, or (ii) the
          +            combination of the Original Software with other software
          +            or devices.
          +
          +    2.2. Contributor Grant.
          +
          +    Conditioned upon Your compliance with Section 3.1 below and
          +    subject to third party intellectual property claims, each
          +    Contributor hereby grants You a world-wide, royalty-free,
          +    non-exclusive license:
          +
          +        (a) under intellectual property rights (other than patent or
          +            trademark) Licensable by Contributor to use, reproduce,
          +            modify, display, perform, sublicense and distribute the
          +            Modifications created by such Contributor (or portions
          +            thereof), either on an unmodified basis, with other
          +            Modifications, as Covered Software and/or as part of a
          +            Larger Work; and
          +
          +        (b) under Patent Claims infringed by the making, using, or
          +            selling of Modifications made by that Contributor either
          +            alone and/or in combination with its Contributor Version
          +            (or portions of such combination), to make, use, sell,
          +            offer for sale, have made, and/or otherwise dispose of:
          +            (1) Modifications made by that Contributor (or portions
          +            thereof); and (2) the combination of Modifications made by
          +            that Contributor with its Contributor Version (or portions
          +            of such combination).
          +
          +        (c) The licenses granted in Sections 2.2(a) and 2.2(b) are
          +            effective on the date Contributor first distributes or
          +            otherwise makes the Modifications available to a third
          +            party.
          +
          +        (d) Notwithstanding Section 2.2(b) above, no patent license is
          +            granted: (1) for any code that Contributor has deleted
          +            from the Contributor Version; (2) for infringements caused
          +            by: (i) third party modifications of Contributor Version,
          +            or (ii) the combination of Modifications made by that
          +            Contributor with other software (except as part of the
          +            Contributor Version) or other devices; or (3) under Patent
          +            Claims infringed by Covered Software in the absence of
          +            Modifications made by that Contributor.
          +
          +3. Distribution Obligations.
          +
          +    3.1. Availability of Source Code.
          +
          +    Any Covered Software that You distribute or otherwise make
          +    available in Executable form must also be made available in Source
          +    Code form and that Source Code form must be distributed only under
          +    the terms of this License.  You must include a copy of this
          +    License with every copy of the Source Code form of the Covered
          +    Software You distribute or otherwise make available.  You must
          +    inform recipients of any such Covered Software in Executable form
          +    as to how they can obtain such Covered Software in Source Code
          +    form in a reasonable manner on or through a medium customarily
          +    used for software exchange.
          +
          +    3.2. Modifications.
          +
          +    The Modifications that You create or to which You contribute are
          +    governed by the terms of this License.  You represent that You
          +    believe Your Modifications are Your original creation(s) and/or
          +    You have sufficient rights to grant the rights conveyed by this
          +    License.
          +
          +    3.3. Required Notices.
          +
          +    You must include a notice in each of Your Modifications that
          +    identifies You as the Contributor of the Modification.  You may
          +    not remove or alter any copyright, patent or trademark notices
          +    contained within the Covered Software, or any notices of licensing
          +    or any descriptive text giving attribution to any Contributor or
          +    the Initial Developer.
          +
          +    3.4. Application of Additional Terms.
          +
          +    You may not offer or impose any terms on any Covered Software in
          +    Source Code form that alters or restricts the applicable version
          +    of this License or the recipients' rights hereunder.  You may
          +    choose to offer, and to charge a fee for, warranty, support,
          +    indemnity or liability obligations to one or more recipients of
          +    Covered Software.  However, you may do so only on Your own behalf,
          +    and not on behalf of the Initial Developer or any Contributor.
          +    You must make it absolutely clear that any such warranty, support,
          +    indemnity or liability obligation is offered by You alone, and You
          +    hereby agree to indemnify the Initial Developer and every
          +    Contributor for any liability incurred by the Initial Developer or
          +    such Contributor as a result of warranty, support, indemnity or
          +    liability terms You offer.
          +
          +    3.5. Distribution of Executable Versions.
          +
          +    You may distribute the Executable form of the Covered Software
          +    under the terms of this License or under the terms of a license of
          +    Your choice, which may contain terms different from this License,
          +    provided that You are in compliance with the terms of this License
          +    and that the license for the Executable form does not attempt to
          +    limit or alter the recipient's rights in the Source Code form from
          +    the rights set forth in this License.  If You distribute the
          +    Covered Software in Executable form under a different license, You
          +    must make it absolutely clear that any terms which differ from
          +    this License are offered by You alone, not by the Initial
          +    Developer or Contributor.  You hereby agree to indemnify the
          +    Initial Developer and every Contributor for any liability incurred
          +    by the Initial Developer or such Contributor as a result of any
          +    such terms You offer.
          +
          +    3.6. Larger Works.
          +
          +    You may create a Larger Work by combining Covered Software with
          +    other code not governed by the terms of this License and
          +    distribute the Larger Work as a single product.  In such a case,
          +    You must make sure the requirements of this License are fulfilled
          +    for the Covered Software.
          +
          +4. Versions of the License.
          +
          +    4.1. New Versions.
          +
          +    Sun Microsystems, Inc. is the initial license steward and may
          +    publish revised and/or new versions of this License from time to
          +    time.  Each version will be given a distinguishing version number.
          +    Except as provided in Section 4.3, no one other than the license
          +    steward has the right to modify this License.
          +
          +    4.2. Effect of New Versions.
          +
          +    You may always continue to use, distribute or otherwise make the
          +    Covered Software available under the terms of the version of the
          +    License under which You originally received the Covered Software.
          +    If the Initial Developer includes a notice in the Original
          +    Software prohibiting it from being distributed or otherwise made
          +    available under any subsequent version of the License, You must
          +    distribute and make the Covered Software available under the terms
          +    of the version of the License under which You originally received
          +    the Covered Software.  Otherwise, You may also choose to use,
          +    distribute or otherwise make the Covered Software available under
          +    the terms of any subsequent version of the License published by
          +    the license steward.
          +
          +    4.3. Modified Versions.
          +
          +    When You are an Initial Developer and You want to create a new
          +    license for Your Original Software, You may create and use a
          +    modified version of this License if You: (a) rename the license
          +    and remove any references to the name of the license steward
          +    (except to note that the license differs from this License); and
          +    (b) otherwise make it clear that the license contains terms which
          +    differ from this License.
          +
          +5. DISCLAIMER OF WARRANTY.
          +
          +    COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS"
          +    BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
          +    INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED
          +    SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR
          +    PURPOSE OR NON-INFRINGING.  THE ENTIRE RISK AS TO THE QUALITY AND
          +    PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU.  SHOULD ANY
          +    COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
          +    INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
          +    NECESSARY SERVICING, REPAIR OR CORRECTION.  THIS DISCLAIMER OF
          +    WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.  NO USE OF
          +    ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS
          +    DISCLAIMER.
          +
          +6. TERMINATION.
          +
          +    6.1. This License and the rights granted hereunder will terminate
          +    automatically if You fail to comply with terms herein and fail to
          +    cure such breach within 30 days of becoming aware of the breach.
          +    Provisions which, by their nature, must remain in effect beyond
          +    the termination of this License shall survive.
          +
          +    6.2. If You assert a patent infringement claim (excluding
          +    declaratory judgment actions) against Initial Developer or a
          +    Contributor (the Initial Developer or Contributor against whom You
          +    assert such claim is referred to as "Participant") alleging that
          +    the Participant Software (meaning the Contributor Version where
          +    the Participant is a Contributor or the Original Software where
          +    the Participant is the Initial Developer) directly or indirectly
          +    infringes any patent, then any and all rights granted directly or
          +    indirectly to You by such Participant, the Initial Developer (if
          +    the Initial Developer is not the Participant) and all Contributors
          +    under Sections 2.1 and/or 2.2 of this License shall, upon 60 days
          +    notice from Participant terminate prospectively and automatically
          +    at the expiration of such 60 day notice period, unless if within
          +    such 60 day period You withdraw Your claim with respect to the
          +    Participant Software against such Participant either unilaterally
          +    or pursuant to a written agreement with Participant.
          +
          +    6.3. In the event of termination under Sections 6.1 or 6.2 above,
          +    all end user licenses that have been validly granted by You or any
          +    distributor hereunder prior to termination (excluding licenses
          +    granted to You by any distributor) shall survive termination.
          +
          +7. LIMITATION OF LIABILITY.
          +
          +    UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
          +    (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE
          +    INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF
          +    COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE
          +    LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
          +    CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT
          +    LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK
          +    STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
          +    COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
          +    INFORMED OF THE POSSIBILITY OF SUCH DAMAGES.  THIS LIMITATION OF
          +    LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL
          +    INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT
          +    APPLICABLE LAW PROHIBITS SUCH LIMITATION.  SOME JURISDICTIONS DO
          +    NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR
          +    CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT
          +    APPLY TO YOU.
          +
          +8. U.S. GOVERNMENT END USERS.
          +
          +    The Covered Software is a "commercial item," as that term is
          +    defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial
          +    computer software" (as that term is defined at 48
          +    C.F.R. 252.227-7014(a)(1)) and "commercial computer software
          +    documentation" as such terms are used in 48 C.F.R. 12.212
          +    (Sept. 1995).  Consistent with 48 C.F.R. 12.212 and 48
          +    C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all
          +    U.S. Government End Users acquire Covered Software with only those
          +    rights set forth herein.  This U.S. Government Rights clause is in
          +    lieu of, and supersedes, any other FAR, DFAR, or other clause or
          +    provision that addresses Government rights in computer software
          +    under this License.
          +
          +9. MISCELLANEOUS.
          +
          +    This License represents the complete agreement concerning subject
          +    matter hereof.  If any provision of this License is held to be
          +    unenforceable, such provision shall be reformed only to the extent
          +    necessary to make it enforceable.  This License shall be governed
          +    by the law of the jurisdiction specified in a notice contained
          +    within the Original Software (except to the extent applicable law,
          +    if any, provides otherwise), excluding such jurisdiction's
          +    conflict-of-law provisions.  Any litigation relating to this
          +    License shall be subject to the jurisdiction of the courts located
          +    in the jurisdiction and venue specified in a notice contained
          +    within the Original Software, with the losing party responsible
          +    for costs, including, without limitation, court costs and
          +    reasonable attorneys' fees and expenses.  The application of the
          +    United Nations Convention on Contracts for the International Sale
          +    of Goods is expressly excluded.  Any law or regulation which
          +    provides that the language of a contract shall be construed
          +    against the drafter shall not apply to this License.  You agree
          +    that You alone are responsible for compliance with the United
          +    States export administration regulations (and the export control
          +    laws and regulation of any other countries) when You use,
          +    distribute or otherwise make available any Covered Software.
          +
          +10. RESPONSIBILITY FOR CLAIMS.
          +
          +    As between Initial Developer and the Contributors, each party is
          +    responsible for claims and damages arising, directly or
          +    indirectly, out of its utilization of rights under this License
          +    and You agree to work with Initial Developer and Contributors to
          +    distribute such responsibility on an equitable basis.  Nothing
          +    herein is intended or shall be deemed to constitute any admission
          +    of liability.
          +
          +--------------------------------------------------------------------
          +
          +NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND
          +DISTRIBUTION LICENSE (CDDL)
          +
          +For Covered Software in this distribution, this License shall
          +be governed by the laws of the State of California (excluding
          +conflict-of-law provisions).
          +
          +Any litigation relating to this License shall be subject to the
          +jurisdiction of the Federal Courts of the Northern District of
          +California and the state courts of the State of California, with
          +venue lying in Santa Clara County, California.
           
        • Community Data License Agreement Permissive 2.0

          Used by:

          # Community Data License Agreement - Permissive - Version 2.0
           
          @@ -11853,6 +15261,88 @@ agreement.
           5.4. "Results" means any outcome obtained by computational analysis
           of Data, including for example machine learning models and models'
           insights.
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          /* Copyright (c) 2014, Intel Corporation.
          + *
          + * Permission to use, copy, modify, and/or distribute this software for any
          + * purpose with or without fee is hereby granted, provided that the above
          + * copyright notice and this permission notice appear in all copies.
          + *
          + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
          +
          +#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H
          +#define OPENSSL_HEADER_EC_ECP_NISTZ384_H
          +
          +#include "../../limbs/limbs.h"
          +
          +#define P384_LIMBS (384u / LIMB_BITS)
          +
          +typedef struct {
          +  Limb X[P384_LIMBS];
          +  Limb Y[P384_LIMBS];
          +  Limb Z[P384_LIMBS];
          +} P384_POINT;
          +
          +typedef struct {
          +  Limb X[P384_LIMBS];
          +  Limb Y[P384_LIMBS];
          +} P384_POINT_AFFINE;
          +
          +
          +#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2015-2016 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +//! EdDSA Signatures.
          +
          +use super::ops::ELEM_LEN;
          +use crate::digest;
          +
          +pub mod signing;
          +pub mod verification;
          +
          +/// The length of an Ed25519 public key.
          +pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN;
          +
          +pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest {
          +    let mut ctx = digest::Context::new(&digest::SHA512);
          +    ctx.update(signature_r);
          +    ctx.update(public_key);
          +    ctx.update(msg);
          +    ctx.finish()
          +}
           
        • @@ -11880,29 +15370,44 @@ insights.

          ISC License

          Used by:

          -
          // Copyright 2021 Brian Smith.
          +                
          // Copyright 2015-2022 Brian Smith.
           //
           // Permission to use, copy, modify, and/or distribute this software for any
           // purpose with or without fee is hereby granted, provided that the above
           // copyright notice and this permission notice appear in all copies.
           //
          -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
           // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
          -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
          -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
          -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
           
          -#[test]
          -fn cert_without_extensions_test() {
          -    // Check the certificate is valid with
          -    // `openssl x509 -in cert_without_extensions.der -inform DER -text -noout`
          -    const CERT_WITHOUT_EXTENSIONS_DER: &[u8] = include_bytes!("cert_without_extensions.der");
          +use crate::limb::Limb;
           
          -    assert!(webpki::EndEntityCert::try_from(CERT_WITHOUT_EXTENSIONS_DER).is_ok());
          +#[derive(Clone, Copy)]
          +#[repr(transparent)]
          +pub struct N0([Limb; 2]);
          +
          +impl N0 {
          +    #[cfg(feature = "alloc")]
          +    pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS;
          +
          +    #[inline]
          +    pub const fn precalculated(n0: u64) -> Self {
          +        #[cfg(target_pointer_width = "64")]
          +        {
          +            Self([n0, 0])
          +        }
          +
          +        #[cfg(target_pointer_width = "32")]
          +        {
          +            Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb])
          +        }
          +    }
           }
           
        • @@ -11910,21 +15415,372 @@ fn cert_without_extensions_test() {

          ISC License

          Used by:

          -
          Copyright (c) 2017 Adam Wick
          +                
          // Copyright 2015-2025 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
           
          -Permission to use, copy, modify, and/or distribute this software for any purpose
          -with or without fee is hereby granted, provided that the above copyright notice
          -and this permission notice appear in all copies.
          +use crate::{bb, error};
           
          -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
          -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
          -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
          -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
          -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
          -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
          -THIS SOFTWARE.
          +#[deprecated(
          +    note = "To be removed. Internal function not intended for external use with no promises regarding side channels."
          +)]
          +pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
          +    bb::verify_slices_are_equal(a, b)
          +}
          +
          + +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2016 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +//! Elliptic curve operations and schemes using Curve25519.
          +
          +pub mod ed25519;
          +
          +pub mod x25519;
          +
          +mod ops;
          +mod scalar;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2016-2024 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +use crate::error::{KeyRejected, Unspecified};
          +
          +impl From<untrusted::EndOfInput> for Unspecified {
          +    fn from(source: untrusted::EndOfInput) -> Self {
          +        super::erase(source)
          +    }
          +}
          +
          +impl From<core::array::TryFromSliceError> for Unspecified {
          +    fn from(source: core::array::TryFromSliceError) -> Self {
          +        super::erase(source)
          +    }
          +}
          +
          +impl From<KeyRejected> for Unspecified {
          +    fn from(source: KeyRejected) -> Self {
          +        super::erase(source)
          +    }
          +}
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2018 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +//! Serialization and deserialization.
          +
          +#[doc(hidden)]
          +pub mod der;
          +
          +#[cfg(feature = "alloc")]
          +mod writer;
          +
          +#[cfg(feature = "alloc")]
          +pub(crate) mod der_writer;
          +
          +pub(crate) mod positive;
          +
          +pub use self::positive::Positive;
          +
          +#[cfg(feature = "alloc")]
          +pub(crate) use self::writer::TooLongError;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2019-2024 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +use super::BlockLen;
          +
          +pub(super) use self::{
          +    sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN},
          +    sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN},
          +};
          +
          +pub(super) const CHAINING_WORDS: usize = 8;
          +
          +#[cfg(any(
          +    all(target_arch = "aarch64", target_endian = "little"),
          +    all(target_arch = "arm", target_endian = "little"),
          +    target_arch = "x86_64"
          +))]
          +#[macro_use]
          +mod ffi;
          +
          +pub(super) mod fallback;
          +mod sha2_32;
          +mod sha2_64;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2024 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`.
          +#[allow(dead_code)]
          +#[inline(always)]
          +pub fn from_mut<T: ?Sized>(r: &mut T) -> *mut T {
          +    r
          +}
          +
          +// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`.
          +#[allow(dead_code)]
          +#[inline(always)]
          +pub const fn from_ref<T: ?Sized>(r: &T) -> *const T {
          +    r
          +}
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2024 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +//! Integration tests for non-public APIs.
          +
          +mod bits_tests;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2024 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +pub use self::{
          +    array::Array,
          +    base::{IndexError, Overlapping},
          +    partial_block::PartialBlock,
          +};
          +
          +mod array;
          +mod base;
          +mod partial_block;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2025 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +#![cfg(all(target_arch = "aarch64", target_endian = "little"))]
          +
          +pub(in super::super) mod mont;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2025 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +#![cfg(target_arch = "x86_64")]
          +
          +pub(in super::super::super) mod mont;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2025 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +mod storage;
          +
          +pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK};
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2025 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +pub(super) mod aarch64;
          +pub(super) mod x86_64;
           
        • @@ -11952,7 +15808,7 @@ CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

          ISC License

          Used by:

          Except as otherwise noted, this project is licensed under the following
           (ISC-style) terms:
          @@ -11979,12 +15835,12 @@ third-party/chromium/LICENSE.
                           

          ISC License

          Used by:

          ISC License
           
           Copyright (c) 2016, Mapbox
          -Copyright (c) 2018, Tree Cricket
          +Copyright (c) 2023, Taku Fukada
           
           Permission to use, copy, modify, and/or distribute this software for any purpose
           with or without fee is hereby granted, provided that the above copyright notice
          @@ -11997,13 +15853,603 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
           OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
           TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
           THIS SOFTWARE.
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          ISC License:
          +
          +Copyright (c) 2004-2010 by Internet Systems Consortium, Inc. ("ISC")
          +Copyright (c) 1995-2003 by Internet Software Consortium
          +
          +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
          +
          +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
           
        • MIT License

          Used by:

          +
                                            MIT License
          +
          +Copyright 2024 Antoine Catton
          +Copyright 2016-2024 David Tolnay
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy of
          +this software and associated documentation files (the “Software”), to deal in
          +the Software without restriction, including without limitation the rights to
          +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
          +of the Software, and to permit persons to whom the Software is furnished to do
          +so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          # 3rd Party Notices
          +
          +The `cfg_aliases!` macro uses a lot of the code from [`tectonic_cfg_support::target_cfg!`] macro which is under the following license:
          +
          +[`tectonic_cfg_support::target_cfg!`]: https://github.com/tectonic-typesetting/tectonic/blob/f2439b936470ad27bdf92882064bc4702ee01899/cfg_support/src/lib.rs#L166
          +
          +    tectonic_cfg_support is licensed under the MIT License.
          +
          +    Permission is hereby granted, free of charge, to any person obtaining a copy
          +    of this software and associated documentation files (the “Software”), to deal
          +    in the Software without restriction, including without limitation the rights
          +    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +    copies of the Software, and to permit persons to whom the Software is
          +    furnished to do so, subject to the following conditions:
          +
          +    The above copyright notice and this permission notice shall be included in all
          +    copies or substantial portions of the Software.
          +
          +    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +    SOFTWARE.
          +---
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * Permission is hereby granted, free of charge, to any person obtaining a copy
          + * of this software and associated documentation files (the "Software"), to
          + * deal in the Software without restriction, including without limitation the
          + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
          + * sell copies of the Software, and to permit persons to whom the Software is
          + * furnished to do so, subject to the following conditions:
          + *
          + * The above copyright notice and this permission notice shall be included in
          + * all copies or substantial portions of the Software.
          + *
          + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
          + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
          + * IN THE SOFTWARE.
          + *
          + */
          +
          +//! Codegen exports used by `tonic-build`.
          +
          +pub use async_trait::async_trait;
          +pub use tokio_stream;
          +
          +pub use std::future::Future;
          +pub use std::pin::Pin;
          +pub use std::sync::Arc;
          +pub use std::task::{Context, Poll};
          +pub use tower_service::Service;
          +pub type StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
          +pub use crate::codec::{CompressionEncoding, EnabledCompressionEncodings};
          +pub use crate::extensions::GrpcMethod;
          +pub use crate::service::interceptor::InterceptedService;
          +pub use bytes::Bytes;
          +pub use http;
          +pub use http_body::Body;
          +
          +pub type BoxFuture<T, E> = self::Pin<Box<dyn self::Future<Output = Result<T, E>> + Send + 'static>>;
          +pub type BoxStream<T> =
          +    self::Pin<Box<dyn tokio_stream::Stream<Item = Result<T, crate::Status>> + Send + 'static>>;
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * Permission is hereby granted, free of charge, to any person obtaining a copy
          + * of this software and associated documentation files (the "Software"), to
          + * deal in the Software without restriction, including without limitation the
          + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
          + * sell copies of the Software, and to permit persons to whom the Software is
          + * furnished to do so, subject to the following conditions:
          + *
          + * The above copyright notice and this permission notice shall be included in
          + * all copies or substantial portions of the Software.
          + *
          + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
          + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
          + * IN THE SOFTWARE.
          + *
          + */
          +
          +//! Utilities for using Tower services with Tonic.
          +
          +pub mod interceptor;
          +pub(crate) mod layered;
          +#[cfg(feature = "router")]
          +pub(crate) mod router;
          +
          +#[doc(inline)]
          +pub use self::interceptor::{Interceptor, InterceptorLayer};
          +pub use self::layered::{LayerExt, Layered};
          +#[doc(inline)]
          +#[cfg(feature = "router")]
          +pub use self::router::{Routes, RoutesBuilder};
          +#[cfg(feature = "router")]
          +pub use axum::{Router as AxumRouter, body::Body as AxumBody};
          +
          +pub mod recover_error;
          +pub use self::recover_error::{RecoverError, RecoverErrorLayer};
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * Permission is hereby granted, free of charge, to any person obtaining a copy
          + * of this software and associated documentation files (the "Software"), to
          + * deal in the Software without restriction, including without limitation the
          + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
          + * sell copies of the Software, and to permit persons to whom the Software is
          + * furnished to do so, subject to the following conditions:
          + *
          + * The above copyright notice and this permission notice shall be included in
          + * all copies or substantial portions of the Software.
          + *
          + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
          + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
          + * IN THE SOFTWARE.
          + *
          + */
          +
          +//! Various utilities used throughout tonic.
          +
          +// some combinations of features might cause things here not to be used
          +#![allow(dead_code)]
          +
          +pub(crate) mod base64 {
          +    use base64::{
          +        alphabet,
          +        engine::{
          +            DecodePaddingMode,
          +            general_purpose::{GeneralPurpose, GeneralPurposeConfig},
          +        },
          +    };
          +
          +    pub(crate) const STANDARD: GeneralPurpose = GeneralPurpose::new(
          +        &alphabet::STANDARD,
          +        GeneralPurposeConfig::new()
          +            .with_encode_padding(true)
          +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
          +    );
          +
          +    pub(crate) const STANDARD_NO_PAD: GeneralPurpose = GeneralPurpose::new(
          +        &alphabet::STANDARD,
          +        GeneralPurposeConfig::new()
          +            .with_encode_padding(false)
          +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
          +    );
          +}
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * Permission is hereby granted, free of charge, to any person obtaining a copy
          + * of this software and associated documentation files (the "Software"), to
          + * deal in the Software without restriction, including without limitation the
          + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
          + * sell copies of the Software, and to permit persons to whom the Software is
          + * furnished to do so, subject to the following conditions:
          + *
          + * The above copyright notice and this permission notice shall be included in
          + * all copies or substantial portions of the Software.
          + *
          + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
          + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
          + * IN THE SOFTWARE.
          + *
          + */
          +
          +/// A gRPC Method info extension.
          +#[derive(Debug, Clone)]
          +pub struct GrpcMethod<'a> {
          +    service: &'a str,
          +    method: &'a str,
          +}
          +
          +impl<'a> GrpcMethod<'a> {
          +    /// Create a new `GrpcMethod` extension.
          +    #[doc(hidden)]
          +    pub fn new(service: &'a str, method: &'a str) -> Self {
          +        Self { service, method }
          +    }
          +
          +    /// gRPC service name
          +    pub fn service(&self) -> &str {
          +        self.service
          +    }
          +    /// gRPC method name
          +    pub fn method(&self) -> &str {
          +        self.method
          +    }
          +}
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * Permission is hereby granted, free of charge, to any person obtaining a copy
          + * of this software and associated documentation files (the "Software"), to
          + * deal in the Software without restriction, including without limitation the
          + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
          + * sell copies of the Software, and to permit persons to whom the Software is
          + * furnished to do so, subject to the following conditions:
          + *
          + * The above copyright notice and this permission notice shall be included in
          + * all copies or substantial portions of the Software.
          + *
          + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
          + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
          + * IN THE SOFTWARE.
          + *
          + */
          +
          +mod add_origin;
          +use self::add_origin::AddOrigin;
          +
          +mod user_agent;
          +use self::user_agent::UserAgent;
          +
          +mod reconnect;
          +use self::reconnect::Reconnect;
          +
          +mod connection;
          +pub(super) use self::connection::Connection;
          +
          +mod discover;
          +pub use self::discover::Change;
          +pub(super) use self::discover::DynamicServiceStream;
          +
          +mod io;
          +use self::io::BoxedIo;
          +
          +mod connector;
          +pub(crate) use self::connector::Connector;
          +
          +mod executor;
          +pub(super) use self::executor::{Executor, SharedExec};
          +
          +#[cfg(feature = "_tls-any")]
          +mod tls;
          +#[cfg(feature = "_tls-any")]
          +pub(super) use self::tls::TlsConnector;
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * Permission is hereby granted, free of charge, to any person obtaining a copy
          + * of this software and associated documentation files (the "Software"), to
          + * deal in the Software without restriction, including without limitation the
          + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
          + * sell copies of the Software, and to permit persons to whom the Software is
          + * furnished to do so, subject to the following conditions:
          + *
          + * The above copyright notice and this permission notice shall be included in
          + * all copies or substantial portions of the Software.
          + *
          + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
          + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
          + * IN THE SOFTWARE.
          + *
          + */
          +
          +mod io;
          +pub(crate) use self::io::{ConnectInfoLayer, ServerIo};
          +
          +#[cfg(feature = "_tls-any")]
          +mod tls;
          +#[cfg(feature = "_tls-any")]
          +pub(crate) use self::tls::TlsAcceptor;
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * Permission is hereby granted, free of charge, to any person obtaining a copy
          + * of this software and associated documentation files (the "Software"), to
          + * deal in the Software without restriction, including without limitation the
          + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
          + * sell copies of the Software, and to permit persons to whom the Software is
          + * furnished to do so, subject to the following conditions:
          + *
          + * The above copyright notice and this permission notice shall be included in
          + * all copies or substantial portions of the Software.
          + *
          + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
          + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
          + * IN THE SOFTWARE.
          + *
          + */
          +
          +pub(crate) mod grpc_timeout;
          +#[cfg(feature = "_tls-any")]
          +pub(crate) mod tls;
          +
          +pub(crate) use self::grpc_timeout::GrpcTimeout;
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * Permission is hereby granted, free of charge, to any person obtaining a copy
          + * of this software and associated documentation files (the "Software"), to
          + * deal in the Software without restriction, including without limitation the
          + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
          + * sell copies of the Software, and to permit persons to whom the Software is
          + * furnished to do so, subject to the following conditions:
          + *
          + * The above copyright notice and this permission notice shall be included in
          + * all copies or substantial portions of the Software.
          + *
          + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
          + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
          + * IN THE SOFTWARE.
          + *
          + */
          +
          +use crate::transport::channel::BoxFuture;
          +use hyper_util::rt::TokioExecutor;
          +use std::{future::Future, sync::Arc};
          +
          +pub(crate) use hyper::rt::Executor;
          +
          +#[derive(Clone)]
          +pub(crate) struct SharedExec {
          +    inner: Arc<dyn Executor<BoxFuture<'static, ()>> + Send + Sync + 'static>,
          +}
          +
          +impl SharedExec {
          +    pub(crate) fn new<E>(exec: E) -> Self
          +    where
          +        E: Executor<BoxFuture<'static, ()>> + Send + Sync + 'static,
          +    {
          +        Self {
          +            inner: Arc::new(exec),
          +        }
          +    }
          +
          +    pub(crate) fn tokio() -> Self {
          +        Self::new(TokioExecutor::new())
          +    }
          +}
          +
          +impl<F> Executor<F> for SharedExec
          +where
          +    F: Future<Output = ()> + Send + 'static,
          +{
          +    fn execute(&self, fut: F) {
          +        self.inner.execute(Box::pin(fut))
          +    }
          +}
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * Permission is hereby granted, free of charge, to any person obtaining a copy
          + * of this software and associated documentation files (the "Software"), to
          + * deal in the Software without restriction, including without limitation the
          + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
          + * sell copies of the Software, and to permit persons to whom the Software is
          + * furnished to do so, subject to the following conditions:
          + *
          + * The above copyright notice and this permission notice shall be included in
          + * all copies or substantial portions of the Software.
          + *
          + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
          + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
          + * IN THE SOFTWARE.
          + *
          + */
          +
          +use super::Connected;
          +use std::sync::Arc;
          +
          +/// Connection info for Unix domain socket streams.
          +///
          +/// This type will be accessible through [request extensions][ext] if you're using
          +/// a unix stream.
          +///
          +/// See [Connected] for more details.
          +///
          +/// [ext]: crate::Request::extensions
          +#[derive(Clone, Debug)]
          +pub struct UdsConnectInfo {
          +    /// Peer address. This will be "unnamed" for client unix sockets.
          +    pub peer_addr: Option<Arc<tokio::net::unix::SocketAddr>>,
          +    /// Process credentials for the unix socket.
          +    pub peer_cred: Option<tokio::net::unix::UCred>,
          +}
          +
          +impl Connected for tokio::net::UnixStream {
          +    type ConnectInfo = UdsConnectInfo;
          +
          +    fn connect_info(&self) -> Self::ConnectInfo {
          +        UdsConnectInfo {
          +            peer_addr: self.peer_addr().ok().map(Arc::new),
          +            peer_cred: self.peer_cred().ok(),
          +        }
          +    }
          +}
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          // Copyright (c) 2019 Nuclear Furnace
          +//
          +// Permission is hereby granted, free of charge, to any person obtaining a copy
          +// of this software and associated documentation files (the "Software"), to deal
          +// in the Software without restriction, including without limitation the rights
          +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +// copies of the Software, and to permit persons to whom the Software is
          +// furnished to do so, subject to the following conditions:
          +//
          +// The above copyright notice and this permission notice shall be included in all
          +// copies or substantial portions of the Software.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +// SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
           
          @@ -12030,7 +16476,7 @@ THE SOFTWARE.
                           

          MIT License

          Used by:

          Copyright (c) 2014 Carl Lerche and other MIO contributors
           
          @@ -12057,7 +16503,6 @@ THE SOFTWARE.
                           

          MIT License

          Used by:

          Copyright (c) 2014-2019 Geoffroy Couprie
          @@ -12086,9 +16531,36 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          -
          Copyright (c) 2014-2021 Sean McArthur
          +                
          Copyright (c) 2014-2020 Optimal Computing (NZ) Ltd
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy of
          +this software and associated documentation files (the "Software"), to deal in
          +the Software without restriction, including without limitation the rights to
          +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
          +of the Software, and to permit persons to whom the Software is furnished to do
          +so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
          +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
          +IN THE SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Copyright (c) 2014-2026 Sean McArthur
           
           Permission is hereby granted, free of charge, to any person obtaining a copy
           of this software and associated documentation files (the "Software"), to deal
          @@ -12113,34 +16585,8 @@ THE SOFTWARE.
                           

          MIT License

          Used by:

          -
          Copyright (c) 2014-2025 Sean McArthur
          -
          -Permission is hereby granted, free of charge, to any person obtaining a copy
          -of this software and associated documentation files (the "Software"), to deal
          -in the Software without restriction, including without limitation the rights
          -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          -copies of the Software, and to permit persons to whom the Software is
          -furnished to do so, subject to the following conditions:
          -
          -The above copyright notice and this permission notice shall be included in
          -all copies or substantial portions of the Software.
          -
          -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
          -THE SOFTWARE.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          -
          Copyright (c) 2015 Jonathan Reem
           
          @@ -12173,7 +16619,7 @@ DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          Copyright (c) 2015 steffengy
           
          @@ -12181,21 +16627,6 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
           
           The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
           
          -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          - -
          Copyright (c) 2016 Paul Masurel
          -
          -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
          -
          -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
          -
           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
           
        • @@ -12259,8 +16690,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

          MIT License

          Used by:

          Copyright (c) 2017 h2 authors
           
          @@ -12293,7 +16723,7 @@ DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          Copyright (c) 2018 Carl Lerche
           
          @@ -12326,52 +16756,34 @@ DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          -
          Copyright (c) 2018 Paul Masurel
          +                
          Copyright (c) 2018 Tom Parker-Shemilt
           
          -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
           
          -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
           
          -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          -
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.
        • MIT License

          Used by:

          -
          Copyright (c) 2018 by Quickwit, Inc. 
          -
          -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
          -
          -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
          -
          -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          - -
          Copyright (c) 2018 by the project authors, as listed in the AUTHORS file. 
          -
          -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
          -
          -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
          -
          -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          -
          Copyright (c) 2018-2019 Sean McArthur
           
          @@ -12462,7 +16874,7 @@ DEALINGS IN THE SOFTWARE.
                           

          Used by:

          Copyright (c) 2019 Carl Lerche
           
          @@ -12549,44 +16961,13 @@ SOFTWARE.
                           

          MIT License

          Used by:

          -
          Copyright (c) 2019 Hyper Contributors
          -
          -Permission is hereby granted, free of charge, to any
          -person obtaining a copy of this software and associated
          -documentation files (the "Software"), to deal in the
          -Software without restriction, including without
          -limitation the rights to use, copy, modify, merge,
          -publish, distribute, sublicense, and/or sell copies of
          -the Software, and to permit persons to whom the Software
          -is furnished to do so, subject to the following
          -conditions:
          -
          -The above copyright notice and this permission notice
          -shall be included in all copies or substantial portions
          -of the Software.
          -
          -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
          -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
          -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
          -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
          -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
          -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
          -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
          -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
          -DEALINGS IN THE SOFTWARE.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          -
          Copyright (c) 2019 Tokio Contributors
           
          @@ -12621,7 +17002,7 @@ DEALINGS IN THE SOFTWARE.
                           
                           
          Copyright (c) 2019 Tower Contributors
           
          @@ -12654,10 +17035,9 @@ DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          -
          Copyright (c) 2019-2021 Tower Contributors
          +                
          Copyright (c) 2019 axum Contributors
           
           Permission is hereby granted, free of charge, to any
           person obtaining a copy of this software and associated
          @@ -12688,9 +17068,10 @@ DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          -
          Copyright (c) 2019-2024 Sean McArthur & Hyper Contributors
          +                
          Copyright (c) 2019-2021 Tower Contributors
           
           Permission is hereby granted, free of charge, to any
           person obtaining a copy of this software and associated
          @@ -12754,7 +17135,68 @@ DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          +
          Copyright (c) 2019-2026 Sean McArthur & Hyper Contributors
          +
          +Permission is hereby granted, free of charge, to any
          +person obtaining a copy of this software and associated
          +documentation files (the "Software"), to deal in the
          +Software without restriction, including without
          +limitation the rights to use, copy, modify, merge,
          +publish, distribute, sublicense, and/or sell copies of
          +the Software, and to permit persons to whom the Software
          +is furnished to do so, subject to the following
          +conditions:
          +
          +The above copyright notice and this permission notice
          +shall be included in all copies or substantial portions
          +of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
          +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
          +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
          +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
          +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
          +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
          +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
          +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
          +DEALINGS IN THE SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Copyright (c) 2021 Metrics Contributors
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          Copyright (c) 2023-2025 Sean McArthur
           
          @@ -12775,36 +17217,6 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
           LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
           OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
           THE SOFTWARE.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          - -
          Copyright (c) 2024 by Quickwit Inc.
          -
          -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
          -
          -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
          -
          -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          - -
          Copyright (c) 2024-Present Paul Masurel
          -
          -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
          -
          -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
          -
          -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
           
        • @@ -12812,6 +17224,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

          Used by:

          Copyright 2016 Nika Layzell
           
          @@ -12819,6 +17232,48 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
           
           The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
           
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Copyright 2019 gRPC authors.
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in
          +all copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
          +THE SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Copyright 2020 David Koloski
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
          +
           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
           
        • @@ -12841,25 +17296,73 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

          MIT License

          Used by:

          -
          Includes portions of humantime
          -Copyright (c) 2016 The humantime Developers
          +                
          Copyright 2021 David Koloski
           
           Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
           
           The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
           
           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          -
          -
           
        • MIT License

          Used by:

          +
          Copyright 2023 David Koloski
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Copyright 2023 David Koloski
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Copyright 2024 David Koloski
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -12882,6 +17385,65 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
           LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
           OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
           SOFTWARE.
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2016 Michael Ma
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2016 fengcen
          +Copyright (c) 2019 svartalf
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
        • MIT License

          @@ -12903,6 +17465,35 @@ furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +
        • + +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2017 Denis Kurilenko
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
           IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
           FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          @@ -12975,9 +17566,41 @@ SOFTWARE.
                           

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) 2017 Sam Rijs
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -12993,6 +17616,35 @@ furnished to do so, subject to the following conditions:
           The above copyright notice and this permission notice shall be included in all
           copies or substantial portions of the Software.
           
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2018 Canop
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
           IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
           FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          @@ -13036,7 +17688,36 @@ SOFTWARE.
                           

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) 2018 sgodwincs
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -13065,7 +17746,7 @@ SOFTWARE.
                           

          MIT License

          Used by:

          MIT License
           
          @@ -13094,36 +17775,7 @@ SOFTWARE.
                           

          MIT License

          Used by:

          -
          MIT License
          -
          -Copyright (c) 2019 Aeledfyr
          -
          -Permission is hereby granted, free of charge, to any person obtaining a copy
          -of this software and associated documentation files (the "Software"), to deal
          -in the Software without restriction, including without limitation the rights
          -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          -copies of the Software, and to permit persons to whom the Software is
          -furnished to do so, subject to the following conditions:
          -
          -The above copyright notice and this permission notice shall be included in all
          -copies or substantial portions of the Software.
          -
          -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          -SOFTWARE.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          -
          MIT License
           
          @@ -13152,8 +17804,37 @@ SOFTWARE.
                           

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) 2019 Kornel
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -13182,7 +17863,7 @@ SOFTWARE.
                           

          MIT License

          Used by:

          MIT License
           
          @@ -13236,6 +17917,40 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
           OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
           SOFTWARE.
           
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2019–2025 axum Contributors
          +
          +Permission is hereby granted, free of charge, to any
          +person obtaining a copy of this software and associated
          +documentation files (the "Software"), to deal in the
          +Software without restriction, including without
          +limitation the rights to use, copy, modify, merge,
          +publish, distribute, sublicense, and/or sell copies of
          +the Software, and to permit persons to whom the Software
          +is furnished to do so, subject to the following
          +conditions:
          +
          +The above copyright notice and this permission notice
          +shall be included in all copies or substantial portions
          +of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
          +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
          +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
          +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
          +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
          +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
          +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
          +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
          +DEALINGS IN THE SOFTWARE.
        • MIT License

          @@ -13270,7 +17985,24 @@ SOFTWARE.

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) 2020 Katharos Technology
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -13288,6 +18020,35 @@ furnished to do so, subject to the following conditions:
           The above copyright notice and this permission notice shall be included in all
           copies or substantial portions of the Software.
           
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2020 magiclen.org (Ron Li)
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
           IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
           FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          @@ -13317,6 +18078,93 @@ furnished to do so, subject to the following conditions:
           The above copyright notice and this permission notice shall be included in all
           copies or substantial portions of the Software.
           
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2020-2022 Oliver Margetts
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2020-2026 Nugine
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2021 Adel Prokurov
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
           IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
           FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          @@ -13346,6 +18194,35 @@ furnished to do so, subject to the following conditions:
           The above copyright notice and this permission notice shall be included in all
           copies or substantial portions of the Software.
           
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2022 Arthur Silva
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
           IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
           FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          @@ -13360,6 +18237,7 @@ SOFTWARE.
                           

          Used by:

          MIT License
           
          @@ -13375,6 +18253,35 @@ furnished to do so, subject to the following conditions:
           The above copyright notice and this permission notice shall be included in all
           copies or substantial portions of the Software.
           
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2022 Jeroen Van Der Donckt
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
           IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
           FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          @@ -13416,7 +18323,36 @@ SOFTWARE.

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) 2022 sarah
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -13445,8 +18381,8 @@ SOFTWARE.
                           

          MIT License

          Used by:

          MIT License
           
          @@ -13475,8 +18411,66 @@ SOFTWARE.
                           

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) 2023 sarah
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2024 Spire Team
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -13506,19 +18500,28 @@ SOFTWARE.
                           

          Used by:

          MIT License
          @@ -13545,9 +18548,9 @@ USE OR OTHER DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          MIT License
           
          @@ -13576,7 +18579,99 @@ SOFTWARE.
                           

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) [2021] [Marvin Countryman]
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Permission is hereby granted, free of charge, to any
          +person obtaining a copy of this software and associated
          +documentation files (the "Software"), to deal in the
          +Software without restriction, including without
          +limitation the rights to use, copy, modify, merge,
          +publish, distribute, sublicense, and/or sell copies of
          +the Software, and to permit persons to whom the Software
          +is furnished to do so, subject to the following
          +conditions:
          +
          +The above copyright notice and this permission notice
          +shall be included in all copies or substantial portions
          +of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
          +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
          +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
          +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
          +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
          +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
          +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
          +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
          +DEALINGS IN THE SOFTWARE.
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Permission is hereby granted, free of charge, to any
          +person obtaining a copy of this software and associated
          +documentation files (the "Software"), to deal in the
          +Software without restriction, including without
          +limitation the rights to use, copy, modify, merge,
          +publish, distribute, sublicense, and/or sell copies of
          +the Software, and to permit persons to whom the Software
          +is furnished to do so, subject to the following
          +conditions:
          +
          +The above copyright notice and this permission notice
          +shall be included in all copies or substantial portions
          +of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
          +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
          +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
          +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
          +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
          +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
          +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
          +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
          +DEALINGS IN THE SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          Permission is hereby granted, free of charge, to any person obtaining
           a copy of this software and associated documentation files (the
          @@ -13602,12 +18697,42 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          -
          The MIT License (MIT)
          +                
          Portions of this project are derived from atty, which bears the following
          +copyright notice and permission notice:
           
          -Copyright (c) 2014 Benjamin Sago
          -Copyright (c) 2021-2022 The Nushell Project Developers
          +Copyright (c) 2015-2019 Doug Tangren
          +
          +Permission is hereby granted, free of charge, to any person obtaining
          +a copy of this software and associated documentation files (the
          +"Software"), to deal in the Software without restriction, including
          +without limitation the rights to use, copy, modify, merge, publish,
          +distribute, sublicense, and/or sell copies of the Software, and to
          +permit persons to whom the Software is furnished to do so, subject to
          +the following conditions:
          +
          +The above copyright notice and this permission notice shall be
          +included in all copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
          +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
          +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
          +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
          +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
          +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
          +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License
          +
          +Copyright 2015 The Fancy Regex Authors.
           
           Permission is hereby granted, free of charge, to any person obtaining a copy
           of this software and associated documentation files (the "Software"), to deal
          @@ -13616,23 +18741,24 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
           copies of the Software, and to permit persons to whom the Software is
           furnished to do so, subject to the following conditions:
           
          -The above copyright notice and this permission notice shall be included in all
          -copies or substantial portions of the Software.
          +The above copyright notice and this permission notice shall be included in
          +all copies or substantial portions of the Software.
           
           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
           IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
           FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
           AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
           LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          -SOFTWARE.
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
          +THE SOFTWARE.
           
        • MIT License

          Used by:

          The MIT License (MIT)
           
          @@ -13655,13 +18781,63 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
           LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
           OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
           SOFTWARE.
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2014 Mathijs van de Nes
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2014 Y. T. CHUNG
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          +
        • MIT License

          Used by:

          The MIT License (MIT)
           
          @@ -13689,21 +18865,11 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          The MIT License (MIT)
           
          -Copyright (c) 2015 Andrew Gallant
          +Copyright (c) 2015 
           
           Permission is hereby granted, free of charge, to any person obtaining a copy
           of this software and associated documentation files (the "Software"), to deal
          @@ -13712,28 +18878,39 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
           copies of the Software, and to permit persons to whom the Software is
           furnished to do so, subject to the following conditions:
           
          -The above copyright notice and this permission notice shall be included in
          -all copies or substantial portions of the Software.
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
           
           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
           IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
           FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
           AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
           LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
          -THE SOFTWARE.
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
           
        • MIT License

          Used by:

          The MIT License (MIT)
           
           Copyright (c) 2015 Andrew Gallant
          -Copyright (c) 2019 Paul Masurel
           
           Permission is hereby granted, free of charge, to any person obtaining a copy
           of this software and associated documentation files (the "Software"), to deal
          @@ -13783,6 +18960,36 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
           OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
           SOFTWARE.
           
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2015 Carl Lerche + nix-rust Authors
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in
          +all copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
          +THE SOFTWARE.
           
        • @@ -13814,6 +19021,64 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +
        • + +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2015 Gerd Zellweger
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in
          +all copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
          +THE SOFTWARE.
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2015 Guillaume Gomez
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
           
        • @@ -13849,11 +19114,72 @@ SOFTWARE.

          MIT License

          Used by:

          The MIT License (MIT)
           
          -Copyright (c) 2015 Vincent Prouillet
          +Copyright (c) 2015 Markus Westerlind
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in
          +all copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
          +THE SOFTWARE.
          +
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2015 Michael Sproul
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in
          +all copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
          +THE SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2015-2020 the fiat-crypto authors (see
          +https://github.com/mit-plv/fiat-crypto/blob/master/AUTHORS).
           
           Permission is hereby granted, free of charge, to any person obtaining a copy
           of this software and associated documentation files (the "Software"), to deal
          @@ -13878,7 +19204,7 @@ SOFTWARE.
                           

          MIT License

          Used by:

          The MIT License (MIT)
           
          @@ -13894,6 +19220,35 @@ furnished to do so, subject to the following conditions:
           The above copyright notice and this permission notice shall be included in all
           copies or substantial portions of the Software.
           
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2016 nabijaczleweli
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
           IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
           FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          @@ -13967,8 +19322,36 @@ SOFTWARE.
                           

          MIT License

          Used by:

          +
          The MIT License (MIT)
          +
          +Copyright (c) 2019 Simon Heath
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          The MIT License (MIT)
           
          @@ -14035,6 +19418,36 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
           The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
           
           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2014 Benjamin Sago
          +Copyright (c) 2021-2022 The Nushell Project Developers
          +
          +Permission is hereby granted, free of charge, to any person obtaining a copy
          +of this software and associated documentation files (the "Software"), to deal
          +in the Software without restriction, including without limitation the rights
          +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          +copies of the Software, and to permit persons to whom the Software is
          +furnished to do so, subject to the following conditions:
          +
          +The above copyright notice and this permission notice shall be included in all
          +copies or substantial portions of the Software.
          +
          +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
           
        • @@ -14099,8 +19512,9 @@ SOFTWARE.
        • MIT License

          Used by:

          The MIT License (MIT)
           
          @@ -14153,6 +19567,387 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
           LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
           OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
           THE SOFTWARE.
          +
          + +
        • +

          Mozilla Public License 2.0

          +

          Used by:

          + +
          Mozilla Public License Version 2.0
          +==================================
          +
          +1. Definitions
          +--------------
          +
          +1.1. "Contributor"
          +    means each individual or legal entity that creates, contributes to
          +    the creation of, or owns Covered Software.
          +
          +1.2. "Contributor Version"
          +    means the combination of the Contributions of others (if any) used
          +    by a Contributor and that particular Contributor's Contribution.
          +
          +1.3. "Contribution"
          +    means Covered Software of a particular Contributor.
          +
          +1.4. "Covered Software"
          +    means Source Code Form to which the initial Contributor has attached
          +    the notice in Exhibit A, the Executable Form of such Source Code
          +    Form, and Modifications of such Source Code Form, in each case
          +    including portions thereof.
          +
          +1.5. "Incompatible With Secondary Licenses"
          +    means
          +
          +    (a) that the initial Contributor has attached the notice described
          +        in Exhibit B to the Covered Software; or
          +
          +    (b) that the Covered Software was made available under the terms of
          +        version 1.1 or earlier of the License, but not also under the
          +        terms of a Secondary License.
          +
          +1.6. "Executable Form"
          +    means any form of the work other than Source Code Form.
          +
          +1.7. "Larger Work"
          +    means a work that combines Covered Software with other material, in 
          +    a separate file or files, that is not Covered Software.
          +
          +1.8. "License"
          +    means this document.
          +
          +1.9. "Licensable"
          +    means having the right to grant, to the maximum extent possible,
          +    whether at the time of the initial grant or subsequently, any and
          +    all of the rights conveyed by this License.
          +
          +1.10. "Modifications"
          +    means any of the following:
          +
          +    (a) any file in Source Code Form that results from an addition to,
          +        deletion from, or modification of the contents of Covered
          +        Software; or
          +
          +    (b) any new file in Source Code Form that contains any Covered
          +        Software.
          +
          +1.11. "Patent Claims" of a Contributor
          +    means any patent claim(s), including without limitation, method,
          +    process, and apparatus claims, in any patent Licensable by such
          +    Contributor that would be infringed, but for the grant of the
          +    License, by the making, using, selling, offering for sale, having
          +    made, import, or transfer of either its Contributions or its
          +    Contributor Version.
          +
          +1.12. "Secondary License"
          +    means either the GNU General Public License, Version 2.0, the GNU
          +    Lesser General Public License, Version 2.1, the GNU Affero General
          +    Public License, Version 3.0, or any later versions of those
          +    licenses.
          +
          +1.13. "Source Code Form"
          +    means the form of the work preferred for making modifications.
          +
          +1.14. "You" (or "Your")
          +    means an individual or a legal entity exercising rights under this
          +    License. For legal entities, "You" includes any entity that
          +    controls, is controlled by, or is under common control with You. For
          +    purposes of this definition, "control" means (a) the power, direct
          +    or indirect, to cause the direction or management of such entity,
          +    whether by contract or otherwise, or (b) ownership of more than
          +    fifty percent (50%) of the outstanding shares or beneficial
          +    ownership of such entity.
          +
          +2. License Grants and Conditions
          +--------------------------------
          +
          +2.1. Grants
          +
          +Each Contributor hereby grants You a world-wide, royalty-free,
          +non-exclusive license:
          +
          +(a) under intellectual property rights (other than patent or trademark)
          +    Licensable by such Contributor to use, reproduce, make available,
          +    modify, display, perform, distribute, and otherwise exploit its
          +    Contributions, either on an unmodified basis, with Modifications, or
          +    as part of a Larger Work; and
          +
          +(b) under Patent Claims of such Contributor to make, use, sell, offer
          +    for sale, have made, import, and otherwise transfer either its
          +    Contributions or its Contributor Version.
          +
          +2.2. Effective Date
          +
          +The licenses granted in Section 2.1 with respect to any Contribution
          +become effective for each Contribution on the date the Contributor first
          +distributes such Contribution.
          +
          +2.3. Limitations on Grant Scope
          +
          +The licenses granted in this Section 2 are the only rights granted under
          +this License. No additional rights or licenses will be implied from the
          +distribution or licensing of Covered Software under this License.
          +Notwithstanding Section 2.1(b) above, no patent license is granted by a
          +Contributor:
          +
          +(a) for any code that a Contributor has removed from Covered Software;
          +    or
          +
          +(b) for infringements caused by: (i) Your and any other third party's
          +    modifications of Covered Software, or (ii) the combination of its
          +    Contributions with other software (except as part of its Contributor
          +    Version); or
          +
          +(c) under Patent Claims infringed by Covered Software in the absence of
          +    its Contributions.
          +
          +This License does not grant any rights in the trademarks, service marks,
          +or logos of any Contributor (except as may be necessary to comply with
          +the notice requirements in Section 3.4).
          +
          +2.4. Subsequent Licenses
          +
          +No Contributor makes additional grants as a result of Your choice to
          +distribute the Covered Software under a subsequent version of this
          +License (see Section 10.2) or under the terms of a Secondary License (if
          +permitted under the terms of Section 3.3).
          +
          +2.5. Representation
          +
          +Each Contributor represents that the Contributor believes its
          +Contributions are its original creation(s) or it has sufficient rights
          +to grant the rights to its Contributions conveyed by this License.
          +
          +2.6. Fair Use
          +
          +This License is not intended to limit any rights You have under
          +applicable copyright doctrines of fair use, fair dealing, or other
          +equivalents.
          +
          +2.7. Conditions
          +
          +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
          +in Section 2.1.
          +
          +3. Responsibilities
          +-------------------
          +
          +3.1. Distribution of Source Form
          +
          +All distribution of Covered Software in Source Code Form, including any
          +Modifications that You create or to which You contribute, must be under
          +the terms of this License. You must inform recipients that the Source
          +Code Form of the Covered Software is governed by the terms of this
          +License, and how they can obtain a copy of this License. You may not
          +attempt to alter or restrict the recipients' rights in the Source Code
          +Form.
          +
          +3.2. Distribution of Executable Form
          +
          +If You distribute Covered Software in Executable Form then:
          +
          +(a) such Covered Software must also be made available in Source Code
          +    Form, as described in Section 3.1, and You must inform recipients of
          +    the Executable Form how they can obtain a copy of such Source Code
          +    Form by reasonable means in a timely manner, at a charge no more
          +    than the cost of distribution to the recipient; and
          +
          +(b) You may distribute such Executable Form under the terms of this
          +    License, or sublicense it under different terms, provided that the
          +    license for the Executable Form does not attempt to limit or alter
          +    the recipients' rights in the Source Code Form under this License.
          +
          +3.3. Distribution of a Larger Work
          +
          +You may create and distribute a Larger Work under terms of Your choice,
          +provided that You also comply with the requirements of this License for
          +the Covered Software. If the Larger Work is a combination of Covered
          +Software with a work governed by one or more Secondary Licenses, and the
          +Covered Software is not Incompatible With Secondary Licenses, this
          +License permits You to additionally distribute such Covered Software
          +under the terms of such Secondary License(s), so that the recipient of
          +the Larger Work may, at their option, further distribute the Covered
          +Software under the terms of either this License or such Secondary
          +License(s).
          +
          +3.4. Notices
          +
          +You may not remove or alter the substance of any license notices
          +(including copyright notices, patent notices, disclaimers of warranty,
          +or limitations of liability) contained within the Source Code Form of
          +the Covered Software, except that You may alter any license notices to
          +the extent required to remedy known factual inaccuracies.
          +
          +3.5. Application of Additional Terms
          +
          +You may choose to offer, and to charge a fee for, warranty, support,
          +indemnity or liability obligations to one or more recipients of Covered
          +Software. However, You may do so only on Your own behalf, and not on
          +behalf of any Contributor. You must make it absolutely clear that any
          +such warranty, support, indemnity, or liability obligation is offered by
          +You alone, and You hereby agree to indemnify every Contributor for any
          +liability incurred by such Contributor as a result of warranty, support,
          +indemnity or liability terms You offer. You may include additional
          +disclaimers of warranty and limitations of liability specific to any
          +jurisdiction.
          +
          +4. Inability to Comply Due to Statute or Regulation
          +---------------------------------------------------
          +
          +If it is impossible for You to comply with any of the terms of this
          +License with respect to some or all of the Covered Software due to
          +statute, judicial order, or regulation then You must: (a) comply with
          +the terms of this License to the maximum extent possible; and (b)
          +describe the limitations and the code they affect. Such description must
          +be placed in a text file included with all distributions of the Covered
          +Software under this License. Except to the extent prohibited by statute
          +or regulation, such description must be sufficiently detailed for a
          +recipient of ordinary skill to be able to understand it.
          +
          +5. Termination
          +--------------
          +
          +5.1. The rights granted under this License will terminate automatically
          +if You fail to comply with any of its terms. However, if You become
          +compliant, then the rights granted under this License from a particular
          +Contributor are reinstated (a) provisionally, unless and until such
          +Contributor explicitly and finally terminates Your grants, and (b) on an
          +ongoing basis, if such Contributor fails to notify You of the
          +non-compliance by some reasonable means prior to 60 days after You have
          +come back into compliance. Moreover, Your grants from a particular
          +Contributor are reinstated on an ongoing basis if such Contributor
          +notifies You of the non-compliance by some reasonable means, this is the
          +first time You have received notice of non-compliance with this License
          +from such Contributor, and You become compliant prior to 30 days after
          +Your receipt of the notice.
          +
          +5.2. If You initiate litigation against any entity by asserting a patent
          +infringement claim (excluding declaratory judgment actions,
          +counter-claims, and cross-claims) alleging that a Contributor Version
          +directly or indirectly infringes any patent, then the rights granted to
          +You by any and all Contributors for the Covered Software under Section
          +2.1 of this License shall terminate.
          +
          +5.3. In the event of termination under Sections 5.1 or 5.2 above, all
          +end user license agreements (excluding distributors and resellers) which
          +have been validly granted by You or Your distributors under this License
          +prior to termination shall survive termination.
          +
          +************************************************************************
          +*                                                                      *
          +*  6. Disclaimer of Warranty                                           *
          +*  -------------------------                                           *
          +*                                                                      *
          +*  Covered Software is provided under this License on an "as is"       *
          +*  basis, without warranty of any kind, either expressed, implied, or  *
          +*  statutory, including, without limitation, warranties that the       *
          +*  Covered Software is free of defects, merchantable, fit for a        *
          +*  particular purpose or non-infringing. The entire risk as to the     *
          +*  quality and performance of the Covered Software is with You.        *
          +*  Should any Covered Software prove defective in any respect, You     *
          +*  (not any Contributor) assume the cost of any necessary servicing,   *
          +*  repair, or correction. This disclaimer of warranty constitutes an   *
          +*  essential part of this License. No use of any Covered Software is   *
          +*  authorized under this License except under this disclaimer.         *
          +*                                                                      *
          +************************************************************************
          +
          +************************************************************************
          +*                                                                      *
          +*  7. Limitation of Liability                                          *
          +*  --------------------------                                          *
          +*                                                                      *
          +*  Under no circumstances and under no legal theory, whether tort      *
          +*  (including negligence), contract, or otherwise, shall any           *
          +*  Contributor, or anyone who distributes Covered Software as          *
          +*  permitted above, be liable to You for any direct, indirect,         *
          +*  special, incidental, or consequential damages of any character      *
          +*  including, without limitation, damages for lost profits, loss of    *
          +*  goodwill, work stoppage, computer failure or malfunction, or any    *
          +*  and all other commercial damages or losses, even if such party      *
          +*  shall have been informed of the possibility of such damages. This   *
          +*  limitation of liability shall not apply to liability for death or   *
          +*  personal injury resulting from such party's negligence to the       *
          +*  extent applicable law prohibits such limitation. Some               *
          +*  jurisdictions do not allow the exclusion or limitation of           *
          +*  incidental or consequential damages, so this exclusion and          *
          +*  limitation may not apply to You.                                    *
          +*                                                                      *
          +************************************************************************
          +
          +8. Litigation
          +-------------
          +
          +Any litigation relating to this License may be brought only in the
          +courts of a jurisdiction where the defendant maintains its principal
          +place of business and such litigation shall be governed by laws of that
          +jurisdiction, without reference to its conflict-of-law provisions.
          +Nothing in this Section shall prevent a party's ability to bring
          +cross-claims or counter-claims.
          +
          +9. Miscellaneous
          +----------------
          +
          +This License represents the complete agreement concerning the subject
          +matter hereof. If any provision of this License is held to be
          +unenforceable, such provision shall be reformed only to the extent
          +necessary to make it enforceable. Any law or regulation which provides
          +that the language of a contract shall be construed against the drafter
          +shall not be used to construe this License against a Contributor.
          +
          +10. Versions of the License
          +---------------------------
          +
          +10.1. New Versions
          +
          +Mozilla Foundation is the license steward. Except as provided in Section
          +10.3, no one other than the license steward has the right to modify or
          +publish new versions of this License. Each version will be given a
          +distinguishing version number.
          +
          +10.2. Effect of New Versions
          +
          +You may distribute the Covered Software under the terms of the version
          +of the License under which You originally received the Covered Software,
          +or under the terms of any subsequent version published by the license
          +steward.
          +
          +10.3. Modified Versions
          +
          +If you create software not governed by this License, and you want to
          +create a new license for such software, you may create and use a
          +modified version of this License if you rename the license and remove
          +any references to the name of the license steward (except to note that
          +such modified license differs from this License).
          +
          +10.4. Distributing Source Code Form that is Incompatible With Secondary
          +Licenses
          +
          +If You choose to distribute Source Code Form that is Incompatible With
          +Secondary Licenses under the terms of this version of the License, the
          +notice described in Exhibit B of this License must be attached.
          +
          +Exhibit A - Source Code Form License Notice
          +-------------------------------------------
          +
          +  This Source Code Form is subject to the terms of the Mozilla Public
          +  License, v. 2.0. If a copy of the MPL was not distributed with this
          +  file, You can obtain one at http://mozilla.org/MPL/2.0/.
          +
          +If it is not possible or desirable to put the notice in a particular
          +file, then You may include the notice in a location (such as a LICENSE
          +file in a relevant directory) where a recipient would be likely to look
          +for such a notice.
          +
          +You may add additional accurate notices of copyright ownership.
          +
          +Exhibit B - "Incompatible With Secondary Licenses" Notice
          +---------------------------------------------------------
          +
          +  This Source Code Form is "Incompatible With Secondary Licenses", as
          +  defined by the Mozilla Public License, v. 2.0.
           
        • @@ -14540,7 +20335,7 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice

          Unicode License v3

          Used by:

          UNICODE LICENSE V3
           
          @@ -14587,24 +20382,28 @@ authorization of the copyright holder.
                           

          Unicode License v3

          Used by:

          UNICODE LICENSE V3
           
          @@ -14653,12 +20452,63 @@ SPDX-License-Identifier: Unicode-3.0
           Portions of ICU4X may have been adapted from ICU4C and/or ICU4J.
           ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others.
           
          +
        • +
        • +

          zlib License

          +

          Used by:

          + +
          Copyright (c) 2021 Matias Rodriguez.
          +
          +This software is provided 'as-is', without any express or implied
          +warranty. In no event will the authors be held liable for any damages
          +arising from the use of this software.
          +
          +Permission is granted to anyone to use this software for any purpose,
          +including commercial applications, and to alter it and redistribute it
          +freely, subject to the following restrictions:
          +
          +1. The origin of this software must not be misrepresented; you must not
          +   claim that you wrote the original software. If you use this software
          +   in a product, an acknowledgment in the product documentation would be
          +   appreciated but is not required.
          +2. Altered source versions must be plainly marked as such, and must not be
          +   misrepresented as being the original software.
          +3. This notice may not be removed or altered from any source distribution.
          +
        • +
        • +

          zlib License

          +

          Used by:

          + +
          Copyright (c) 2023 Matias Rodriguez.
          +
          +This software is provided 'as-is', without any express or implied
          +warranty. In no event will the authors be held liable for any damages
          +arising from the use of this software.
          +
          +Permission is granted to anyone to use this software for any purpose,
          +including commercial applications, and to alter it and redistribute it
          +freely, subject to the following restrictions:
          +
          +1. The origin of this software must not be misrepresented; you must not
          +   claim that you wrote the original software. If you use this software
          +   in a product, an acknowledgment in the product documentation would be
          +   appreciated but is not required.
          +2. Altered source versions must be plainly marked as such, and must not be
          +   misrepresented as being the original software.
          +3. This notice may not be removed or altered from any source distribution.
        • zlib License

          Used by:

          Copyright (c) 2024 Orson Peters
           
          diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi
          index 98936e0a2..54b9f8083 100644
          --- a/python/python/lancedb/_lancedb.pyi
          +++ b/python/python/lancedb/_lancedb.pyi
          @@ -26,6 +26,7 @@ from .index import (
               Fm,
               NGram,
               ZoneMap,
          +    RTree,
               HnswPq,
               HnswSq,
               HnswFlat,
          @@ -604,6 +605,7 @@ class Table:
                       Fm,
                       NGram,
                       ZoneMap,
          +            RTree,
                       FTS,
                   ],
                   replace: Optional[bool],
          @@ -629,6 +631,7 @@ class Table:
                       Fm,
                       NGram,
                       ZoneMap,
          +            RTree,
                       FTS,
                   ],
                   replace: Optional[bool],
          diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py
          index f1626c540..321a1b151 100644
          --- a/python/python/lancedb/index.py
          +++ b/python/python/lancedb/index.py
          @@ -147,6 +147,45 @@ class ZoneMap:
               pass
           
           
          +@dataclass
          +class RTree:
          +    """Describe an RTree index configuration.
          +
          +    `RTree` is a scalar index on a GeoArrow geometry column, that is, a column
          +    whose Arrow field metadata sets ``ARROW:extension:name`` to a GeoArrow type
          +    such as ``geoarrow.point``, ``geoarrow.polygon`` or ``geoarrow.wkb``. It
          +    stores the bounding box of each geometry and accelerates spatial filters
          +    passed to ``where()``.
          +
          +    The index accelerates ``ST_Intersects``, ``ST_Contains``, ``ST_Within``,
          +    ``ST_Touches``, ``ST_Crosses``, ``ST_Overlaps``, ``ST_Covers`` and
          +    ``ST_CoveredBy`` between the indexed column and a constant geometry, in
          +    either argument order, for example
          +    ``ST_Within(geom, ST_GeomFromText('POLYGON ((...))'))``, as well as
          +    ``geom IS NULL``. These filters can be combined with other conditions
          +    using ``AND``.
          +
          +    See the R-tree section of 
          +    for storing geometry, the other spatial functions, and spatial filters on
          +    vector search.
          +
          +    Remote tables send the ``RTREE`` index type to the server, which must
          +    support it.
          +
          +    Examples
          +    --------
          +    >>> config = RTree(page_size=1024)
          +
          +    Attributes
          +    ----------
          +    page_size : int, optional
          +        The maximum number of entries in each R-tree page. Must be at least 2.
          +        ``None`` uses Lance's default of 4096.
          +    """
          +
          +    page_size: Optional[int] = None
          +
          +
           @dataclass
           class FTS:
               """Describe a FTS index configuration.
          @@ -1001,4 +1040,5 @@ __all__ = [
               "LabelList",
               "Fm",
               "NGram",
          +    "RTree",
           ]
          diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py
          index 214d2255f..dee2a480d 100644
          --- a/python/python/lancedb/query.py
          +++ b/python/python/lancedb/query.py
          @@ -1647,6 +1647,10 @@ class LanceQueryBuilder(ABC):
                   -----
                   Calling this multiple times combines the filters with a logical AND
                   rather than replacing the previous filter.
          +
          +        Spatial predicates such as ``ST_Intersects(geom, ST_GeomFromText(...))``
          +        work on GeoArrow columns and use an [RTree][lancedb.index.RTree] index
          +        when one exists.
                   """
                   self._where = _combine_where(self._where, where)
                   self._postfilter = not prefilter
          @@ -4293,9 +4297,11 @@ class AsyncStandardQuery(AsyncQueryBase):
                   >>> predicate = "x > 10"
                   >>> predicate = "y > 0 AND y < 100"
                   >>> predicate = "x > 5 OR y = 'test'"
          +        >>> predicate = "ST_Intersects(geom, ST_GeomFromText('POINT (1 2)'))"
           
                   Filtering performance can often be improved by creating a scalar index
          -        on the filter column(s).
          +        on the filter column(s). Spatial predicates on GeoArrow columns use an
          +        [RTree][lancedb.index.RTree] index.
           
                   Calling this multiple times combines the filters with a logical AND
                   rather than replacing the previous filter.
          diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py
          index f984b47fb..51a656a52 100644
          --- a/python/python/lancedb/remote/table.py
          +++ b/python/python/lancedb/remote/table.py
          @@ -604,7 +604,7 @@ class RemoteTable(Table):
                   config : IndexConfigType, optional
                       The index configuration object. If provided, uses the new unified API.
                       Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
          -            BTree, Bitmap, LabelList, Fm, FTS.
          +            BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
                   replace : bool, default True
                       Whether to replace an existing index on this column.
                   wait_timeout : timedelta, optional
          diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py
          index dfb1d1cde..ff014396c 100644
          --- a/python/python/lancedb/table.py
          +++ b/python/python/lancedb/table.py
          @@ -80,6 +80,7 @@ from .index import (
               Fm,
               NGram,
               ZoneMap,
          +    RTree,
               HnswPq,
               HnswSq,
               HnswFlat,
          @@ -344,6 +345,7 @@ IndexConfigType = Union[
               Fm,
               NGram,
               ZoneMap,
          +    RTree,
               FTS,
           ]
           
          @@ -1961,7 +1963,7 @@ class Table(ABC):
                   config : IndexConfigType, optional
                       The index configuration object. If provided, uses the new unified API.
                       Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
          -            BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
          +            BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
                   replace : bool, default True
                       Whether to replace an existing index on this column.
                   exist_ok : bool, default False
          @@ -4760,7 +4762,7 @@ class LanceTable(Table):
                   config : IndexConfigType, optional
                       The index configuration object. If provided, uses the new unified API.
                       Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
          -            BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
          +            BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
                   replace : bool, default True
                       Whether to replace an existing index on this column.
                   exist_ok : bool, default False
          @@ -7347,6 +7349,7 @@ class AsyncTable:
                           Fm,
                           NGram,
                           ZoneMap,
          +                RTree,
                           FTS,
                       ]
                   ] = None,
          @@ -7428,13 +7431,14 @@ class AsyncTable:
                               Fm,
                               NGram,
                               ZoneMap,
          +                    RTree,
                               FTS,
                           ),
                       ):
                           raise TypeError(
                               "config must be an instance of IvfSq, IvfPq, IvfRq, HnswPq, HnswSq,"
          -                    " BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, or FTS, but got "
          -                    + str(type(config))
          +                    " BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, or FTS,"
          +                    " but got " + str(type(config))
                           )
                   try:
                       await self._inner.create_index(
          @@ -7474,6 +7478,7 @@ class AsyncTable:
                           Fm,
                           NGram,
                           ZoneMap,
          +                RTree,
                           FTS,
                       ]
                   ] = None,
          @@ -9820,6 +9825,7 @@ class IndexStatistics:
                   "LABEL_LIST",
                   "NGRAM",
                   "ZONEMAP",
          +        "RTREE",
               ]
               distance_type: Optional[Literal["l2", "cosine", "dot"]] = None
               num_indices: Optional[int] = None
          diff --git a/python/python/lancedb/types.py b/python/python/lancedb/types.py
          index 3d7168dcf..7684398c2 100644
          --- a/python/python/lancedb/types.py
          +++ b/python/python/lancedb/types.py
          @@ -52,6 +52,7 @@ IndexType = Literal[
               "BITMAP",
               "LABEL_LIST",
               "NGRAM",
          +    "RTREE",
               "IVF_RQ",
           ]
           
          diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py
          index e658d18e1..d222b3f94 100644
          --- a/python/python/tests/test_index.py
          +++ b/python/python/tests/test_index.py
          @@ -3,11 +3,13 @@
           
           from datetime import timedelta
           import random
          +import struct
           from typing import get_args, get_type_hints
           
           import pyarrow as pa
           import pytest
           import pytest_asyncio
          +import lancedb
           from lancedb import AsyncConnection, AsyncTable, connect_async
           from lancedb.index import (
               BTree,
          @@ -23,6 +25,7 @@ from lancedb.index import (
               Fm,
               NGram,
               ZoneMap,
          +    RTree,
               HnswPq,
               HnswSq,
               HnswFlat,
          @@ -250,6 +253,388 @@ async def test_create_fm_index(some_table: AsyncTable):
               assert indices[0].columns == ["data"]
           
           
          +POINT_TYPE = pa.struct([("x", pa.float64()), ("y", pa.float64())])
          +POLYGON_TYPE = pa.list_(pa.field("rings", pa.list_(pa.field("vertices", POINT_TYPE))))
          +
          +
          +def geoarrow_field(name: str, extension: str, data_type: pa.DataType) -> pa.Field:
          +    return pa.field(
          +        name,
          +        data_type,
          +        metadata={
          +            "ARROW:extension:name": extension,
          +            "ARROW:extension:metadata": "{}",
          +        },
          +    )
          +
          +
          +# The triangle's bounding box covers the 25 grid points with x <= 4 and y <= 4,
          +# but only the 15 with x + y <= 4 intersect the triangle itself.
          +TRIANGLE = "ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))')"
          +INTERSECTS_TRIANGLE = f"ST_Intersects(geom, {TRIANGLE})"
          +TRIANGLE_IDS = [10 * y + x for y in range(10) for x in range(10) if x + y <= 4]
          +
          +
          +def grid_points(nrows: int) -> pa.Table:
          +    """A grid of GeoArrow points in which row ``10 * y + x`` sits at ``(x, y)``."""
          +    ids = list(range(nrows))
          +    geom = pa.StructArray.from_arrays(
          +        [
          +            pa.array([float(i % 10) for i in ids]),
          +            pa.array([float(i // 10) for i in ids]),
          +        ],
          +        names=["x", "y"],
          +    )
          +    schema = pa.schema(
          +        [
          +            pa.field("id", pa.int64()),
          +            geoarrow_field("geom", "geoarrow.point", POINT_TYPE),
          +            pa.field("vector", pa.list_(pa.float32(), DIM)),
          +        ]
          +    )
          +    return pa.Table.from_arrays(
          +        [pa.array(ids, pa.int64()), geom, sample_fixed_size_list_array(nrows, DIM)],
          +        schema=schema,
          +    )
          +
          +
          +@pytest_asyncio.fixture
          +async def point_table(db_async):
          +    return await db_async.create_table("point_table", grid_points(100))
          +
          +
          +async def query_ids(query) -> list:
          +    return (await query.to_arrow())["id"].to_pylist()
          +
          +
          +@pytest.mark.asyncio
          +async def test_create_rtree_index(point_table: AsyncTable):
          +    assert sorted(await query_ids(point_table.query().where(INTERSECTS_TRIANGLE))) == (
          +        TRIANGLE_IDS
          +    )
          +
          +    await point_table.create_index("geom", config=RTree())
          +    indices = await point_table.list_indices()
          +    assert len(indices) == 1
          +    assert indices[0].name == "geom_idx"
          +    assert indices[0].index_type == "RTree"
          +    assert indices[0].columns == ["geom"]
          +    stats = await point_table.index_stats("geom_idx")
          +    assert stats.index_type == "RTREE"
          +    assert stats.num_indexed_rows == 100
          +    assert stats.num_unindexed_rows == 0
          +
          +    # The index narrows the scan to the bounding box; the exact predicate then
          +    # drops the candidates that fall outside the triangle.
          +    query = point_table.query().where(INTERSECTS_TRIANGLE)
          +    assert "ScalarIndexQuery" in await query.explain_plan(True)
          +    assert sorted(await query_ids(query)) == TRIANGLE_IDS
          +
          +
          +@pytest.mark.asyncio
          +@pytest.mark.parametrize(
          +    "predicate, expected_ids",
          +    [
          +        (INTERSECTS_TRIANGLE, TRIANGLE_IDS),
          +        (f"ST_Within(geom, {TRIANGLE})", [11, 12, 21]),
          +        (f"ST_CoveredBy(geom, {TRIANGLE})", TRIANGLE_IDS),
          +        (
          +            f"ST_Touches(geom, {TRIANGLE})",
          +            [0, 1, 2, 3, 4, 10, 13, 20, 22, 30, 31, 40],
          +        ),
          +        (f"ST_Intersects(geom, {TRIANGLE}) AND id > 20", [21, 22, 30, 31, 40]),
          +        ("ST_Intersects(geom, ST_Point(3.0, 3.0))", [33]),
          +        ("ST_Contains(geom, ST_Point(3.0, 3.0))", [33]),
          +        ("ST_Covers(geom, ST_Point(3.0, 3.0))", [33]),
          +    ],
          +)
          +async def test_rtree_index_accelerates_spatial_filters(
          +    point_table: AsyncTable, predicate: str, expected_ids: list
          +):
          +    unindexed = sorted(await query_ids(point_table.query().where(predicate)))
          +    assert unindexed == expected_ids
          +
          +    await point_table.create_index("geom", config=RTree())
          +    query = point_table.query().where(predicate)
          +    assert "ScalarIndexQuery" in await query.explain_plan(True)
          +    assert sorted(await query_ids(query)) == expected_ids
          +
          +
          +@pytest.mark.asyncio
          +async def test_rtree_index_prefilters_vector_search(point_table: AsyncTable):
          +    await point_table.create_index("geom", config=RTree())
          +    # Row 99 sits outside the triangle, and its nearest vectors are rows 98, 97, ...
          +    far_corner = list(range(99 * DIM, 100 * DIM))
          +
          +    prefiltered = point_table.query().nearest_to(far_corner).where(INTERSECTS_TRIANGLE)
          +    assert "ScalarIndexQuery" in await prefiltered.explain_plan(True)
          +    assert await query_ids(prefiltered.limit(5)) == [40, 31, 30, 22, 21]
          +
          +    postfiltered = (
          +        point_table.query()
          +        .nearest_to(far_corner)
          +        .where(INTERSECTS_TRIANGLE)
          +        .postfilter()
          +        .limit(5)
          +    )
          +    assert await query_ids(postfiltered) == []
          +
          +
          +def square(corner: float) -> list:
          +    """A 2 x 2 square polygon with its lower left corner at ``(corner, corner)``."""
          +    ring = [(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)]
          +    return [[{"x": corner + x, "y": corner + y} for x, y in ring]]
          +
          +
          +@pytest_asyncio.fixture
          +async def polygon_table(db_async):
          +    """Ten overlapping squares; row ``i`` covers ``(i, i)`` to ``(i + 2, i + 2)``."""
          +    schema = pa.schema(
          +        [
          +            pa.field("id", pa.int64()),
          +            geoarrow_field("area", "geoarrow.polygon", POLYGON_TYPE),
          +        ]
          +    )
          +    data = pa.Table.from_arrays(
          +        [
          +            pa.array(range(10), pa.int64()),
          +            pa.array([square(float(i)) for i in range(10)], POLYGON_TYPE),
          +        ],
          +        schema=schema,
          +    )
          +    return await db_async.create_table("polygons", data)
          +
          +
          +@pytest.mark.asyncio
          +@pytest.mark.parametrize(
          +    "predicate, expected_ids",
          +    [
          +        ("ST_Intersects(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
          +        ("ST_Contains(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
          +        ("ST_Covers(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
          +        ("ST_Crosses(area, ST_GeomFromText('LINESTRING (2.5 2.5, 2.5 10)'))", [1, 2]),
          +        (
          +            "ST_Overlaps(area, ST_GeomFromText('POLYGON ((3 3, 5 3, 5 5, 3 5, 3 3))'))",
          +            [2, 4],
          +        ),
          +        (
          +            "ST_Touches(area, ST_GeomFromText('POLYGON ((3 3, 5 3, 5 5, 3 5, 3 3))'))",
          +            [1, 5],
          +        ),
          +    ],
          +)
          +async def test_create_rtree_index_on_polygons(
          +    polygon_table: AsyncTable, predicate: str, expected_ids: list
          +):
          +    assert sorted(await query_ids(polygon_table.query().where(predicate))) == (
          +        expected_ids
          +    )
          +
          +    await polygon_table.create_index("area", config=RTree(page_size=2))
          +    assert (await polygon_table.list_indices())[0].index_type == "RTree"
          +
          +    query = polygon_table.query().where(predicate)
          +    assert "ScalarIndexQuery" in await query.explain_plan(True)
          +    assert sorted(await query_ids(query)) == expected_ids
          +
          +
          +@pytest.mark.asyncio
          +async def test_rtree_index_with_null_geometries(db_async):
          +    # Every third row has no geometry; the others sit on the diagonal at (i, i).
          +    geom = pa.array(
          +        [None if i % 3 == 0 else {"x": float(i), "y": float(i)} for i in range(10)],
          +        POINT_TYPE,
          +    )
          +    schema = pa.schema(
          +        [
          +            pa.field("id", pa.int64()),
          +            geoarrow_field("geom", "geoarrow.point", POINT_TYPE),
          +        ]
          +    )
          +    table = await db_async.create_table(
          +        "nulls",
          +        pa.Table.from_arrays([pa.array(range(10), pa.int64()), geom], schema=schema),
          +    )
          +    box = "ST_GeomFromText('POLYGON ((-1 -1, 1.5 -1, 1.5 1.5, -1 1.5, -1 -1))')"
          +    expected = {
          +        "geom IS NULL": [0, 3, 6, 9],
          +        "geom IS NOT NULL": [1, 2, 4, 5, 7, 8],
          +        # Row 0 is inside the box but has no geometry, so it matches neither.
          +        f"ST_Intersects(geom, {box})": [1],
          +        f"NOT ST_Intersects(geom, {box})": [2, 4, 5, 7, 8],
          +    }
          +    for predicate, ids in expected.items():
          +        assert sorted(await query_ids(table.query().where(predicate))) == ids
          +
          +    await table.create_index("geom", config=RTree())
          +    for predicate, ids in expected.items():
          +        assert sorted(await query_ids(table.query().where(predicate))) == ids
          +    for predicate in ["geom IS NULL", f"ST_Intersects(geom, {box})"]:
          +        assert "ScalarIndexQuery" in await table.query().where(predicate).explain_plan(
          +            True
          +        )
          +
          +
          +@pytest.mark.asyncio
          +async def test_create_rtree_index_on_wkb(db_async):
          +    """GeoParquet and GeoPandas data usually arrives as well-known binary."""
          +
          +    def wkb_point(x: float, y: float) -> bytes:
          +        # Byte order (1 = little endian), geometry type (1 = point), x, y.
          +        return struct.pack(">) -> PyResult Ok(LanceDbIndex::Fm(FmIndexBuilder::default())),
                       "NGram" => Ok(LanceDbIndex::NGram(NGramIndexBuilder::default())),
                       "ZoneMap" => Ok(LanceDbIndex::ZoneMap(ZoneMapIndexBuilder::default())),
          +            "RTree" => {
          +                let params = source.extract::()?;
          +                let mut builder = RTreeIndexBuilder::default();
          +                if let Some(page_size) = params.page_size {
          +                    builder = builder
          +                        .page_size(page_size)
          +                        .map_err(|err| PyValueError::new_err(err.to_string()))?;
          +                }
          +                Ok(LanceDbIndex::RTree(builder))
          +            }
                       "FTS" => {
                           let params = source.extract::()?;
                           let code_options = CodeAnalyzerOptions {
          @@ -293,7 +303,7 @@ pub fn extract_index_params(source: &Option>) -> PyResult Err(PyValueError::new_err(format!(
          -                "Invalid index type '{}'.  Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
          +                "Invalid index type '{}'.  Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
                           not_supported
                       ))),
                   }
          @@ -327,6 +337,11 @@ struct FtsParams {
               index_operators: Option,
           }
           
          +#[derive(FromPyObject)]
          +struct RTreeParams {
          +    page_size: Option,
          +}
          +
           #[derive(FromPyObject)]
           struct IvfFlatParams {
               distance_type: String,
          
          From ae665a4655198606f86820f02321e8aa508e3ce2 Mon Sep 17 00:00:00 2001
          From: Xuanwo 
          Date: Thu, 19 Nov 2026 14:12:40 +0800
          Subject: [PATCH 22/78] docs: mark Blob v2 GA for ordinary tables in Enterprise
           1.15.0 (#5094)
          
          The Quickstart and table guide describe Blob columns as Early access
          without naming a product version. Document general availability for
          ordinary tables starting with LanceDB Enterprise 1.15.0 and make the
          Realtime Engine and MemWAL scope visible in the table guide.
          
          Xuanwo confirmed Enterprise 1.15.0 as the first edition to document GA
          for ordinary-table Blob v2. Enterprise 1.13.0 and 1.14.0 retain their
          existing status. The Enterprise 1.15.0 edition must carry this wording
          when prepared from its release inputs. Earlier saved editions keep their
          historical guidance.
          
          Refs ENT-3556.
          ---
           docs/web/management/table.mdx | 10 +++-------
           docs/web/quickstart.mdx       |  4 ++--
           2 files changed, 5 insertions(+), 9 deletions(-)
          
          diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx
          index dba741c2b..c5dc4f8cd 100644
          --- a/docs/web/management/table.mdx
          +++ b/docs/web/management/table.mdx
          @@ -395,16 +395,12 @@ file, up to 64 KiB by default, and larger values are stored outside it.
           
           ### Blob columns {#multimodal-blob-v2}
           
          -Early access
          -
           Filter rows by their metadata first. Then read the matching blob bytes in
           Python, or copy the matching rows to another table with Enterprise SQL.
           
          -{/* Draft for Blob v2 GA. Confirm release status before removing Early access.
          -
          -Blob v2 GA supports standard tables. Tables with Realtime or MemWAL enabled
          -are outside the GA support scope.
          -*/}
          +Starting with LanceDB Enterprise 1.15.0, Blob v2 is generally available on
          +ordinary tables. Tables with Realtime Engine or MemWAL enabled are outside
          +this support scope.
           
           #### From image files to a filtered table {#photo-tutorial}
           
          diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx
          index dda4d9acc..12a57c06f 100644
          --- a/docs/web/quickstart.mdx
          +++ b/docs/web/quickstart.mdx
          @@ -370,8 +370,8 @@ Store images, audio, or other binary data alongside vectors and metadata, in a c
           For image files and larger payloads, follow the
           [Blob photo tutorial](/management/table#photo-tutorial) to create an ordinary
           Blob table, filter its metadata, save and check an image, and copy matching rows.
          -It includes an Embedded path and an Enterprise SQL path. Blob columns are in
          -Early access.
          +The tutorial covers LanceDB Embedded and Enterprise SQL. Blob v2 is generally
          +available on ordinary tables starting with LanceDB Enterprise 1.15.0.
           
           ## 8\. Train on your data {#8-train}
           
          
          From a274ecb16ee2abd4e9c734aa04bf8e631d0e6e79 Mon Sep 17 00:00:00 2001
          From: Will Jones 
          Date: Thu, 19 Nov 2026 08:50:49 -0800
          Subject: [PATCH 23/78] fix: bump yanked libsais-rs to 0.2.4 (#5093)
          MIME-Version: 1.0
          Content-Type: text/plain; charset=UTF-8
          Content-Transfer-Encoding: 8bit
          
          ## Summary
          
          The `deny` job on main fails because `libsais-rs` 0.2.0, pulled in by
          `lance-index`, was yanked from crates.io. This bumps it to 0.2.4 in
          `Cargo.lock` and `docs/web-tests/rs/Cargo.lock`. Lockfile-only change.
          
          ## Evidence
          
          Before (CI on main):
          
          ```text
          error[yanked]: detected yanked crate (try `cargo update -p libsais-rs`)
          advisories FAILED, bans ok, licenses ok, sources ok
          ```
          
          After (local, same args as CI):
          
          ```text
          $ cargo deny --all-features check advisories bans licenses sources
          advisories ok, bans ok, licenses ok, sources ok
          ```
          
          ## Merge Risk
          
          **Door:** two-way; lockfile patch bump.
          **Blast Radius:** `lance-index` code that builds suffix arrays.
          
          🤖 Generated with [Claude Code](https://claude.com/claude-code)
          
          Co-authored-by: Claude Opus 5.5 
          ---
           Cargo.lock                   | 4 ++--
           docs/web-tests/rs/Cargo.lock | 4 ++--
           2 files changed, 4 insertions(+), 4 deletions(-)
          
          diff --git a/Cargo.lock b/Cargo.lock
          index 44405cdf0..59cbf509e 100644
          --- a/Cargo.lock
          +++ b/Cargo.lock
          @@ -6338,9 +6338,9 @@ dependencies = [
           
           [[package]]
           name = "libsais-rs"
          -version = "0.2.0"
          +version = "0.2.4"
           source = "registry+https://github.com/rust-lang/crates.io-index"
          -checksum = "40fe164dbd47ea0c20e78a121c980ef673326905f1d4fba55e3645a20ef6717f"
          +checksum = "ec55b7be74ed721889b8bc62d53e6a032d2b3b9bb60a4942b45b1e8362e64583"
           dependencies = [
            "rayon",
           ]
          diff --git a/docs/web-tests/rs/Cargo.lock b/docs/web-tests/rs/Cargo.lock
          index 85384c8af..54dd5c8af 100644
          --- a/docs/web-tests/rs/Cargo.lock
          +++ b/docs/web-tests/rs/Cargo.lock
          @@ -3679,9 +3679,9 @@ dependencies = [
           
           [[package]]
           name = "libsais-rs"
          -version = "0.2.0"
          +version = "0.2.4"
           source = "registry+https://github.com/rust-lang/crates.io-index"
          -checksum = "40fe164dbd47ea0c20e78a121c980ef673326905f1d4fba55e3645a20ef6717f"
          +checksum = "ec55b7be74ed721889b8bc62d53e6a032d2b3b9bb60a4942b45b1e8362e64583"
           dependencies = [
            "rayon",
           ]
          
          From e0995c39c2334d3f08e2b5f58c82dfc5dadd45fc Mon Sep 17 00:00:00 2001
          From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
          Date: Thu, 19 Nov 2026 10:25:27 -0800
          Subject: [PATCH 24/78] chore(deps): bump @opentelemetry/sdk-metrics from
           2.12.0 to 2.12.1 in /nodejs (#5051)
          MIME-Version: 1.0
          Content-Type: text/plain; charset=UTF-8
          Content-Transfer-Encoding: 8bit
          
          Bumps the nodejs-deps group in /nodejs with 1 update:
          [@opentelemetry/sdk-metrics](https://github.com/open-telemetry/opentelemetry-js).
          
          Updates `@opentelemetry/sdk-metrics` from 2.12.0 to 2.12.1
          
          Release notes

          Sourced from @​opentelemetry/sdk-metrics's releases.

          v2.12.1

          2.12.1

          :bug: Bug Fixes

          • fix(resources): specify full path for ioreg command on Darwin, and kenv command on BSD for host.id @​trentm
          • ci: update the W3C harness for Python 3.14 #7236 @​adityareddy-dev
          Changelog

          Sourced from @​opentelemetry/sdk-metrics's changelog.

          2.12.1

          :bug: Bug Fixes

          • fix(resources): specify full path for ioreg command on Darwin, and kenv command on BSD for host.id @​trentm
          • ci: update the W3C harness for Python 3.14 #7236 @​adityareddy-dev
          Commits
          • 8795a06 chore: prepare next v2.x release (#7296)
          • 66a9cdd ci: update W3C harness for Python 3.14 (#7236) (#7295)
          • 55398d4 fix(resources): specify full path for ioreg command on Darwin, and kenv comma...
          • f698f0c ci: drop 'latest' dist-tag option from v2.x publish workflow (#7222)
          • See full diff in compare view

          [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=@opentelemetry/sdk-metrics&package-manager=npm_and_yarn&previous-version=2.12.0&new-version=2.12.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
          Dependabot commands and options
          You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) - `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) - `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) - `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency - `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions
          Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- nodejs/pnpm-lock.yaml | 40 +++++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/nodejs/pnpm-lock.yaml b/nodejs/pnpm-lock.yaml index e57bb68d3..df01d672a 100644 --- a/nodejs/pnpm-lock.yaml +++ b/nodejs/pnpm-lock.yaml @@ -35,7 +35,7 @@ importers: version: 3.7.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)(@types/node@22.7.4) '@opentelemetry/sdk-metrics': specifier: ^2.10.0 - version: 2.12.0(@opentelemetry/api@1.10.0) + version: 2.12.1(@opentelemetry/api@1.10.0) '@types/axios': specifier: ^0.14.0 version: 0.14.4 @@ -1399,26 +1399,26 @@ packages: resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==} engines: {node: '>=8.0.0'} - '@opentelemetry/core@2.12.0': - resolution: {integrity: sha512-1HsSAuvT4/my0QrXWsyXFdWjKaPeCHsismKZgEEIb8NK13LP6DrMRlsUbvD/0F9mDWK3xDom9AMv3IscxgOnOQ==} + '@opentelemetry/core@2.12.1': + resolution: {integrity: sha512-3hr6Pj0/G0oVgIGb97IVcw9BjZ6eudonKjrmQxw7JquyU/XmVbJelkmyoU0sT/OvHGkv+r1tcrwv8MbSX7aKHw==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.0.0 <1.10.0' - '@opentelemetry/resources@2.12.0': - resolution: {integrity: sha512-+rSRoOdln6NhXTVcBdHSlZxJDNzwxadeweK2ltZO3tVtfp6aklABc06xclDk6ovRR+EiGgIcSbh/6NgjFhnb3A==} + '@opentelemetry/resources@2.12.1': + resolution: {integrity: sha512-IwrNcuLCvnJAnNLkXxx0Uw+rjBkVW6VGQrhd7PanNf0LavOzkTk9sDAjdqegM7p/VdxefNRrii6d+wBRJfz35g==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' - '@opentelemetry/sdk-metrics@2.12.0': - resolution: {integrity: sha512-mVMaEHwCUJuY3S4Esn+nT0yQA3qCEGh+SOPJsXygU0Gl453WcsDNjtEa8EfdewMwoLyr1tlofB4fXytVpiXuow==} + '@opentelemetry/sdk-metrics@2.12.1': + resolution: {integrity: sha512-HeSblYhpds4QWliBE7ANCfoa2p3QH83uUxX4vO2qtk6BhIcqP7qDYYT36z3LOXftEBpdfbDStZxv+Cw5mqKX5g==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.9.0 <1.10.0' - '@opentelemetry/semantic-conventions@1.43.0': - resolution: {integrity: sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==} + '@opentelemetry/semantic-conventions@1.45.0': + resolution: {integrity: sha512-aOP45mbcOKbQVvFWfQmgoOPT8R2iwbbbgl83k4CujGV9BrJhFr3qG55MFpwFs4YLabpuW3HhzUY9eQxPlDqaZw==} engines: {node: '>=14'} '@protobufjs/aspromise@1.1.2': @@ -1485,7 +1485,9 @@ packages: '@smithy/core@3.24.1': resolution: {integrity: sha512-3mT7o4qQyUWttYnVK3A0Z/u3Xha3E81tXn32Tz6vjZiUXhBrkEivpw1hBYfh84iFF9CSzkBU9Y1DJ3Q6RQ231g==} engines: {node: '>=18.0.0'} - deprecated: Deprecated due to bug in browser bundling instructions https://github.com/smithy-lang/smithy-typescript/issues/2025 + deprecated: |- + Deprecated due to a bug in custom logger data redaction. Upgrade to the latest version. If you used a custom logger with this + version, review your logs and rotate any credentials or other secrets. See https://github.com/aws/aws-sdk-js-v3/issues/8393. '@smithy/credential-provider-imds@4.3.1': resolution: {integrity: sha512-0S/acwHnqX4WrjXzhdiDRxsG2s9SC0cpPIK9nZ1R6UOHd+j7uL28+4bHu22urbLk2TVw3fkp6na/+fkUt/pLNQ==} @@ -5165,24 +5167,24 @@ snapshots: '@opentelemetry/api@1.10.0': {} - '@opentelemetry/core@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/core@2.12.1(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/semantic-conventions': 1.45.0 - '@opentelemetry/resources@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/resources@2.12.1(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/core': 2.12.1(@opentelemetry/api@1.10.0) + '@opentelemetry/semantic-conventions': 1.45.0 - '@opentelemetry/sdk-metrics@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/sdk-metrics@2.12.1(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.10.0) + '@opentelemetry/core': 2.12.1(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 2.12.1(@opentelemetry/api@1.10.0) - '@opentelemetry/semantic-conventions@1.43.0': {} + '@opentelemetry/semantic-conventions@1.45.0': {} '@protobufjs/aspromise@1.1.2': optional: true From c136022c7b8645d5ce0d0b5db8a21e8587b6b2c9 Mon Sep 17 00:00:00 2001 From: Shu Chen Date: Thu, 19 Nov 2026 14:18:10 -0500 Subject: [PATCH 25/78] ci: pin third-party GitHub Actions to full commit SHAs (#4922) Pin every remaining third-party action reference in `.github/` to a full 40-character commit SHA, with the intended version in a trailing comment (`uses: owner/action@ # vX.Y.Z`), following the pins already in `cli.yml`, `typos.yml` and `make-release-commit.yml`. Fixes #3293. 53 references across 13 files change, covering 16 actions, including the branch refs called out in the issue (`dtolnay/rust-toolchain@master`, `@stable`) and `pypa/gh-action-pypi-publish@release/v1`. Each SHA is the commit its current tag or branch resolves to today, so the code that runs is unchanged. Comments name the most specific tag on that commit (for example `v2.9.3` for `Swatinem/rust-cache@v2`); where no such tag exists, they keep the original ref (`v1` for `srvaroa/labeler` and `rui314/setup-mold`, `v3` for `addnab/docker-run-action`, `stable`/`master` for `dtolnay/rust-toolchain`). The `stable` branch of `dtolnay/rust-toolchain` defaults its `toolchain` input to `stable`, so pinning its SHA keeps the `nodejs.yml` step that passes no toolchain on stable. GitHub-maintained `actions/*` references are left on their tags, as in the existing pins. Keeping SHAs current through Dependabot is the sibling issue and is not part of this change. Validation: - No third-party `uses:` reference in `.github/` is left without a 40-character SHA (53 before, 0 after). - For all 23 distinct third-party pins in `.github/`, `git ls-remote` against the upstream repository confirms the SHA is the commit that the commented tag or branch points to. A deliberately altered SHA and a reverted tag ref were both caught. - `pre-commit run` on the changed files passes (check-yaml, end-of-file, trailing whitespace, typos). - actionlint 1.7.12 reports the same 35 findings on `main` and on this branch, all of them existing ones (custom runner labels and composite actions under `workflows/`). It reports none for this change. --- .../workflows/build_linux_wheel/action.yml | 4 +-- .github/workflows/build_mac_wheel/action.yml | 2 +- .../workflows/build_windows_wheel/action.yml | 2 +- .github/workflows/cargo-publish.yml | 4 +-- .../codex-update-lance-dependency.yml | 2 +- .github/workflows/dev.yml | 4 +-- .github/workflows/docs.yml | 2 +- .github/workflows/gh-release.yml | 4 +-- .github/workflows/nodejs.yml | 20 ++++++------ .github/workflows/npm-publish.yml | 18 +++++------ .github/workflows/pypi-publish.yml | 4 +-- .github/workflows/python.yml | 8 ++--- .github/workflows/rust.yml | 32 +++++++++---------- 13 files changed, 53 insertions(+), 53 deletions(-) diff --git a/.github/workflows/build_linux_wheel/action.yml b/.github/workflows/build_linux_wheel/action.yml index 44ce82ee5..51cd20ab0 100644 --- a/.github/workflows/build_linux_wheel/action.yml +++ b/.github/workflows/build_linux_wheel/action.yml @@ -54,7 +54,7 @@ runs: grep '^name = ' python/pyproject.toml - name: Build x86_64 Manylinux wheel if: ${{ inputs.arm-build == 'false' }} - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: maturin-version: "1.12.4" command: build @@ -72,7 +72,7 @@ runs: /usr/local/bin/protoc --version - name: Build Arm Manylinux Wheel if: ${{ inputs.arm-build == 'true' }} - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: maturin-version: "1.12.4" command: build diff --git a/.github/workflows/build_mac_wheel/action.yml b/.github/workflows/build_mac_wheel/action.yml index 727cd190c..ba7b7b1c5 100644 --- a/.github/workflows/build_mac_wheel/action.yml +++ b/.github/workflows/build_mac_wheel/action.yml @@ -14,7 +14,7 @@ runs: steps: - uses: ./.github/actions/setup-protoc - name: Build wheel - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: command: build maturin-version: "1.12.4" diff --git a/.github/workflows/build_windows_wheel/action.yml b/.github/workflows/build_windows_wheel/action.yml index 3d92d818a..0d061ac59 100644 --- a/.github/workflows/build_windows_wheel/action.yml +++ b/.github/workflows/build_windows_wheel/action.yml @@ -17,7 +17,7 @@ runs: run: git config --global core.longpaths true - uses: ./.github/actions/setup-protoc - name: Build wheel - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: command: build maturin-version: "1.12.4" diff --git a/.github/workflows/cargo-publish.yml b/.github/workflows/cargo-publish.yml index 052fb1876..83593307b 100644 --- a/.github/workflows/cargo-publish.yml +++ b/.github/workflows/cargo-publish.yml @@ -25,14 +25,14 @@ jobs: if: startsWith(github.ref, 'refs/tags/v') steps: - uses: actions/checkout@v6 - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: workspaces: rust - name: Install dependencies run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: rust-lang/crates-io-auth-action@v1 + - uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 id: auth - name: Publish the package run: | diff --git a/.github/workflows/codex-update-lance-dependency.yml b/.github/workflows/codex-update-lance-dependency.yml index 79ef84364..ef59213bd 100644 --- a/.github/workflows/codex-update-lance-dependency.yml +++ b/.github/workflows/codex-update-lance-dependency.yml @@ -44,7 +44,7 @@ jobs: run: npm install -g @openai/codex - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: toolchain: stable components: clippy, rustfmt diff --git a/.github/workflows/dev.yml b/.github/workflows/dev.yml index eac4cc4fc..64a6971e6 100644 --- a/.github/workflows/dev.yml +++ b/.github/workflows/dev.yml @@ -18,7 +18,7 @@ jobs: name: Label PR runs-on: ubuntu-latest steps: - - uses: srvaroa/labeler@v1 + - uses: srvaroa/labeler@9c29ad1ef33d169f9ef33c52722faf47a566bcf3 # v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} commitlint: @@ -30,7 +30,7 @@ jobs: - uses: actions/setup-node@v6 with: node-version: "24" - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 # These rules are disabled because Github will always ensure there diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index fb3fb1d6a..3dc4dab56 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -47,7 +47,7 @@ jobs: python-version: "3.10" cache: "pip" cache-dependency-path: "docs/requirements.txt" - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - name: Build Python working-directory: python run: | diff --git a/.github/workflows/gh-release.yml b/.github/workflows/gh-release.yml index bbaade34c..eedf8450c 100644 --- a/.github/workflows/gh-release.yml +++ b/.github/workflows/gh-release.yml @@ -77,7 +77,7 @@ jobs: echo "from_tag=$FROM_TAG" >> $GITHUB_OUTPUT - name: Create Release Notes id: release_notes - uses: mikepenz/release-changelog-builder-action@v4 + uses: mikepenz/release-changelog-builder-action@32e3c96f29a6532607f638797455e9e98cfc703d # v4.2.2 with: configuration: .github/release_notes.json toTag: ${{ steps.extract_version.outputs.tag }} @@ -85,7 +85,7 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Create GH release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2 with: # Marking betas as pre-releases keeps them from taking the "Latest" # badge on the releases page. diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 4d28ca4a1..9a21786d2 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -42,7 +42,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -52,14 +52,14 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: components: rustfmt, clippy - name: Install dependencies run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -98,7 +98,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -110,7 +110,7 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -188,7 +188,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -196,7 +196,7 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Same crate, profile and target as the `linux` job above, so reuse # its cache: rust-cache keys on the job id by default, and this job @@ -249,7 +249,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -259,11 +259,11 @@ jobs: cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml # Use the same pinned compiler for cache selection and the native build. - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: cache: false rustflags: "" - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index ac95b5a47..6de291c7d 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -167,7 +167,7 @@ jobs: # Cargo also checks out Lance test fixtures below its git cache path. run: git config --global core.longpaths true - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - name: Setup node @@ -178,7 +178,7 @@ jobs: cache: pnpm cache-dependency-path: nodejs/pnpm-lock.yaml - name: Install - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable if: ${{ !matrix.settings.docker }} with: toolchain: stable @@ -194,7 +194,7 @@ jobs: # re-runs regardless, since the local crate changes every time, so the # win is larger on the non-LTO jobs than here. - name: Cache cargo (native builds) - uses: Swatinem/rust-cache@v2 + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 if: ${{ !matrix.settings.docker }} with: # The release profile and per-target dirs differ from what the test @@ -216,7 +216,7 @@ jobs: # that built these artifacts -- safe, since cargo fingerprints the real # one; a base-image bump just costs one cold build. - name: Cache cargo (docker builds) - uses: Swatinem/rust-cache@v2 + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 if: ${{ matrix.settings.docker }} with: key: docker-${{ matrix.settings.target }} @@ -225,17 +225,17 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile - name: Install Zig - uses: mlugg/setup-zig@v2 + uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 if: ${{ contains(matrix.settings.target, 'musl') }} with: version: 0.14.1 - name: Install cargo-zigbuild - uses: taiki-e/install-action@v2 + uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3 if: ${{ contains(matrix.settings.target, 'musl') }} with: tool: cargo-zigbuild - name: Build in docker - uses: addnab/docker-run-action@v3 + uses: addnab/docker-run-action@4f65fabd2431ebc8d299f8e5a018d79a769ae185 # v3 if: ${{ matrix.settings.docker }} with: image: ${{ matrix.settings.docker }} @@ -352,7 +352,7 @@ jobs: steps: - uses: actions/checkout@v6 - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - name: Setup Node.js 24 for install @@ -404,7 +404,7 @@ jobs: steps: - uses: actions/checkout@v6 - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - name: Setup node diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index 8730e220d..304e96857 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -184,7 +184,7 @@ jobs: with: python-version: "3.12" - name: Build sdist - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: maturin-version: "1.12.4" command: sdist @@ -311,7 +311,7 @@ jobs: # `docker://ghcr.io/:` image reference that GHA tries to pull. - name: Publish to PyPI if: steps.choose_repo.outputs.repo == 'pypi' - uses: pypa/gh-action-pypi-publish@release/v1 + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 with: packages-dir: target/wheels/ report-failure: diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index e208ac7cd..62da9cf6e 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -112,7 +112,7 @@ jobs: # `pip install -e .` builds the extension with maturin, which is most of # this job's ~33 minutes. It had no Rust cache, so every dependency was # recompiled from scratch on every run. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -198,7 +198,7 @@ jobs: python-version: "3.13" # maturin runs cargo natively on macOS (docker is Linux-only), so the host # target dir is cacheable. This job had no Rust cache. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -236,7 +236,7 @@ jobs: # maturin runs cargo natively on Windows (docker is Linux-only), so the # host target dir is cacheable. This job had no Rust cache at all and so # rebuilt every dependency from scratch on every run. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. The repo sits at # GitHub's cache cap, so per-PR saves just evict main's entries. @@ -271,7 +271,7 @@ jobs: python-version: "3.10" # As with Doctest, `pip install -e .` compiles the extension and this job # had no Rust cache, which is most of its ~37 minutes. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 636c1a7bf..b3805b422 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -42,7 +42,7 @@ jobs: timeout-minutes: 15 steps: - uses: actions/checkout@v6 - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 - name: Read the pinned Lance tag id: lance run: | @@ -108,10 +108,10 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: components: rustfmt, clippy - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -135,7 +135,7 @@ jobs: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v6 - - uses: EmbarkStudios/cargo-deny-action@v2 + - uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1 with: command: check advisories bans licenses sources @@ -151,7 +151,7 @@ jobs: - uses: actions/checkout@v6 # Building without a lock file often requires the latest Rust version since downstream # dependencies may have updated their minimum Rust version. - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: toolchain: "stable" # The explicit cache below runs after lock removal and only saves on main. @@ -159,8 +159,8 @@ jobs: # Remove cargo.lock to force a fresh build - name: Remove Cargo.lock run: rm -f Cargo.lock - - uses: rui314/setup-mold@v1 - - uses: Swatinem/rust-cache@v2 + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -208,7 +208,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -218,7 +218,7 @@ jobs: run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: rui314/setup-mold@v1 + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 - name: Make Swap run: | swapfile=/swapfile @@ -280,7 +280,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Remote tests use a different feature graph from the main Linux # job. Cache downloads, but build into a fresh target directory. @@ -290,7 +290,7 @@ jobs: run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: rui314/setup-mold@v1 + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 - name: Run remote tests run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests @@ -317,7 +317,7 @@ jobs: python-version: "3.13" - name: CPU features run: sysctl -a | grep cpu - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # PyO3 caches the interpreter library path; runner images can differ. key: ${{ matrix.mac-runner }}-python-${{ steps.python.outputs.python-version }} @@ -358,7 +358,7 @@ jobs: run: git config --global core.longpaths true - name: Set target run: rustup target add ${{ matrix.target }} - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -397,7 +397,7 @@ jobs: run: git config --global core.longpaths true - name: Set target run: rustup target add aarch64-pc-windows-msvc - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -437,10 +437,10 @@ jobs: sudo apt update sudo apt install -y protobuf-compiler libssl-dev - name: Install ${{ matrix.msrv }} - uses: dtolnay/rust-toolchain@master + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master with: toolchain: ${{ matrix.msrv }} - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes From 7d33f7ba9442715e0b00cec8f70a1374b0647149 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 19 Nov 2026 11:25:27 -0800 Subject: [PATCH 26/78] ci: prioritize Rust security updates in dependabot config (#5100) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Dependabot wasn't getting security fixes in, and its Rust PRs were failing CI: - Security updates were disabled for the repo, so ~170 open alerts never got a PR. (Now enabled in repo settings; not part of this diff.) - The `pip` entry for `/python` never touched `uv.lock`, so Python had no Dependabot PRs at all. - With `versioning-strategy: lockfile-only`, breaking bumps such as reqwest 0.12 → 0.13 (#4781), tokenizers 0.19 → 0.23 (#4905), sha2 (#4230) and base64 (#4229) write a `Cargo.lock` that the `Cargo.toml` requirements don't allow. Every `--locked` build then fails before compiling. The priority is Rust, which is statically linked into the shipped binaries. Python and npm deps are resolved in users' environments, so those are best effort. | Entry | Version updates | Security updates | |---|---|---| | cargo `/` | weekly, minor/patch, one group | grouped | | uv `/python` (was `pip`) | monthly, minor/patch, one group | grouped | | npm `/nodejs`, `/nodejs/examples` | monthly, minor/patch, one group | grouped | | docs, docs tests, `/java` | off | grouped | Breaking bumps are excluded with `allow.update-types`, which the docs say applies only to version updates. An `ignore` rule would also suppress security updates. `dependency-type: all` keeps transitive dependencies in scope for security fixes, which also means the weekly cargo PR now bumps transitive crates within their allowed ranges. A security fix that's only available as a breaking bump will still produce a failing PR and need a manual `Cargo.toml` change. ## Merge Risk **Door:** two-way; config only. **Blast Radius:** Dependabot PRs. Config errors only surface after merge, on Dependabot's next run. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .github/dependabot.yml | 165 ++++++++++++++++++++++++++++++----------- 1 file changed, 120 insertions(+), 45 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d625b0698..4f5ff4bd4 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,70 +1,145 @@ version: 2 -# Scope: the root Cargo workspace, which produces the Rust binaries we -# ship to users (the Node.js and Python native extensions). The -# `rust/lancedb` library crate shares the same lockfile; its consumers -# pick their own dependency versions, but bumping transitive deps here -# keeps the binaries we ship current. +# Every entry uses `versioning-strategy: lockfile-only`: bump the lockfile, +# never widen or raise the version requirements in manifests. Those ranges are +# our library consumers' constraints, not ours. +# +# Because of that, version updates are limited to minor and patch bumps. +# A semver-breaking bump (including 0.x minor bumps such as 0.12 -> 0.13) +# can't be satisfied without editing a manifest, so Dependabot would produce a +# lockfile that fails `cargo --locked` and every CI job. We do those by hand. +# This is done with `allow` rather than `ignore` because `allow.update-types` +# only filters version updates; an `ignore` rule would also suppress security +# updates. `dependency-type: all` matters for the same reason: `allow` does +# apply to security updates otherwise, and most advisories are in transitive +# dependencies. +# +# Security updates are grouped so advisories that land together become one PR. +# They ignore `schedule` and `cooldown` and are opened as soon as an advisory +# is published. updates: + # Highest priority: the root Cargo workspace is statically linked into the + # Node.js and Python native extensions we ship, so users can't patch these + # themselves. Weekly updates keep the lockfile close to current, so security + # fixes are usually small patch bumps. - package-ecosystem: cargo directory: / schedule: interval: weekly - open-pull-requests-limit: 10 - # Only update Cargo.lock, never widen/raise the version requirements in - # Cargo.toml. The goal is keeping the lockfile (and the binaries we ship) - # current on security fixes, not forcing our library's consumers onto - # newer minimum versions. + day: wednesday + cooldown: + default-days: 2 versioning-strategy: lockfile-only - groups: - # The arrow-rs and datafusion crates are released in lockstep and have to - # move together, so keep them in one PR instead of one per sub-crate. - # Listed first: a dependency joins the first group it matches. - arrow-datafusion: - patterns: - - arrow - - arrow-* - - parquet - - parquet-* - - datafusion - - datafusion-* - - object_store - rust-minor-patch: + allow: + - dependency-type: all update-types: - - minor - - patch + - version-update:semver-minor + - version-update:semver-patch + groups: + cargo: + applies-to: version-updates + patterns: + - "*" + cargo-security: + applies-to: security-updates + patterns: + - "*" - - package-ecosystem: pip + # Python and Node.js dependencies are resolved in the user's own environment, + # so these lockfiles only affect our dev/test setup. Lower priority: monthly. + - package-ecosystem: uv directory: /python schedule: - interval: weekly - # Only update uv.lock, never widen version requirements in pyproject.toml. + interval: monthly + cooldown: + default-days: 2 versioning-strategy: lockfile-only + allow: + - dependency-type: all + update-types: + - version-update:semver-minor + - version-update:semver-patch groups: - python-deps: + python: + applies-to: version-updates patterns: - "*" - - # The npm ecosystem covers pnpm lockfiles. There are two separate installs: - # the bindings themselves and the examples, which have their own lockfile. - # As with cargo and pip above, only bump the lockfile — the version ranges - # in package.json are our consumers' constraints, not ours. - - package-ecosystem: npm - directory: /nodejs - schedule: - interval: weekly - versioning-strategy: lockfile-only - groups: - nodejs-deps: + python-security: + applies-to: security-updates patterns: - "*" - package-ecosystem: npm - directory: /nodejs/examples + directories: + - /nodejs + - /nodejs/examples schedule: - interval: weekly + interval: monthly + cooldown: + default-days: 2 versioning-strategy: lockfile-only + allow: + - dependency-type: all + update-types: + - version-update:semver-minor + - version-update:semver-patch groups: - nodejs-examples-deps: + nodejs: + applies-to: version-updates + patterns: + - "*" + nodejs-security: + applies-to: security-updates + patterns: + - "*" + + # Docs, docs tests, and Java. Security updates scan these lockfiles whether or + # not they're listed here; these entries only exist to group those PRs. + # `open-pull-requests-limit: 0` turns off version updates. + - package-ecosystem: cargo + directory: /docs/web-tests/rs + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + docs-cargo-security: + applies-to: security-updates + patterns: + - "*" + + - package-ecosystem: npm + directories: + - /docs/web-tests/ts + - /docs/web-tests/blob-v2/ts + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + docs-npm-security: + applies-to: security-updates + patterns: + - "*" + + - package-ecosystem: pip + directories: + - /docs + - /docs/web-tests/blob-v2/py + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + docs-pip-security: + applies-to: security-updates + patterns: + - "*" + + - package-ecosystem: maven + directory: /java + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + maven-security: + applies-to: security-updates patterns: - "*" From 3e712f5105a77a210ba4ff0c172fa6c84fe7fc13 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 19 Nov 2026 11:25:46 -0800 Subject: [PATCH 27/78] fix: bump blob v2 docs test to lancedb 0.42.0-beta.20 (#5102) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary The blob v2 TypeScript docs test pinned `@lancedb/lancedb` `0.41.0-beta.8`, which pulls `@huggingface/transformers` 3.0.2 and `sharp` 0.33.5. Aikido flags that `sharp` with 2 critical and 1 high advisory. Bumping to `0.42.0-beta.20` brings transformers 4.3.2 and `sharp` 0.35.5, matching what the `nodejs` package already ships. The stable `0.41.0` still uses transformers 3.0.2, so it doesn't fix this. ## Evidence `npm install --package-lock-only` reports `found 0 vulnerabilities`, and `npm test` passes 4/4 locally against `0.42.0-beta.20`. ## Merge Risk **Door:** two-way; only a docs test lockfile changes. **Blast Radius:** none (docs test only, not run in PR CI). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- docs/web-tests/blob-v2/ts/package-lock.json | 872 +++++++++++--------- docs/web-tests/blob-v2/ts/package.json | 2 +- 2 files changed, 468 insertions(+), 406 deletions(-) diff --git a/docs/web-tests/blob-v2/ts/package-lock.json b/docs/web-tests/blob-v2/ts/package-lock.json index 9426f2b18..914855656 100644 --- a/docs/web-tests/blob-v2/ts/package-lock.json +++ b/docs/web-tests/blob-v2/ts/package-lock.json @@ -8,95 +8,126 @@ "name": "lancedb-blob-v2-docs", "version": "0.0.0", "dependencies": { - "@lancedb/lancedb": "0.41.0-beta.8", + "@lancedb/lancedb": "0.42.0-beta.20", "apache-arrow": "21.2.0" + }, + "engines": { + "node": ">=22.6.0" } }, "node_modules/@emnapi/runtime": { "version": "1.11.3", "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", - "license": "MIT", "optional": true, "dependencies": { "tslib": "^2.4.0" } }, "node_modules/@huggingface/jinja": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.3.4.tgz", - "integrity": "sha512-kFFQWJiWwvxezKQnvH1X7GjsECcMljFx+UZK9hx6P26aVHwwidJVTB0ptLfRVZQvVkOGHoMmTGvo4nT0X9hHOA==", - "license": "MIT", + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.5.13.tgz", + "integrity": "sha512-jM17MqFily1iyT/1LD3r5w8/CZiyapVB0+7vOw48PfVtzyKsXStmHE4jVTyDAD05Tqv3un1xrS9ILUU1ugQAYQ==", "optional": true, "engines": { "node": ">=18" } }, + "node_modules/@huggingface/tokenizers": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@huggingface/tokenizers/-/tokenizers-0.2.0.tgz", + "integrity": "sha512-LidMHe1FpcSYH4vcSjXooda34pC0M8m1gmDOv7SQi6Iv+ib1zX7J3sHBCC9/3FPCkn2k1b55FneVqMRxrr99pg==", + "optional": true + }, "node_modules/@huggingface/transformers": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@huggingface/transformers/-/transformers-3.0.2.tgz", - "integrity": "sha512-lTyS81eQazMea5UCehDGFMfdcNRZyei7XQLH5X6j4AhA/18Ka0+5qPgMxUxuZLU4xkv60aY2KNz9Yzthv6WVJg==", - "license": "Apache-2.0", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@huggingface/transformers/-/transformers-4.3.2.tgz", + "integrity": "sha512-V3+dqf3iWlRYJ9I9GreM3zGQd0lAXnnoPeddmkOQYWAEE4l/+Fi6p7tx/qVUJlKQgLXGim2W76rTOzz+eC0i7g==", "optional": true, "dependencies": { - "@huggingface/jinja": "^0.3.0", - "onnxruntime-node": "1.19.2", - "onnxruntime-web": "1.21.0-dev.20241024-d9ca84ef96", - "sharp": "^0.33.5" + "@huggingface/jinja": "^0.5.10", + "@huggingface/tokenizers": "^0.2.0", + "onnxruntime-node": "1.30.0", + "onnxruntime-web": "1.31.0-dev.20260914-8d85527a0", + "sharp": "^0.35.4" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "optional": true, + "engines": { + "node": ">=18" } }, "node_modules/@img/sharp-darwin-arm64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz", - "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", "cpu": [ "arm64" ], - "license": "Apache-2.0", "optional": true, "os": [ "darwin" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-darwin-arm64": "1.0.4" + "@img/sharp-libvips-darwin-arm64": "1.3.4" } }, "node_modules/@img/sharp-darwin-x64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz", - "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", "cpu": [ "x64" ], - "license": "Apache-2.0", "optional": true, "os": [ "darwin" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-darwin-x64": "1.0.4" + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, "node_modules/@img/sharp-libvips-darwin-arm64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz", - "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", "cpu": [ "arm64" ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "darwin" @@ -106,13 +137,12 @@ } }, "node_modules/@img/sharp-libvips-darwin-x64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz", - "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", "cpu": [ "x64" ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "darwin" @@ -122,16 +152,12 @@ } }, "node_modules/@img/sharp-libvips-linux-arm": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz", - "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", "cpu": [ "arm" ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -141,16 +167,42 @@ } }, "node_modules/@img/sharp-libvips-linux-arm64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz", - "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", "cpu": [ "arm64" ], - "libc": [ - "glibc" + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -160,16 +212,12 @@ } }, "node_modules/@img/sharp-libvips-linux-s390x": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.0.4.tgz", - "integrity": "sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -179,16 +227,12 @@ } }, "node_modules/@img/sharp-libvips-linux-x64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz", - "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", "cpu": [ "x64" ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -198,16 +242,12 @@ } }, "node_modules/@img/sharp-libvips-linuxmusl-arm64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.0.4.tgz", - "integrity": "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", "cpu": [ "arm64" ], - "libc": [ - "musl" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -217,16 +257,12 @@ } }, "node_modules/@img/sharp-libvips-linuxmusl-x64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.0.4.tgz", - "integrity": "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", "cpu": [ "x64" ], - "libc": [ - "musl" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -236,234 +272,268 @@ } }, "node_modules/@img/sharp-linux-arm": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz", - "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", "cpu": [ "arm" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-arm": "1.0.5" + "@img/sharp-libvips-linux-arm": "1.3.4" } }, "node_modules/@img/sharp-linux-arm64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz", - "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-arm64": "1.0.4" + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" } }, "node_modules/@img/sharp-linux-s390x": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.33.5.tgz", - "integrity": "sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-s390x": "1.0.4" + "@img/sharp-libvips-linux-s390x": "1.3.4" } }, "node_modules/@img/sharp-linux-x64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz", - "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", "cpu": [ "x64" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-x64": "1.0.4" + "@img/sharp-libvips-linux-x64": "1.3.4" } }, "node_modules/@img/sharp-linuxmusl-arm64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.33.5.tgz", - "integrity": "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", "cpu": [ "arm64" ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-arm64": "1.0.4" + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" } }, "node_modules/@img/sharp-linuxmusl-x64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.33.5.tgz", - "integrity": "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", "cpu": [ "x64" ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-x64": "1.0.4" + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" } }, "node_modules/@img/sharp-wasm32": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.33.5.tgz", - "integrity": "sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", "cpu": [ "wasm32" ], - "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", "optional": true, "dependencies": { - "@emnapi/runtime": "^1.2.0" + "@img/sharp-wasm32": "0.35.5" }, "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" } }, "node_modules/@img/sharp-win32-ia32": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.33.5.tgz", - "integrity": "sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", "cpu": [ "ia32" ], - "license": "Apache-2.0 AND LGPL-3.0-or-later", "optional": true, "os": [ "win32" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": "^20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" } }, "node_modules/@img/sharp-win32-x64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz", - "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", "cpu": [ "x64" ], - "license": "Apache-2.0 AND LGPL-3.0-or-later", "optional": true, "os": [ "win32" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" } }, - "node_modules/@isaacs/fs-minipass": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", - "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", - "license": "ISC", - "optional": true, - "dependencies": { - "minipass": "^7.0.4" - }, - "engines": { - "node": ">=18.0.0" - } - }, "node_modules/@lancedb/lancedb": { - "version": "0.41.0-beta.8", - "resolved": "https://registry.npmjs.org/@lancedb/lancedb/-/lancedb-0.41.0-beta.8.tgz", - "integrity": "sha512-W6Sw1rJgJJAT75jXom2fkNvE976iH8EO74ShytymS6sEzCj63gQXQqCYg+jPvQva/dnvYQiOeOGsdkGDFwKmlA==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb/-/lancedb-0.42.0-beta.20.tgz", + "integrity": "sha512-sPccnvQbxgybSu3nypRKXtbWE1pa90imQuOnxNQ1w68pz6KFISereKYp9o0HtukMqJWYfrezetYJPG+uC3KprA==", "cpu": [ "x64", "arm64" ], - "license": "Apache-2.0", "os": [ "darwin", "linux", @@ -477,14 +547,14 @@ "node": ">= 22" }, "optionalDependencies": { - "@huggingface/transformers": "3.0.2", - "@lancedb/lancedb-darwin-arm64": "0.41.0-beta.8", - "@lancedb/lancedb-linux-arm64-gnu": "0.41.0-beta.8", - "@lancedb/lancedb-linux-arm64-musl": "0.41.0-beta.8", - "@lancedb/lancedb-linux-x64-gnu": "0.41.0-beta.8", - "@lancedb/lancedb-linux-x64-musl": "0.41.0-beta.8", - "@lancedb/lancedb-win32-arm64-msvc": "0.41.0-beta.8", - "@lancedb/lancedb-win32-x64-msvc": "0.41.0-beta.8", + "@huggingface/transformers": "4.3.2", + "@lancedb/lancedb-darwin-arm64": "0.42.0-beta.20", + "@lancedb/lancedb-linux-arm64-gnu": "0.42.0-beta.20", + "@lancedb/lancedb-linux-arm64-musl": "0.42.0-beta.20", + "@lancedb/lancedb-linux-x64-gnu": "0.42.0-beta.20", + "@lancedb/lancedb-linux-x64-musl": "0.42.0-beta.20", + "@lancedb/lancedb-win32-arm64-msvc": "0.42.0-beta.20", + "@lancedb/lancedb-win32-x64-msvc": "0.42.0-beta.20", "openai": "4.29.2" }, "peerDependencies": { @@ -498,13 +568,12 @@ } }, "node_modules/@lancedb/lancedb-darwin-arm64": { - "version": "0.41.0-beta.8", - "resolved": "https://registry.npmjs.org/@lancedb/lancedb-darwin-arm64/-/lancedb-darwin-arm64-0.41.0-beta.8.tgz", - "integrity": "sha512-M1o7VQmB1th9L8YnOqXlxruB1jW6Gns9rTS5H5rCzjv25CTEq/mw9uwl6jrDlLiuVSLWJ89Jj2EDUMH8ZKkEbw==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-darwin-arm64/-/lancedb-darwin-arm64-0.42.0-beta.20.tgz", + "integrity": "sha512-UbIQknmvPdkHAn/2fXE41YDXXyZKoBjeW3TTpWMY9CdcBr6zOEvoL6hIcfIZ7ToN5B8kLePo6Vigc6SOY+Bt4w==", "cpu": [ "arm64" ], - "license": "Apache-2.0", "optional": true, "os": [ "darwin" @@ -514,16 +583,12 @@ } }, "node_modules/@lancedb/lancedb-linux-arm64-gnu": { - "version": "0.41.0-beta.8", - "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-arm64-gnu/-/lancedb-linux-arm64-gnu-0.41.0-beta.8.tgz", - "integrity": "sha512-X5lJ2JWMHIrvq/IkkHPjQ3v6myv2jZKK/eayiLe/8Wasxt6LIm9Z7KJYLtXpp5y+kqncAmMRP+BaAJAY02FgvQ==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-arm64-gnu/-/lancedb-linux-arm64-gnu-0.42.0-beta.20.tgz", + "integrity": "sha512-Pkn9fjIsYu5h4grzbCp+X7HT/byHd4N0/BFpvN4oRW703kjkwp9QzwSyRRvXEtgywv47diJu2W0cl8+8su5XtQ==", "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" @@ -533,16 +598,12 @@ } }, "node_modules/@lancedb/lancedb-linux-arm64-musl": { - "version": "0.41.0-beta.8", - "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-arm64-musl/-/lancedb-linux-arm64-musl-0.41.0-beta.8.tgz", - "integrity": "sha512-9reTx4gKOIZlx1hNp3s+O2tMv56aF0bp+kt22+XniwL6xLhVyMlyp+cRnhReVqbvu3Ykqe1lZEQO8U3EXuxSFg==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-arm64-musl/-/lancedb-linux-arm64-musl-0.42.0-beta.20.tgz", + "integrity": "sha512-A2fKIET4p1r1geWFX5omLCtjg03c8V42QQJPtCUjuX9sG9EXcNM6tHQSSJj3En/7T4N5gSlSzS3dcy4ciYEVYQ==", "cpu": [ "arm64" ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" @@ -552,16 +613,12 @@ } }, "node_modules/@lancedb/lancedb-linux-x64-gnu": { - "version": "0.41.0-beta.8", - "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-x64-gnu/-/lancedb-linux-x64-gnu-0.41.0-beta.8.tgz", - "integrity": "sha512-tu9RvxpNNVeUOIWrjmsZgufP+ebBvNES0x4D4qHpPsUJXwdR/LJ4QjON57NvuyQ9CZTUL7Rdk8xbzg+nvlmAaQ==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-x64-gnu/-/lancedb-linux-x64-gnu-0.42.0-beta.20.tgz", + "integrity": "sha512-s7/l3mlktGM1tsfVT0Ioso+B+adG/Ke4sAOEPdbGtIoGRauswov6lzCBmgMnNhV13Q2lniMmnAJR6rGC4Vtg/A==", "cpu": [ "x64" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" @@ -571,16 +628,12 @@ } }, "node_modules/@lancedb/lancedb-linux-x64-musl": { - "version": "0.41.0-beta.8", - "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-x64-musl/-/lancedb-linux-x64-musl-0.41.0-beta.8.tgz", - "integrity": "sha512-EFMuG0GaFO0BPNfY/XRo66nDKKq3ndyiq/t+P4P500cagDtFgCpZphhF8Q+BkQpQ1b+ZgVS2Uaxu5tOyo0SPhg==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-x64-musl/-/lancedb-linux-x64-musl-0.42.0-beta.20.tgz", + "integrity": "sha512-2YgGQjV5AqacKXC1IDJwR/WYOPJk34PuUvo1iy4d+hOdaIy+r7vQLYUy1nFx4uYx7kLCfV/cuuq6V7OkzGkx7Q==", "cpu": [ "x64" ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" @@ -590,13 +643,12 @@ } }, "node_modules/@lancedb/lancedb-win32-arm64-msvc": { - "version": "0.41.0-beta.8", - "resolved": "https://registry.npmjs.org/@lancedb/lancedb-win32-arm64-msvc/-/lancedb-win32-arm64-msvc-0.41.0-beta.8.tgz", - "integrity": "sha512-+vKZHO0CzZgoqqu9izXP2Ea0fBQ/PtolNz3B9JZItR5nc2w12bknA57K1sS06H74BBU9Yie2hDHNt3qzdPBEdw==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-win32-arm64-msvc/-/lancedb-win32-arm64-msvc-0.42.0-beta.20.tgz", + "integrity": "sha512-VGRLcDBGtYZEw/GJAOfDJX3ad36+sWP+lQrKmnNzzHAOs4MATLcbVk50zbqRbs6ukGBc784yM0ycnKy31TbN1w==", "cpu": [ "arm64" ], - "license": "Apache-2.0", "optional": true, "os": [ "win32" @@ -606,13 +658,12 @@ } }, "node_modules/@lancedb/lancedb-win32-x64-msvc": { - "version": "0.41.0-beta.8", - "resolved": "https://registry.npmjs.org/@lancedb/lancedb-win32-x64-msvc/-/lancedb-win32-x64-msvc-0.41.0-beta.8.tgz", - "integrity": "sha512-qSgWdgh9TzUiurd658ynzD4BxI/6E9yih7HFuFxvi8S+Zcp/NNiDpgrMWLQn/KfvorVJg9XBO8nhZMtg34UTGw==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-win32-x64-msvc/-/lancedb-win32-x64-msvc-0.42.0-beta.20.tgz", + "integrity": "sha512-eXoK1x9Ie2E2X/eYowGo2Daqve8zwLG8pvHexwCTzLLvVFM/o7iTK0WvSRXO9/9O4uhAsAGXBzH4I52ZY3kqqw==", "cpu": [ "x64" ], - "license": "Apache-2.0", "optional": true, "os": [ "win32" @@ -634,35 +685,30 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", - "license": "BSD-3-Clause", "optional": true }, "node_modules/@protobufjs/base64": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", - "license": "BSD-3-Clause", "optional": true }, "node_modules/@protobufjs/codegen": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", - "license": "BSD-3-Clause", "optional": true }, "node_modules/@protobufjs/eventemitter": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", - "license": "BSD-3-Clause", "optional": true }, "node_modules/@protobufjs/fetch": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", - "license": "BSD-3-Clause", "optional": true, "dependencies": { "@protobufjs/aspromise": "^1.1.1" @@ -672,28 +718,24 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", - "license": "BSD-3-Clause", "optional": true }, "node_modules/@protobufjs/path": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", - "license": "BSD-3-Clause", "optional": true }, "node_modules/@protobufjs/pool": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", - "license": "BSD-3-Clause", "optional": true }, "node_modules/@protobufjs/utf8": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", - "license": "BSD-3-Clause", "optional": true }, "node_modules/@types/node": { @@ -729,6 +771,15 @@ "node": ">=6.5" } }, + "node_modules/adm-zip": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.6.1.tgz", + "integrity": "sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==", + "optional": true, + "engines": { + "node": ">=14.0" + } + }, "node_modules/agentkeepalive": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", @@ -794,61 +845,6 @@ "node": "*" } }, - "node_modules/chownr": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", - "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", - "license": "BlueOak-1.0.0", - "optional": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/color": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", - "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", - "license": "MIT", - "optional": true, - "dependencies": { - "color-convert": "^2.0.1", - "color-string": "^1.9.0" - }, - "engines": { - "node": ">=12.5.0" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "license": "MIT", - "optional": true - }, - "node_modules/color-string": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", - "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", - "license": "MIT", - "optional": true, - "dependencies": { - "color-name": "^1.0.0", - "simple-swizzle": "^0.2.2" - } - }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -872,6 +868,40 @@ "node": "*" } }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "optional": true, + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "optional": true, + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -886,7 +916,6 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "license": "Apache-2.0", "optional": true, "engines": { "node": ">=8" @@ -967,6 +996,18 @@ "node": ">= 0.4" } }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/event-target-shim": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", @@ -1080,6 +1121,37 @@ "node": ">= 0.4" } }, + "node_modules/global-agent": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-4.1.7.tgz", + "integrity": "sha512-pxaZqdsMwPA4i7TuRKpDUONm2xGRjvYdRoidCQz7VleUKVuUfh/4p5Q3QDTGrpAE5Kz5TxxcZ+uqEgTkoKRNtg==", + "optional": true, + "dependencies": { + "globalthis": "^1.0.2", + "matcher": "^4.0.0", + "semver": "^7.3.5", + "serialize-error": "^8.1.0" + }, + "engines": { + "node": ">=10.0" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "optional": true, + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -1097,9 +1169,20 @@ "version": "1.0.9", "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==", - "license": "ISC", "optional": true }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "optional": true, + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/has-symbols": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", @@ -1152,13 +1235,6 @@ "ms": "^2.0.0" } }, - "node_modules/is-arrayish": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz", - "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==", - "license": "MIT", - "optional": true - }, "node_modules/is-buffer": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", @@ -1176,9 +1252,23 @@ "version": "5.3.2", "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", - "license": "Apache-2.0", "optional": true }, + "node_modules/matcher": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/matcher/-/matcher-4.0.0.tgz", + "integrity": "sha512-S6x5wmcDmsDRRU/c2dkccDwQPXoFczc5+HpQ2lON8pnvHlnvHAHj5WlLVvw6n6vNyHuVugYrFohYxbS+pvFpKQ==", + "optional": true, + "dependencies": { + "escape-string-regexp": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -1224,29 +1314,6 @@ "node": ">= 0.6" } }, - "node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "license": "BlueOak-1.0.0", - "optional": true, - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/minizlib": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", - "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", - "license": "MIT", - "optional": true, - "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">= 18" - } - }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -1296,19 +1363,26 @@ } } }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/onnxruntime-common": { - "version": "1.19.2", - "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.19.2.tgz", - "integrity": "sha512-a4R7wYEVFbZBlp0BfhpbFWqe4opCor3KM+5Wm22Az3NGDcQMiU2hfG/0MfnBs+1ZrlSGmlgWeMcXQkDk1UFb8Q==", - "license": "MIT", + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.30.0.tgz", + "integrity": "sha512-7fdVWjAID1dVhH/G8qK3APARunV4VkBFoCQAP7qp4Wkab0mrorvmc+sqiT+mKXOzDqdjN5j+/Z9nb4gzNPWcyA==", "optional": true }, "node_modules/onnxruntime-node": { - "version": "1.19.2", - "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.19.2.tgz", - "integrity": "sha512-9eHMP/HKbbeUcqte1JYzaaRC8JPn7ojWeCeoyShO86TOR97OCyIyAIOGX3V95ErjslVhJRXY8Em/caIUc0hm1Q==", + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.30.0.tgz", + "integrity": "sha512-twhs1C2C/BFkz1yc5OY0KIU2GUq6DURO7hD4bx5Q2Qy3nAMJwRXW8xU3NVczE29VA9lolLOYepoD8fjTGOfIqw==", "hasInstallScript": true, - "license": "MIT", "optional": true, "os": [ "win32", @@ -1316,37 +1390,29 @@ "linux" ], "dependencies": { - "onnxruntime-common": "1.19.2", - "tar": "^7.0.1" + "adm-zip": "^0.6.0", + "global-agent": "^4.1.3", + "onnxruntime-common": "1.30.0" } }, "node_modules/onnxruntime-web": { - "version": "1.21.0-dev.20241024-d9ca84ef96", - "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.21.0-dev.20241024-d9ca84ef96.tgz", - "integrity": "sha512-ANSQfMALvCviN3Y4tvTViKofKToV1WUb2r2VjZVCi3uUBPaK15oNJyIxhsNyEckBr/Num3JmSXlkHOD8HfVzSQ==", - "license": "MIT", + "version": "1.31.0-dev.20260914-8d85527a0", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.31.0-dev.20260914-8d85527a0.tgz", + "integrity": "sha512-Iy7rtadoBgxS/LLvDr3QW38DB1PNXRnr0GJMcL0TAt7c9qjgVQl83UlGCVyeAnK2InpmW8Uc3PL8XIuqtDeF6g==", "optional": true, "dependencies": { - "flatbuffers": "^1.12.0", + "flatbuffers": "^25.1.24", "guid-typescript": "^1.0.9", "long": "^5.2.3", - "onnxruntime-common": "1.20.0-dev.20241016-2b8fc5529b", + "onnxruntime-common": "1.31.0-dev.20260911-2a43ec07e", "platform": "^1.3.6", "protobufjs": "^7.2.4" } }, - "node_modules/onnxruntime-web/node_modules/flatbuffers": { - "version": "1.12.0", - "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-1.12.0.tgz", - "integrity": "sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==", - "license": "SEE LICENSE IN LICENSE.txt", - "optional": true - }, "node_modules/onnxruntime-web/node_modules/onnxruntime-common": { - "version": "1.20.0-dev.20241016-2b8fc5529b", - "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.20.0-dev.20241016-2b8fc5529b.tgz", - "integrity": "sha512-KZK8b6zCYGZFjd4ANze0pqBnqnFTS3GIVeclQpa2qseDpXrCQJfkWBixRcrZShNhm3LpFOZ8qJYFC5/qsJK9WQ==", - "license": "MIT", + "version": "1.31.0-dev.20260911-2a43ec07e", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.31.0-dev.20260911-2a43ec07e.tgz", + "integrity": "sha512-gBuF6U32YErKIAt+yD7DeGBpjRxhJ1uJwako6ygjokSZULDU6Pd+KWComX8Tumk1hYVHRxjPj7mdMnD0ryAPOw==", "optional": true }, "node_modules/openai": { @@ -1391,7 +1457,6 @@ "version": "1.3.6", "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", - "license": "MIT", "optional": true }, "node_modules/protobufjs": { @@ -1399,7 +1464,6 @@ "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", "hasInstallScript": true, - "license": "BSD-3-Clause", "optional": true, "dependencies": { "@protobufjs/aspromise": "^1.1.2", @@ -1425,10 +1489,9 @@ "license": "Apache-2.0" }, "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "license": "ISC", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "optional": true, "bin": { "semver": "bin/semver.js" @@ -1437,71 +1500,68 @@ "node": ">=10" } }, - "node_modules/sharp": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz", - "integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==", - "hasInstallScript": true, - "license": "Apache-2.0", + "node_modules/serialize-error": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-8.1.0.tgz", + "integrity": "sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==", "optional": true, "dependencies": { - "color": "^4.2.3", - "detect-libc": "^2.0.3", - "semver": "^7.6.3" + "type-fest": "^0.20.2" }, "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "optional": true, + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-darwin-arm64": "0.33.5", - "@img/sharp-darwin-x64": "0.33.5", - "@img/sharp-libvips-darwin-arm64": "1.0.4", - "@img/sharp-libvips-darwin-x64": "1.0.4", - "@img/sharp-libvips-linux-arm": "1.0.5", - "@img/sharp-libvips-linux-arm64": "1.0.4", - "@img/sharp-libvips-linux-s390x": "1.0.4", - "@img/sharp-libvips-linux-x64": "1.0.4", - "@img/sharp-libvips-linuxmusl-arm64": "1.0.4", - "@img/sharp-libvips-linuxmusl-x64": "1.0.4", - "@img/sharp-linux-arm": "0.33.5", - "@img/sharp-linux-arm64": "0.33.5", - "@img/sharp-linux-s390x": "0.33.5", - "@img/sharp-linux-x64": "0.33.5", - "@img/sharp-linuxmusl-arm64": "0.33.5", - "@img/sharp-linuxmusl-x64": "0.33.5", - "@img/sharp-wasm32": "0.33.5", - "@img/sharp-win32-ia32": "0.33.5", - "@img/sharp-win32-x64": "0.33.5" - } - }, - "node_modules/simple-swizzle": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz", - "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==", - "license": "MIT", - "optional": true, - "dependencies": { - "is-arrayish": "^0.3.1" - } - }, - "node_modules/tar": { - "version": "7.5.22", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", - "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==", - "license": "BlueOak-1.0.0", - "optional": true, - "dependencies": { - "@isaacs/fs-minipass": "^4.0.0", - "chownr": "^3.0.0", - "minipass": "^7.1.2", - "minizlib": "^3.1.0", - "yallist": "^5.0.0" + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" }, - "engines": { - "node": ">=18" + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, "node_modules/tr46": { @@ -1517,6 +1577,18 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/undici-types": { "version": "7.24.6", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", @@ -1550,16 +1622,6 @@ "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } - }, - "node_modules/yallist": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", - "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", - "license": "BlueOak-1.0.0", - "optional": true, - "engines": { - "node": ">=18" - } } } } diff --git a/docs/web-tests/blob-v2/ts/package.json b/docs/web-tests/blob-v2/ts/package.json index f39495edd..17daaeab0 100644 --- a/docs/web-tests/blob-v2/ts/package.json +++ b/docs/web-tests/blob-v2/ts/package.json @@ -10,7 +10,7 @@ "node": ">=22.6.0" }, "dependencies": { - "@lancedb/lancedb": "0.41.0-beta.8", + "@lancedb/lancedb": "0.42.0-beta.20", "apache-arrow": "21.2.0" } } From 4ac2728e73d5b47b69d7052b3c0e023a5d58a7b1 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 19 Nov 2026 14:42:22 -0800 Subject: [PATCH 28/78] ci: scope workflow permissions and drop unverified downloads (#5103) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Fixes four high-severity Aikido findings in CI and the Dockerfile. - **Workflow permissions:** `npm-publish.yml` and `codex-update-lance-dependency.yml` now set `permissions: {}` at the workflow level and grant permissions per job. - `npm-publish`: only `publish` gets `id-token: write` (npm provenance). Nothing in the workflow needed `contents: write`, so every job is now read-only. - `codex-update-lance-dependency`: keeps `contents: write`, because the branch is pushed with the checkout token. It drops `pull-requests: write` and `actions: read`, because all `gh` calls use `ROBOT_TOKEN`. - **license-header-check:** replaces `curl .../master/install.sh | bash` with `go install …@v1.5.0`. Go verifies the module against sum.golang.org, so we don't maintain a hash ourselves. Go is preinstalled on `ubuntu-latest`. - **Dockerfile:** drops the rustup `curl | sh` along with `build-essential`, `protoc`, and `git`, and runs as a non-root `lancedb` user. `lancedb` installs from prebuilt `manylinux_2_28` wheels, and the toolchain was only needed for the tantivy FTS support removed in #3282. Alternatives considered for the Dockerfile, in case we want Rust in the image: - `COPY --from=rust:-slim-bookworm@sha256:…` to copy the toolchain from the official image, pinned by digest. - Download `rustup-init` from `static.rust-lang.org` and check it against the published `.sha256`. Neither seemed worth it for an image that only runs `pip install lancedb`. ## Evidence - In a clean Python 3.12 venv, `pip install --only-binary :all: lancedb` installed 0.41.0, and building an FTS index and querying it worked. Docker wasn't available, so the image itself wasn't built. - Running `license-header-checker` v1.5.0 installed via `go install` over `rust/` reports `license_ok: 258 files`. - This PR runs both the `npm-publish` dry run and `license-header-check`, because both workflows' path filters include their own files. ## Merge Risk **Door:** two-way; CI config and an example Dockerfile only. **Blast Radius:** release automation. If `npm publish` or the Codex bump job needs a permission I removed, it will fail on the next tag or dispatch, and restoring that one permission fixes it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../codex-update-lance-dependency.yml | 8 ++--- .github/workflows/license-header-check.yml | 5 ++-- .github/workflows/npm-publish.yml | 12 ++++++-- dockerfiles/Dockerfile | 29 ++++--------------- 4 files changed, 21 insertions(+), 33 deletions(-) diff --git a/.github/workflows/codex-update-lance-dependency.yml b/.github/workflows/codex-update-lance-dependency.yml index ef59213bd..1d1890efb 100644 --- a/.github/workflows/codex-update-lance-dependency.yml +++ b/.github/workflows/codex-update-lance-dependency.yml @@ -16,14 +16,14 @@ on: default: "" type: string -permissions: - contents: write - pull-requests: write - actions: read +permissions: {} jobs: update: runs-on: ubuntu-latest + permissions: + # Pushes the branch with the checkout token. PR creation uses ROBOT_TOKEN. + contents: write steps: - name: Show inputs run: | diff --git a/.github/workflows/license-header-check.yml b/.github/workflows/license-header-check.yml index 8b8510b58..904eea2c4 100644 --- a/.github/workflows/license-header-check.yml +++ b/.github/workflows/license-header-check.yml @@ -21,11 +21,10 @@ jobs: steps: - name: Check out code uses: actions/checkout@v6 + # `go install` at a fixed version is verified against the Go checksum database. - name: Install license-header-checker - working-directory: /tmp run: | - curl -s https://raw.githubusercontent.com/lluissm/license-header-checker/master/install.sh | bash - mv /tmp/bin/license-header-checker /usr/local/bin/ + GOBIN=/usr/local/bin go install github.com/lluissm/license-header-checker/cmd/license-header-checker@v1.5.0 - name: Check license headers (rust) run: license-header-checker -a -v ./rust/license_header.txt ./ rs && [[ -z `git status -s` ]] - name: Check license headers (python) diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index 6de291c7d..fbaa43201 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -4,9 +4,7 @@ env: MACOSX_DEPLOYMENT_TARGET: '10.13' CARGO_INCREMENTAL: '0' -permissions: - contents: write - id-token: write +permissions: {} on: push: @@ -33,6 +31,8 @@ concurrency: jobs: build-lancedb: + permissions: + contents: read strategy: fail-fast: false matrix: @@ -326,6 +326,8 @@ jobs: nodejs/dist/* !nodejs/dist/*.node test-lancedb: + permissions: + contents: read name: "Test: ${{ matrix.settings.target }} - node@${{ matrix.node }}" needs: - build-lancedb @@ -394,6 +396,10 @@ jobs: run: node_modules/.bin/jest --verbose publish: name: Publish + permissions: + contents: read + # npm provenance + id-token: write runs-on: ubuntu-latest defaults: run: diff --git a/dockerfiles/Dockerfile b/dockerfiles/Dockerfile index 1c223b9b8..d8cafa690 100644 --- a/dockerfiles/Dockerfile +++ b/dockerfiles/Dockerfile @@ -1,27 +1,10 @@ -# Simple base dockerfile that supports basic dependencies required to run lance with FTS and Hybrid Search +# Simple base dockerfile for running LanceDB, including FTS and Hybrid Search # Usage: docker build -t lancedb:latest -f Dockerfile . FROM python:3.12-slim-bookworm -# Install build dependencies in a single layer -RUN apt-get update && \ - apt-get install -y --no-install-recommends \ - curl \ - build-essential \ - protobuf-compiler \ - git \ - ca-certificates && \ - apt-get clean && \ - rm -rf /var/lib/apt/lists/* - -# Install Rust (pinned installer, non-interactive) -RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal - -# Set the environment variable for Rust -ENV PATH="/root/.cargo/bin:${PATH}" - -# Verify installations -RUN python --version && \ - rustc --version && \ - protoc --version - +# lancedb ships prebuilt manylinux wheels, so no Rust or C toolchain is needed. RUN pip install --no-cache-dir lancedb + +RUN useradd --create-home --uid 1000 lancedb +USER lancedb +WORKDIR /home/lancedb From a9be4525a046c7b6356087adaf8fbe658995ddba Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:20:34 +0800 Subject: [PATCH 29/78] fix(python): accept optional discard_weight in split_hash (#5116) ### Problem `PermutationBuilder.split_hash()` raises `TypeError` when `discard_weight` is omitted because the Python wrapper forwards `None` while the PyO3 binding requires `u64`. The `_lancedb.pyi` stub also disagrees with the native signature: it omits `split_names` and types `discard_weight` as non-optional. ### Behavior The native binding accepts an optional `discard_weight` and treats omitted/`None` as `0`, so `split_hash(..., split_names=[...])` works without passing a discard weight. The stub now matches the binding. A regression test verifies that omitting `discard_weight` assigns every row exactly like explicit `0`. Fixes OSS-2856. --- python/python/lancedb/_lancedb.pyi | 7 ++++- python/python/tests/test_permutation.py | 35 +++++++++++++++++++++++++ python/src/permutation.rs | 5 ++-- 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 54b9f8083..5a89f100b 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1280,7 +1280,12 @@ class AsyncPermutationBuilder: seed: Optional[int] = None, ) -> "AsyncPermutationBuilder": ... def split_hash( - self, columns: List[str], split_weights: List[int], *, discard_weight: int = 0 + self, + columns: List[str], + split_weights: List[int], + *, + discard_weight: Optional[int] = None, + split_names: Optional[List[str]] = None, ) -> "AsyncPermutationBuilder": ... def split_sequential( self, diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 46d6493ed..165172622 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -275,6 +275,41 @@ def test_split_hash(mem_db): assert data["split_id"] == data2["split_id"] # Should be identical +def test_split_hash_default_discard_weight_matches_zero(mem_db): + """Omitting discard_weight must assign every row like discard_weight=0.""" + tbl = mem_db.create_table( + "test_table", + pa.table( + { + "id": range(100), + "category": (["A", "B", "C"] * 34)[:100], + "value": range(100), + } + ), + ) + + default = ( + permutation_builder(tbl) + .split_hash(["category"], [1, 1], split_names=["train", "test"]) + .execute() + ) + explicit_zero = ( + permutation_builder(tbl) + .split_hash( + ["category"], [1, 1], discard_weight=0, split_names=["train", "test"] + ) + .execute() + ) + + default_data = default.search(None).to_arrow().to_pydict() + explicit_data = explicit_zero.search(None).to_arrow().to_pydict() + assert default.count_rows() == 100 + assert default.count_rows() == explicit_zero.count_rows() + assert dict(zip(default_data["row_id"], default_data["split_id"])) == dict( + zip(explicit_data["row_id"], explicit_data["split_id"]) + ) + + def test_split_hash_with_discard(mem_db): """Test hash-based splitting with discard weight.""" tbl = mem_db.create_table( diff --git a/python/src/permutation.rs b/python/src/permutation.rs index 4e07d439e..9cb4da247 100644 --- a/python/src/permutation.rs +++ b/python/src/permutation.rs @@ -123,14 +123,15 @@ impl PyAsyncPermutationBuilder { }) } - #[pyo3(signature = (columns, split_weights, *, discard_weight=0, split_names=None))] + #[pyo3(signature = (columns, split_weights, *, discard_weight=None, split_names=None))] pub fn split_hash( slf: PyRefMut<'_, Self>, columns: Vec, split_weights: Vec, - discard_weight: u64, + discard_weight: Option, split_names: Option>, ) -> PyResult { + let discard_weight = discard_weight.unwrap_or(0); slf.modify(|builder| { builder.with_split_strategy( SplitStrategy::Hash { From 5e9b17b639dd4d1e10e4206f5354a9d8de0b0a0e Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:21:27 +0800 Subject: [PATCH 30/78] feat(python): make native tables and connections picklable (#5114) ## Summary Adds `__getstate__`/`__setstate__` to native `LanceTable` and `LanceDBConnection` so a PyTorch `Dataset` that keeps both can cross `spawn` and `forkserver` worker boundaries. `Permutation` and `StreamingDataset` now delegate to the same table state representation while retaining compatibility with older pickle payloads. ## Pickle contract - Reconnects from the serialized connection and preserves the table name, namespace path, explicit storage overrides, location, index-cache setting, managed versioning and pushdown routing. - Standard mode reopens at latest; `checkout(version)` remains pinned to the resolved branch/version; branch handles preserve their branch. Cross-branch tag checkout records the actual live branch. - `read_consistency_interval=timedelta(0)` remains distinct from `None`. - `memory://` tables keep the existing Arrow snapshot export/rebuild behavior. - `Session` and unreconstructable custom namespace clients fail at `pickle.dumps` with an explicit `TypeError`; declared namespace configurations reconstruct, including an omitted properties map. - Namespace storage options keep caller-only overrides layered over the live provider, with vended values winning conflicts. Caller options survive refresh, refreshed credentials replace old vended values, an explicit provider remains selected on open, and an empty provider response stays empty rather than restoring an expired seed. - Declared Python namespace connections reopen through their connection provider instead of turning the reconstructed client into an explicit table provider. ## Verification - Fresh binding build with `uv run --extra tests --extra dev maturin develop --extras tests,dev`. - End-to-end `DataLoader` holding `self._db` and `self._table`: spawn and forkserver passed. - `test_namespace.py`: 90 passed; `test_table.py` + `test_db.py` + `test_permutation.py`: 700 passed, 17 skipped. - Focused namespace provider/pickle regressions: passed, including caller-only and vended keys after a declared-namespace refresh. - Rust `test_namespace_connection_with_storage_options` and `test_manifest_enabled_vend_input_storage_options`: passed. - `cargo clippy -p lancedb --features remote --tests --examples`, `cargo fmt --check`, exact CI Pyright (0 errors/0 warnings), and Ruff passed. - DataLoader Workers documentation updated; Vale reports 0 findings. ## Scope Does not change the fork hard-error policy, #3851, or direct `LanceNamespaceDBConnection` pickling. It does not claim changes to the existing namespace dir `index_cache_size` behavior. This supersedes the earlier draft #3486, which only moved the table-state portion. --- docs/web/training/data-loading.mdx | 23 +- python/python/lancedb/db.py | 31 +- python/python/lancedb/namespace.py | 5 +- python/python/lancedb/permutation.py | 29 +- python/python/lancedb/table.py | 175 ++++++++++- python/python/tests/test_db.py | 24 ++ python/python/tests/test_namespace.py | 420 +++++++++++++++++++++++++ python/python/tests/test_table.py | 123 ++++++++ python/python/tests/test_torch.py | 41 +++ rust/lancedb/src/connection.rs | 69 ++++ rust/lancedb/src/database/namespace.rs | 36 ++- rust/lancedb/src/table.rs | 96 +++++- 12 files changed, 1027 insertions(+), 45 deletions(-) diff --git a/docs/web/training/data-loading.mdx b/docs/web/training/data-loading.mdx index 1e4989cf9..2a3250105 100644 --- a/docs/web/training/data-loading.mdx +++ b/docs/web/training/data-loading.mdx @@ -217,12 +217,23 @@ dataloader = torch.utils.data.DataLoader( ``` -By default, `StreamingDataset` serializes enough table state to reopen the -table in each worker. Remote LanceDB Enterprise tables (`db://...`) work the -same way: workers reopen the table from the pickled connection state. -Replace the URI, API key, region and endpoint below with your deployment -details. In application code, load credentials from environment variables -or a secrets manager: +By default, `StreamingDataset` and `Permutation` pickle the native table's +reopen state, including its connection, table identity, open options and +explicit storage overrides. A standard-mode handle reopens at the latest +version; `checkout(version)` and branch-scoped handles keep their pinned +version and branch. `memory://` tables are exported as an Arrow snapshot, so +workers see the data as of pickling; an in-memory connection by itself is not +picklable. + +Connections opened with a `Session` cannot be pickled. For a Session-backed +table, pass a picklable `connection_factory` to +`Permutation.with_connection_factory` or `StreamingDataset(connection_factory=...)` +so each worker creates its own connection and Session. + +Remote LanceDB Enterprise tables (`db://...`) work the same way: workers +reopen the table from the pickled connection state. Replace the URI, API key, +region and endpoint below with your deployment details. In application code, +load credentials from environment variables or a secrets manager: ```py Python icon=Python diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 86001ef10..aa1d73b29 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1936,11 +1936,40 @@ class LanceDBConnection(DBConnection): "manifest_enabled": self._manifest_enabled, "namespace_client_properties": self._namespace_client_properties, "read_consistency_interval_seconds": ( - rci.total_seconds() if rci else None + rci.total_seconds() if rci is not None else None ), } ) + def _pickle_state(self) -> str: + """Serialize this connection for pickle-based workers.""" + if self._session is not None: + raise TypeError( + "Cannot pickle a LanceDBConnection created with a Session; " + "Session objects are not serializable. Create the Session in " + "each worker process instead." + ) + if self.uri.startswith("memory://"): + raise TypeError( + "Cannot pickle an in-memory LanceDBConnection because its tables " + "exist only in this process. Pickle a LanceTable instead to " + "export its data, or connect to a persistent URI." + ) + return self.serialize() + + def __getstate__(self) -> dict[str, str]: + return {"serialized": self._pickle_state()} + + def __setstate__(self, state: dict[str, str]) -> None: + from . import deserialize_conn + + connection = deserialize_conn(state["serialized"], for_worker=True) + if not isinstance(connection, LanceDBConnection): + raise TypeError( + "Serialized connection did not reconstruct a LanceDBConnection" + ) + self.__dict__.update(connection.__dict__) + async def _async_get_table_names(self, start_after: Optional[str], limit: int): conn = AsyncConnection(await lancedb_connect(self.uri)) return await conn.table_names(start_after=start_after, limit=limit) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 463536619..1de49d935 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -584,7 +584,7 @@ class LanceNamespaceDBConnection(DBConnection): "storage_options": self.storage_options or None, "read_consistency_interval_seconds": ( self.read_consistency_interval.total_seconds() - if self.read_consistency_interval + if self.read_consistency_interval is not None else None ), } @@ -668,6 +668,7 @@ class LanceNamespaceDBConnection(DBConnection): self, name, namespace_path=namespace_path, + storage_options=storage_options, namespace_client=self._namespace_client, pushdown_operations=self._namespace_client_pushdown_operations, route_pushdown_to_rust=self._route_pushdown_to_rust, @@ -706,6 +707,7 @@ class LanceNamespaceDBConnection(DBConnection): self, name, namespace_path=namespace_path, + storage_options=storage_options, namespace_client=self._namespace_client, pushdown_operations=self._namespace_client_pushdown_operations, route_pushdown_to_rust=self._route_pushdown_to_rust, @@ -1132,6 +1134,7 @@ class LanceNamespaceDBConnection(DBConnection): self, name, namespace_path=namespace_path, + storage_options=storage_options, location=table_uri, namespace_client=namespace_client, managed_versioning=managed_versioning, diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index a6f584f8a..c8e6f84e0 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -410,6 +410,8 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]: from .remote.table import RemoteTable if isinstance(table, RemoteTable): + # RemoteTable already owns its reopen state; keep the table object so + # pickle delegates to its __getstate__ without duplicating the fields. return { "kind": "remote", "table": table, @@ -418,20 +420,15 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]: if not isinstance(table, LanceTable): raise ValueError(f"Cannot pickle table of type {type(table)!r}") - base_uri = table._conn.uri - if base_uri.startswith("memory://"): + state = table.__getstate__() + if state.get("kind") == "memory": return { "kind": "memory", - "name": table.name, - "data": table.to_arrow(), + "state": state, } - return { - "kind": "local", - "name": table.name, - "uri": base_uri, - "namespace": table._namespace_path, - "storage_options": table._conn.storage_options, + "kind": "lance", + "state": state, } @@ -444,13 +441,25 @@ def _drop_base_version(permutation_data: pa.Table) -> pa.Table: return permutation_data.replace_schema_metadata(metadata) +def _lance_table_from_pickle_state(state: dict[str, Any]) -> LanceTable: + table = LanceTable.__new__(LanceTable) + table.__setstate__(state) + return table + + def _table_from_pickle_state(state: dict[str, Any]) -> Table: from . import connect kind = state["kind"] if kind == "remote": return state["table"] + if kind == "lance": + return _lance_table_from_pickle_state(state["state"]) if kind == "memory": + if "state" in state: + return _lance_table_from_pickle_state(state["state"]) + # Backward compatibility for pickles written before tables carried + # their own state. return connect("memory://").create_table(state["name"], state["data"]) if kind == "local": db = connect(state["uri"], storage_options=state["storage_options"]) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index ff014396c..ea9dee024 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -299,7 +299,7 @@ def _maybe_add_fts_error_note( if TYPE_CHECKING: - from .db import LanceDBConnection + from .db import DBConnection, LanceDBConnection from ._lancedb import ( Table as LanceDBTable, OptimizeStats, @@ -4191,7 +4191,10 @@ class LanceTable(Table): namespace_path = [] self._conn = connection self._namespace_path = namespace_path + self._storage_options = storage_options + self._index_cache_size = index_cache_size self._location = location # Store location for use in _dataset_path + self._managed_versioning = managed_versioning self._namespace_client = namespace_client self._pushdown_operations = pushdown_operations or set() # When the connection built the namespace client natively (e.g. an @@ -4218,6 +4221,154 @@ class LanceTable(Table): ) # Take queries read the pushdown set from the inner table. self._table._pushdown_operations = self._pushdown_operations + # These coordinates live on the Python wrapper: the native table only + # reports its current branch and version, not whether it is pinned. + self._branch = self._table.current_branch() + self._checkout_version: Optional[int] = None + + def _pickle_connection_state(self) -> str: + """Serialize the connection, rejecting state a worker cannot recreate.""" + connection = self._conn + namespace_client = getattr(connection, "_namespace_client", None) + namespace_impl = getattr(connection, "_namespace_client_impl", None) + if namespace_client is not None and namespace_impl is None: + raise TypeError( + f"Cannot pickle LanceTable {self.name!r} backed by a namespace " + "connection whose custom namespace_client cannot be " + "reconstructed. Connect through connect_namespace(impl, " + "properties) or provide a picklable worker-side namespace " + "connection instead." + ) + + pickle_state = getattr(connection, "_pickle_state", None) + if pickle_state is not None: + return pickle_state() + + session = getattr(connection, "session", None) + if session is not None: + raise TypeError( + "Cannot pickle a LanceTable whose connection was created with a " + "Session; Session objects are not serializable. Create the " + "Session in each worker process instead." + ) + return connection.serialize() + + def _namespace_client_for_pickle(self) -> Optional[Any]: + """Keep a table-level namespace client only when pickle can carry it.""" + namespace_client = self._namespace_client + if namespace_client is None: + return None + if namespace_client is getattr(self._conn, "_namespace_client", None): + # The serialized connection rebuilds its own namespace client. + return None + if namespace_client is getattr(self._conn, "_cached_namespace_client", None): + # Local manifest-mode connections cache their namespace client here. + return None + + import pickle + + try: + pickle.dumps(namespace_client) + except Exception as error: + raise TypeError( + f"Cannot pickle LanceTable {self.name!r}: its custom " + f"namespace_client ({type(namespace_client).__name__}) is not " + "serializable. Reopen the table in the worker through a " + "picklable namespace connection instead." + ) from error + return namespace_client + + @classmethod + def _open_from_pickle_state( + cls, connection: "DBConnection", state: dict[str, Any] + ) -> "LanceTable": + """Reopen a table from the state returned by ``__getstate__``.""" + async_connection = getattr(connection, "_conn", None) + if async_connection is None: + async_connection = connection._inner + + # Only a table-level explicit client travels in the state. A connection + # namespace client must reopen through its own provider path so caller + # storage options keep their layering; passing the reconstructed client + # here would turn it into an explicit table provider. + namespace_client = state.get("namespace_client") + + async_table = LOOP.run( + async_connection.open_table( + state["name"], + namespace_path=state["namespace_path"], + storage_options=state["storage_options"], + index_cache_size=state["index_cache_size"], + location=state["location"], + namespace_client=namespace_client, + managed_versioning=state["managed_versioning"], + ) + ) + table = cls( + connection, + state["name"], + namespace_path=state["namespace_path"], + storage_options=state["storage_options"], + index_cache_size=state["index_cache_size"], + location=state["location"], + namespace_client=namespace_client, + managed_versioning=state["managed_versioning"], + pushdown_operations=state["pushdown_operations"], + route_pushdown_to_rust=state["route_pushdown_to_rust"], + _async=async_table, + ) + + version = state["checkout_version"] + if state["branch"] is not None: + table = table.branches.checkout(state["branch"], version) + elif version is not None: + table.checkout(version) + return table + + def __getstate__(self) -> dict[str, Any]: + """Return a process-independent state for pickle-based workers.""" + if self._conn.uri.startswith("memory://"): + # In-memory databases cannot be reopened by name in another process. + # Keep the established behavior of exporting the visible table. + return {"kind": "memory", "name": self.name, "data": self.to_arrow()} + + # The native handle is authoritative: a tag checkout can move this + # wrapper onto another branch, so never trust the branch captured at + # construction time. + self._branch = self.current_branch() + return { + "kind": "lance", + "connection_state": self._pickle_connection_state(), + "name": self.name, + "namespace_path": list(self._namespace_path), + # Only caller-supplied overrides are safe to replay. Namespace-provided + # initial options may contain rotating credentials and must be fetched + # again by the reopened connection's storage-options provider. + "storage_options": self._storage_options, + "index_cache_size": self._index_cache_size, + "location": self._location, + "namespace_client": self._namespace_client_for_pickle(), + "managed_versioning": self._managed_versioning, + "pushdown_operations": set(self._pushdown_operations), + "route_pushdown_to_rust": self._route_pushdown_to_rust, + "branch": self._branch, + "checkout_version": self._checkout_version, + } + + def __setstate__(self, state: dict[str, Any]) -> None: + """Rebuild a table from ``__getstate__`` in the current process.""" + if state.get("kind") == "memory": + from . import connect + + rebuilt = connect("memory://").create_table(state["name"], state["data"]) + self.__dict__.update(rebuilt.__dict__) + return + + from . import deserialize_conn + + connection = deserialize_conn(state["connection_state"], for_worker=True) + reopened = type(self)._open_from_pickle_state(connection, state) + self.__dict__.update(reopened.__dict__) @property def name(self) -> str: @@ -4456,18 +4607,23 @@ class LanceTable(Table): def _wrap_branch_handle( self, async_table: "AsyncTable", version: Optional[int] = None ) -> "LanceTable": - # version is unused locally: the pin already lives on async_table and a - # local handle is not reopened via a serialized connection. - return LanceTable( + table = LanceTable( self._conn, async_table.name, namespace_path=self._namespace_path, + storage_options=self._storage_options, + index_cache_size=self._index_cache_size, namespace_client=self._namespace_client, + managed_versioning=self._managed_versioning, pushdown_operations=self._pushdown_operations, route_pushdown_to_rust=self._route_pushdown_to_rust, location=self._location, _async=async_table, ) + # The native handle knows its branch but not whether this wrapper is a + # pinned branch version, so carry that coordinate explicitly. + table._checkout_version = version + return table def checkout(self, version: Union[int, str]): """Checkout a version of the table. This is an in-place operation. @@ -4506,6 +4662,8 @@ class LanceTable(Table): 0 [1.1, 0.9] vector """ LOOP.run(self._table.checkout(version)) + self._checkout_version = self.version + self._branch = self.current_branch() def checkout_latest(self): """Checkout the latest version of the table. This is an in-place operation. @@ -4514,6 +4672,8 @@ class LanceTable(Table): version of the table. """ LOOP.run(self._table.checkout_latest()) + self._checkout_version = None + self._branch = self.current_branch() def restore(self, version: Optional[Union[int, str]] = None): """Restore a version of the table. This is an in-place operation. @@ -4562,6 +4722,8 @@ class LanceTable(Table): if version is not None: LOOP.run(self._table.checkout(version)) LOOP.run(self._table.restore()) + self._checkout_version = None + self._branch = self.current_branch() def count_rows(self, filter: Optional[str] = None) -> int: return LOOP.run(self._table.count_rows(filter)) @@ -5651,7 +5813,9 @@ class LanceTable(Table): self = cls.__new__(cls) self._conn = db self._namespace_path = namespace_path + self._index_cache_size = None self._location = location + self._managed_versioning = None self._namespace_client = namespace_client self._pushdown_operations = pushdown_operations or set() self._route_pushdown_to_rust = route_pushdown_to_rust @@ -5679,6 +5843,7 @@ class LanceTable(Table): enable_v2_manifest_paths ).lower() + self._storage_options = storage_options self._table = LOOP.run( self._conn._conn.create_table( name, @@ -5695,6 +5860,8 @@ class LanceTable(Table): namespace_client=namespace_client, ) ) + self._branch = self._table.current_branch() + self._checkout_version = None return self def delete(self, where: Union[str, Expr]) -> DeleteResult: diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 80a98bc18..fa09a9e19 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -4,6 +4,7 @@ import contextlib import inspect +import pickle import re import sys from datetime import timedelta @@ -69,6 +70,29 @@ def test_basic(tmp_path): assert db.open_table("test").name == db["test"].name +def test_lance_db_connection_pickle_roundtrip(tmp_path): + interval = timedelta(seconds=2) + db = lancedb.connect(tmp_path, read_consistency_interval=interval) + db.create_table("pickle_conn", pa.table({"id": [1, 2]})) + + restored = pickle.loads(pickle.dumps(db)) + + assert restored.uri == str(tmp_path) + assert restored.read_consistency_interval == interval + assert restored.open_table("pickle_conn").to_arrow()["id"].to_pylist() == [1, 2] + + +def test_lance_db_connection_pickle_preserves_zero_read_consistency(tmp_path): + db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0)) + table = db.create_table("pickle_zero", pa.table({"id": [1]})) + + restored_db, restored_table = pickle.loads(pickle.dumps((db, table))) + lancedb.connect(tmp_path).open_table("pickle_zero").add(pa.table({"id": [2]})) + + assert restored_db.read_consistency_interval == timedelta(0) + assert restored_table.to_arrow()["id"].to_pylist() == [1, 2] + + def test_sync_debugger_inspection_does_not_use_background_loop(tmp_path, monkeypatch): from lancedb.background_loop import LOOP diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index b4ca746b0..c965618cd 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -6,6 +6,8 @@ import tempfile import shutil import importlib +import asyncio +import pickle import warnings import http.server import json @@ -16,6 +18,7 @@ import copy import pyarrow as pa import lancedb from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError +from lance_namespace import DescribeTableResponse from utils import start_server_thread from lancedb.listing import AsyncListing, Listing from lancedb.index import FTS @@ -35,6 +38,37 @@ PUSHDOWN_DATA = pa.table( ) +class _RefreshNamespaceWithExpiringOptions(LanceNamespace): + def __init__(self, root): + self.root = root + + def namespace_id(self): + return f"refresh-test:{self.root}" + + def describe_table(self, request): + from pathlib import Path + + return DescribeTableResponse( + location=str(Path(self.root) / "t.lance"), + storage_options={"vended": "fresh", "expires_at_millis": "1"}, + ) + + +class _DeclaredNamespaceWithoutProperties(LanceNamespace): + root = None + + def __init__(self): + from lance.namespace import DirectoryNamespace + + self.client = DirectoryNamespace(root=self.root) + + def namespace_id(self): + return self.client.namespace_id() + + def describe_table(self, request): + return self.client.describe_table(request) + + @pytest.mark.asyncio @pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]]) async def test_custom_namespace_table_exists_uses_namespace_api(table_id): @@ -56,6 +90,70 @@ async def test_custom_namespace_table_exists_uses_namespace_api(table_id): assert await adb.table_exists(table_id) is (table_id != ["missing"]) +def test_table_pickle_rejects_custom_namespace_connection(tmp_path): + pytest.importorskip("lance") + from lance.namespace import DirectoryNamespace + + lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table( + "t", [{"id": 1}] + ) + + class UnserializableNamespace(LanceNamespace): + def __init__(self, root): + from threading import Lock + + self.client = DirectoryNamespace(root=str(root)) + self.lock = Lock() + + def namespace_id(self): + return self.client.namespace_id() + + def describe_table(self, request): + return self.client.describe_table(request) + + db = LanceNamespaceDBConnection(UnserializableNamespace(tmp_path)) + table = db.open_table("t") + + with pytest.raises(TypeError, match="namespace"): + pickle.dumps(table) + + +def test_declared_namespace_pickle_keeps_caller_options_after_refresh(tmp_path): + lancedb.connect(tmp_path).create_table("t", [{"id": 1}]) + db = lancedb.connect_namespace( + f"{__name__}._RefreshNamespaceWithExpiringOptions", {"root": str(tmp_path)} + ) + table = db.open_table("t", storage_options={"caller_only": "keep"}) + + restored = pickle.loads(pickle.dumps(table)) + + for current in (table, restored): + options = current.latest_storage_options() + assert options["caller_only"] == "keep" + assert options["vended"] == "fresh" + + +def test_table_pickle_allows_declared_namespace_without_properties(tmp_path): + pytest.importorskip("lance") + + lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table( + "t", [{"id": 1}] + ) + _DeclaredNamespaceWithoutProperties.root = str(tmp_path) + try: + impl = f"{__name__}._DeclaredNamespaceWithoutProperties" + db = LanceNamespaceDBConnection( + _DeclaredNamespaceWithoutProperties(), namespace_client_impl=impl + ) + table = db.open_table("t") + + restored = pickle.loads(pickle.dumps(table)) + + assert restored.to_arrow()["id"].to_pylist() == [1] + finally: + _DeclaredNamespaceWithoutProperties.root = None + + class TestNamespaceCreateTableOptions: @pytest.mark.parametrize("version", ["legacy", "stable"]) @pytest.mark.parametrize("empty", [False, True]) @@ -309,6 +407,328 @@ def paginated_rest_namespace(): thread.join() +def test_rest_namespace_table_pickle_keeps_live_storage_options(tmp_path): + from time import time + + local = lancedb.connect(tmp_path) + local.create_table("t", [{"id": 1}]) + location = str(tmp_path / "t.lance") + ipc = _ipc_file(pa.table({"id": [42]})) + seen = [] + current_options = { + "block_size": "4096", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + seen.append(path) + if path.endswith("/describe"): + body = json.dumps( + {"location": location, "storage_options": current_options} + ).encode() + content_type = "application/json" + elif path.endswith("/query"): + body = ipc + content_type = "application/vnd.apache.arrow.file" + else: + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + db = lancedb.connect_namespace( + "rest", + {"uri": f"http://127.0.0.1:{server.server_port}"}, + namespace_client_pushdown_operations=["QueryTable"], + ) + table = db.open_table("t") + restored = pickle.loads(pickle.dumps(table)) + + seen.clear() + assert restored.search().limit(1).to_list() == [{"id": 42}] + assert seen == ["/v1/table/t/query"] + + current_options = { + "block_size": "8192", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + } + assert table.latest_storage_options()["block_size"] == "8192" + assert restored.latest_storage_options()["block_size"] == "8192" + finally: + server.shutdown() + thread.join() + + +def test_rest_namespace_create_empty_refresh_does_not_restore_expired_seed(tmp_path): + from time import time + + location = str(tmp_path / "t.lance") + current_options = { + "vended_seed": "short-lived", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + if not (path.endswith("/declare") or path.endswith("/describe")): + self.send_error(404) + return + body = json.dumps( + {"location": location, "storage_options": current_options} + ).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + db = lancedb.connect_namespace( + "rest", {"uri": f"http://127.0.0.1:{server.server_port}"} + ) + table = db.create_table("t", [{"id": 1}]) + payload = pickle.dumps(table) + assert b"short-lived" not in payload + restored = pickle.loads(payload) + + current_options = {} + assert table.latest_storage_options() == {} + assert restored.latest_storage_options() == {} + finally: + server.shutdown() + thread.join() + + +@pytest.mark.parametrize("entrypoint", ["create", "open"]) +def test_rest_namespace_pickle_layers_caller_storage_options(tmp_path, entrypoint): + from time import time + + location = str(tmp_path / "t.lance") + caller_options = {"caller_option": "kept", "conflict": "caller"} + vended_options = { + "vended_1": "old", + "conflict": "vended", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + if path.endswith("/declare") or path.endswith("/describe"): + body = json.dumps( + {"location": location, "storage_options": vended_options} + ).encode() + else: + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + db = lancedb.connect_namespace( + "rest", + {"uri": f"http://127.0.0.1:{server.server_port}"}, + ) + if entrypoint == "create": + table = db.create_table( + "t", [{"id": 1}], storage_options=caller_options + ) + else: + db.create_table("t", [{"id": 1}]) + table = db.open_table("t", storage_options=caller_options) + restored = pickle.loads(pickle.dumps(table)) + + for current in (table, restored): + options = current.latest_storage_options() + assert options["caller_option"] == "kept" + assert options["conflict"] == "vended" + + vended_options.update( + { + "vended_2": "new", + "conflict": "vended-new", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + } + ) + + for current in (table, restored): + options = current.latest_storage_options() + assert options["caller_option"] == "kept" + assert options["vended_2"] == "new" + assert options["conflict"] == "vended-new" + finally: + server.shutdown() + thread.join() + + +def test_namespace_open_uses_explicit_storage_options_provider(tmp_path): + from time import time + + from lancedb._lancedb import connect_namespace as connect_namespace_inner + from lancedb.db import AsyncConnection + + location = str(tmp_path / "t.lance") + seed_options = { + "vended_seed": "short-lived", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + if not (path.endswith("/declare") or path.endswith("/describe")): + self.send_error(404) + return + result = {"location": location, "storage_options": seed_options} + body = json.dumps(result).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + class ExplicitClient(LanceNamespace): + calls = 0 + + def namespace_id(self): + return "explicit-storage-options-provider" + + def describe_table(self, request): + self.calls += 1 + return DescribeTableResponse( + location=location, + storage_options={ + "explicit_provider": "fresh", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + }, + ) + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + properties = {"uri": f"http://127.0.0.1:{server.server_port}"} + db = lancedb.connect_namespace("rest", properties) + db.create_table("t", [{"id": 1}]) + + async def check(): + connection = AsyncConnection( + connect_namespace_inner("rest", properties) + ) + client = ExplicitClient() + table = await connection.open_table("t", namespace_client=client) + options = await table.latest_storage_options() + assert client.calls > 0 + assert options["explicit_provider"] == "fresh" + + asyncio.run(check()) + finally: + server.shutdown() + thread.join() + + +def test_namespace_create_without_seed_uses_connection_provider(tmp_path): + from time import time + + from lancedb._lancedb import connect_namespace as connect_namespace_inner + from lancedb.db import AsyncConnection + + location = str(tmp_path / "t.lance") + seed_options = { + "vended_seed": "short-lived", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + result = {"location": location} + if path.endswith("/describe"): + result["storage_options"] = seed_options + elif not path.endswith("/declare"): + self.send_error(404) + return + body = json.dumps(result).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + class ExplicitClient(LanceNamespace): + calls = 0 + + def namespace_id(self): + return "explicit-storage-options-provider" + + def describe_table(self, request): + self.calls += 1 + return DescribeTableResponse( + location=location, + storage_options={ + "explicit_provider": "fresh", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + }, + ) + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + properties = {"uri": f"http://127.0.0.1:{server.server_port}"} + + async def check(): + connection = AsyncConnection( + connect_namespace_inner("rest", properties) + ) + client = ExplicitClient() + table = await connection.create_table( + "t", [{"id": 1}], namespace_client=client + ) + options = await table.latest_storage_options() + assert client.calls == 0 + assert options["vended_seed"] == "short-lived" + + asyncio.run(check()) + finally: + server.shutdown() + thread.join() + + @pytest.mark.asyncio @pytest.mark.parametrize("namespace_path", [[], ["n"]]) async def test_rest_namespace_table_names_collects_pages( diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 90ae62d1b..e999390a1 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -6,6 +6,7 @@ import ctypes import gc import json import os +import pickle import sys import threading import warnings @@ -1228,6 +1229,128 @@ def test_list_versions_timestamp_precision_remote(): assert versions[0]["timestamp"].microsecond == 274000 +def test_lance_table_is_picklable(tmp_db: DBConnection): + table = tmp_db.create_table("pickle_table", pa.table({"id": [1, 2, 3]})) + payload = pickle.dumps(table) + + # A standard-mode handle must reopen at latest, not freeze the version that + # happened to be current when pickle.dumps ran. + tmp_db.open_table("pickle_table").add(pa.table({"id": [4]})) + + restored = pickle.loads(payload) + assert restored.name == "pickle_table" + assert restored.count_rows() == 4 + assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3, 4] + + +def test_lance_table_pickle_preserves_checkout(tmp_db: DBConnection): + table = tmp_db.create_table("pickle_checkout", pa.table({"id": [1]})) + table.add(pa.table({"id": [2]})) + table.checkout(1) + payload = pickle.dumps(table) + + tmp_db.open_table("pickle_checkout").add(pa.table({"id": [3]})) + + restored = pickle.loads(payload) + assert restored.version == 1 + assert restored.to_arrow()["id"].to_pylist() == [1] + + restored.checkout_latest() + assert restored.version == 3 + assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3] + + +def test_lance_table_pickle_preserves_cross_branch_tag_checkout(tmp_path): + db = lancedb.connect(tmp_path) + main = db.create_table("pickle_tag_branch", pa.table({"id": [0]})) + branch = main.branches.create("exp") + branch.add(pa.table({"id": [1]})) + branch.tags.create("exp_tag", branch.version) + + # Advance main independently, then resolve a tag that points into exp. + main.add(pa.table({"id": [9]})) + main.checkout("exp_tag") + assert main.current_branch() == "exp" + assert main.version == 2 + assert main.to_arrow()["id"].to_pylist() == [0, 1] + + restored = pickle.loads(pickle.dumps(main)) + assert restored.current_branch() == "exp" + assert restored.version == 2 + assert restored.to_arrow()["id"].to_pylist() == [0, 1] + + +def test_lance_table_pickle_preserves_branch_and_version(tmp_path): + db = lancedb.connect(tmp_path) + main = db.create_table("pickle_branch", pa.table({"id": [0]})) + branch = main.branches.create("exp") + branch.add(pa.table({"id": [1]})) + branch_version = branch.version + + branch_payload = pickle.dumps(branch) + pinned = db.open_table("pickle_branch", branch="exp", version=branch_version) + pinned_payload = pickle.dumps(pinned) + + db.open_table("pickle_branch", branch="exp").add(pa.table({"id": [2]})) + + restored_branch = pickle.loads(branch_payload) + assert restored_branch.current_branch() == "exp" + assert restored_branch.to_arrow()["id"].to_pylist() == [0, 1, 2] + + restored_pinned = pickle.loads(pinned_payload) + assert restored_pinned.current_branch() == "exp" + assert restored_pinned.version == branch_version + assert restored_pinned.to_arrow()["id"].to_pylist() == [0, 1] + assert main.count_rows() == 1 + + +def test_lance_table_pickle_memory_uses_arrow_snapshot(mem_db: DBConnection): + table = mem_db.create_table("pickle_memory", pa.table({"id": [1, 2]})) + payload = pickle.dumps(table) + + table.add(pa.table({"id": [3]})) + + restored = pickle.loads(payload) + assert restored.name == "pickle_memory" + assert restored.to_arrow()["id"].to_pylist() == [1, 2] + + +def test_memory_connection_pickle_requires_a_table_snapshot(mem_db: DBConnection): + with pytest.raises(TypeError, match="in-memory LanceDBConnection"): + pickle.dumps(mem_db) + + +def test_pickle_rejects_session_backed_connection(tmp_path): + db = lancedb.connect(tmp_path, session=lancedb.Session()) + table = db.create_table("pickle_session", pa.table({"id": [1]})) + + with pytest.raises(TypeError, match="Session"): + pickle.dumps(db) + with pytest.raises(TypeError, match="Session"): + pickle.dumps(table) + + +def test_pickle_rejects_custom_namespace_client(tmp_db: DBConnection): + table = tmp_db.create_table("pickle_custom_ns", pa.table({"id": [1]})) + table._namespace_client = threading.Lock() + + with pytest.raises(TypeError, match="namespace_client"): + pickle.dumps(table) + + +def test_lance_table_pickle_preserves_namespace_path(tmp_path): + pytest.importorskip("lance") + db = lancedb.connect_namespace("dir", {"root": str(tmp_path)}) + db.create_namespace(["ns1"]) + table = db.create_table("pickle_ns", pa.table({"id": [1]}), namespace_path=["ns1"]) + + restored = pickle.loads(pickle.dumps(table)) + + assert restored.namespace == ["ns1"] + assert restored.count_rows() == 1 + assert restored._conn._namespace_client_properties == {"root": str(tmp_path)} + + def test_versioning(mem_db: DBConnection): table = mem_db.create_table( "test", diff --git a/python/python/tests/test_torch.py b/python/python/tests/test_torch.py index befa3c10f..1cc6500bd 100644 --- a/python/python/tests/test_torch.py +++ b/python/python/tests/test_torch.py @@ -135,6 +135,23 @@ def _open_native_table(uri: str, table_name: str): return lancedb.connect(uri).open_table(table_name) +class _DatasetHoldingConnectionAndTable(torch.utils.data.Dataset): + """User-style Dataset that keeps both the connection and table.""" + + def __init__(self, db, table): + self._db = db + self._table = table + + def __len__(self): + return self._table.count_rows() + + def __getitem__(self, index): + row = self._table.take_offsets([index]).to_arrow().to_pylist()[0] + # Touch the connection too, so workers prove both objects were restored. + row["db_uri"] = self._db.uri + return row + + def test_table_dataloader(mem_db): table = mem_db.create_table("test_table", pa.table({"a": range(1000)})) dataloader = torch.utils.data.DataLoader( @@ -229,6 +246,30 @@ def test_permutation_with_memory_base_is_picklable(mem_db): assert restored.__getitems__([0, 10, 49]) == [{"a": 0}, {"a": 10}, {"a": 49}] +@pytest.mark.parametrize("start_method", ["spawn", "forkserver"]) +def test_dataset_with_connection_and_table_dataloader(tmp_path, start_method): + if start_method not in mp.get_all_start_methods(): + pytest.skip(f"{start_method} start method is not available") + + db = lancedb.connect(tmp_path) + table = db.create_table("test_table", pa.table({"a": range(20)})) + dataset = _DatasetHoldingConnectionAndTable(db, table) + + dataloader = torch.utils.data.DataLoader( + dataset, + batch_size=4, + num_workers=2, + multiprocessing_context=start_method, + ) + + seen = [] + expected_uri = str(tmp_path) + for batch in dataloader: + seen.extend(batch["a"].tolist()) + assert all(uri == expected_uri for uri in batch["db_uri"]) + assert sorted(seen) == list(range(20)) + + def test_permutation_dataloader_multiprocessing(tmp_db): """Using a Permutation with a PyTorch DataLoader that has num_workers > 0 must work end-to-end. Each worker process gets a pickled copy of the diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index bbefc3ca8..db6aa2ba8 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -90,6 +90,75 @@ fn set_storage_options_provider( store_params.storage_options_accessor = Some(Arc::new(accessor)); } +/// Preserve caller-supplied options across provider refreshes. +/// +/// Namespace providers return a fresh credential map and replace the accessor +/// cache, so a plain initial-options accessor would drop caller-only settings +/// after the first refresh. This wrapper merges the caller options into every +/// provider result, with provider values winning overlapping keys. +#[derive(Debug)] +pub(crate) struct LayeredStorageOptionsProvider { + caller_options: HashMap, + inner: Arc, +} + +impl LayeredStorageOptionsProvider { + pub(crate) fn new( + caller_options: HashMap, + inner: Arc, + ) -> Self { + Self { + caller_options, + inner, + } + } + + fn layer( + &self, + mut options: Option>, + ) -> Option> { + let mut merged = self.caller_options.clone(); + match options.take() { + Some(options) => { + merged.extend(options); + Some(merged) + } + None if merged.is_empty() => None, + None => Some(merged), + } + } +} + +#[async_trait::async_trait] +impl StorageOptionsProvider for LayeredStorageOptionsProvider { + async fn fetch_storage_options(&self) -> lance_core::Result>> { + Ok(self.layer(self.inner.fetch_storage_options().await?)) + } + + async fn force_fetch_storage_options( + &self, + ) -> lance_core::Result>> { + Ok(self.layer(self.inner.force_fetch_storage_options().await?)) + } + + fn provider_id(&self) -> String { + use std::hash::{Hash, Hasher}; + + let mut entries: Vec<_> = self.caller_options.iter().collect(); + entries.sort_by_key(|(key, _)| *key); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + for (key, value) in entries { + key.hash(&mut hasher); + value.hash(&mut hasher); + } + format!( + "layered(caller_options={:x},{})", + hasher.finish(), + self.inner.provider_id() + ) + } +} + /// A builder for configuring a [`Connection::table_names`] operation pub struct TableNamesBuilder { parent: Arc, diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index 4e61710ff..d603a878b 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -9,7 +9,10 @@ use std::sync::{Arc, Mutex}; use async_trait::async_trait; use lance::io::commit::namespace_manifest::LanceNamespaceExternalManifestStore; -use lance_io::object_store::{ObjectStoreParams, StorageOptionsAccessor}; +use lance_io::object_store::{ + LanceNamespaceStorageOptionsProvider, ObjectStoreParams, StorageOptionsAccessor, + StorageOptionsProvider, +}; use lance_namespace::{ LanceNamespace, error::{ErrorCode, NamespaceError}, @@ -25,7 +28,9 @@ use lance_table::io::commit::CommitHandler; use lance_table::io::commit::external_manifest::ExternalManifestCommitHandler; use crate::blob::ensure_blob_storage_version; -use crate::connection::NamespaceClientPushdownOperation; +use crate::connection::{ + LayeredStorageOptionsProvider, NamespaceClientPushdownOperation, merge_storage_options, +}; use crate::database::ReadConsistency; use crate::database::listing::{NewTableConfig, take_request_creation_overrides}; use crate::database::read_freshness::{ @@ -465,13 +470,29 @@ impl Database for LanceNamespaceDatabase { params.mode = WriteMode::Overwrite; } - // Set up storage options if provided + // Set up storage options if provided. Namespace options take + // precedence for overlapping keys, but must not discard caller-only + // options supplied with the create request. + let store_params = params + .store_params + .get_or_insert_with(ObjectStoreParams::default); + let caller_storage_options = store_params.storage_options().cloned().unwrap_or_default(); if let Some(storage_opts) = initial_storage_options { - let store_params = params - .store_params - .get_or_insert_with(ObjectStoreParams::default); + merge_storage_options(store_params, storage_opts); + } + if let Some(initial_options) = store_params + .storage_options() + .cloned() + .filter(|options| !options.is_empty()) + { + let namespace_provider: Arc = Arc::new( + LanceNamespaceStorageOptionsProvider::new(self.namespace.clone(), table_id.clone()), + ); + let provider: Arc = Arc::new( + LayeredStorageOptionsProvider::new(caller_storage_options, namespace_provider), + ); store_params.storage_options_accessor = Some(Arc::new( - StorageOptionsAccessor::with_static_options(storage_opts), + StorageOptionsAccessor::with_initial_and_provider(initial_options, provider), )); } @@ -618,6 +639,7 @@ mod tests { use arrow_array::{Int32Array, RecordBatch, StringArray}; use arrow_schema::{DataType, Field, Schema}; use futures::TryStreamExt; + use lance_io::object_store::StorageOptionsAccessor; use tempfile::tempdir; #[derive(Debug)] diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 775261bb5..4d663649e 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -29,7 +29,9 @@ use lance::index::scalar::load_segment_params; use lance::io::{ObjectStoreParams, WrappingObjectStore}; use lance_datafusion::utils::StreamingWriteSource; use lance_index::IndexCriteria; -use lance_io::object_store::{LanceNamespaceStorageOptionsProvider, StorageOptionsAccessor}; +use lance_io::object_store::{ + LanceNamespaceStorageOptionsProvider, StorageOptionsAccessor, StorageOptionsProvider, +}; pub use query::AnyQuery; use lance::io::commit::namespace_manifest::LanceNamespaceExternalManifestStore; @@ -49,7 +51,7 @@ use std::format; use std::path::Path; use std::sync::Arc; -use crate::connection::NamespaceClientPushdownOperation; +use crate::connection::{LayeredStorageOptionsProvider, NamespaceClientPushdownOperation}; use crate::DistanceType; use crate::blob::BlobRangeRequest; @@ -3679,7 +3681,7 @@ impl NativeTable { } // patch the params if we have a write store wrapper - let params = match write_store_wrapper.clone() { + let mut params = match write_store_wrapper.clone() { Some(wrapper) => params.patch_with_store_wrapper(wrapper)?, None => params, }; @@ -3690,9 +3692,49 @@ impl NativeTable { // Use DatasetBuilder::from_namespace which automatically fetches location // and storage options from the namespace - let builder = DatasetBuilder::from_namespace(namespace_client.clone(), table_id) - .await - .map_err(|e| map_namespace_lance_error(e, name))?; + let mut builder = + DatasetBuilder::from_namespace(namespace_client.clone(), table_id.clone()) + .await + .map_err(|e| map_namespace_lance_error(e, name))?; + + // A caller-supplied read-params accessor replaces the namespace-backed + // accessor in with_read_params. Preserve an explicit provider/accessor; + // only layer static caller options onto the live namespace provider so + // refresh keeps working and namespace values retain their precedence. + if let Some(mut store_options) = params.store_options.take() { + if let Some(accessor) = store_options.get_accessor() { + if accessor.provider().is_some() { + builder = builder.with_store_params(store_options); + } else { + let caller_options = accessor + .initial_storage_options() + .cloned() + .unwrap_or_default(); + let namespace_provider: Arc = + Arc::new(LanceNamespaceStorageOptionsProvider::new( + namespace_client.clone(), + table_id, + )); + let provider: Arc = + Arc::new(LayeredStorageOptionsProvider::new( + caller_options.clone(), + namespace_provider, + )); + let accessor = if caller_options.is_empty() { + Arc::new(StorageOptionsAccessor::with_provider(provider)) + } else { + Arc::new(StorageOptionsAccessor::with_initial_and_provider( + caller_options, + provider, + )) + }; + store_options.storage_options_accessor = Some(accessor); + builder = builder.with_store_params(store_options); + } + } else { + builder = builder.with_store_params(store_options); + } + } let dataset = builder .with_read_params(params) @@ -3901,10 +3943,9 @@ impl NativeTable { table_id.push(name.to_string()); // Set up storage options provider from namespace - let storage_options_provider = Arc::new(LanceNamespaceStorageOptionsProvider::new( - namespace_client.clone(), - table_id, - )); + let namespace_provider: Arc = Arc::new( + LanceNamespaceStorageOptionsProvider::new(namespace_client.clone(), table_id), + ); // Start with provided params or defaults let mut params = params.unwrap_or_default(); @@ -3914,17 +3955,40 @@ impl NativeTable { params.session = Some(sess); } - // Ensure store_params exists and set the storage options provider + // Ensure store_params exists and preserve an already-layered provider + // from create_table, or attach the namespace provider to the caller's + // initial options for other callers. let store_params = params .store_params .get_or_insert_with(ObjectStoreParams::default); - let accessor = match store_params.storage_options().cloned() { - Some(options) => { - StorageOptionsAccessor::with_initial_and_provider(options, storage_options_provider) + let accessor = match store_params.storage_options_accessor.take() { + Some(existing) + if existing.provider().is_some() + && existing.initial_storage_options().is_some() => + { + existing } - None => StorageOptionsAccessor::with_provider(storage_options_provider), + Some(existing) => { + let options = existing + .initial_storage_options() + .cloned() + .unwrap_or_default(); + let provider: Arc = Arc::new( + LayeredStorageOptionsProvider::new(options.clone(), namespace_provider), + ); + if options.is_empty() { + Arc::new(StorageOptionsAccessor::with_provider(provider)) + } else { + Arc::new(StorageOptionsAccessor::with_initial_and_provider( + options, provider, + )) + } + } + None => Arc::new(StorageOptionsAccessor::with_provider(Arc::new( + LayeredStorageOptionsProvider::new(HashMap::new(), namespace_provider), + ))), }; - store_params.storage_options_accessor = Some(Arc::new(accessor)); + store_params.storage_options_accessor = Some(accessor); // Patch the params if we have a write store wrapper let params = match write_store_wrapper.clone() { From 28e9ebb3ddda2cafac6f861919375ca31e91fb4a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:22:12 +0800 Subject: [PATCH 31/78] fix(python): reject unsupported fragment constraints (#5120) `with_fragments()` / `fragment_ids()` were only honored by the embedded plain-scan blob Pandas path. Every other sync, async, and remote terminal could silently ignore the selection and scan the full table, and async query conversions plus FTS `count_rows()` could drop the constraint before execution. This change makes unsupported paths fail with `NotImplementedError` before I/O, preserves fragment state across async Standard/Vector/FTS/Hybrid conversions, and keeps the supported embedded blob `to_pandas()` behavior unchanged. The FTS `count_rows()` sync and async entry points now reject fragment constraints explicitly. Refs OSS-2859 --- python/python/lancedb/query.py | 205 ++++++++++++++++---- python/python/tests/test_hybrid_query.py | 25 +++ python/python/tests/test_query.py | 231 +++++++++++++++++++++++ python/python/tests/test_remote_db.py | 30 +++ 4 files changed, 456 insertions(+), 35 deletions(-) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index dee2a480d..60fab3b8e 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -273,6 +273,24 @@ def _query_needs_lance_scanner(builder: Any) -> bool: ) +def _raise_unsupported_fragment_constraints( + fragments: Optional[Any], + fragment_ids: Optional[List[int]], + *, + operation: str, +) -> None: + """Reject fragment selection where execution would silently scan everything.""" + if fragments is None and fragment_ids is None: + return + raise NotImplementedError( + "with_fragments() and fragment_ids() are only supported for embedded " + "plain-scan blob queries executed through to_pandas(). " + f"{operation} would ignore the fragment selection and scan the full " + "table. Remove the fragment constraint, or use table.to_lance() with " + "a Lance scanner for this query shape." + ) + + def _query_is_plain_scan(query: Query) -> bool: return ( query.vector is None @@ -1686,11 +1704,19 @@ class LanceQueryBuilder(ABC): return self._user_requested_row_id() or self._blob_auto_row_id_enabled() def _query_for_scan(self, blob_sources: Optional[dict[str, str]] = None) -> Query: + self._ensure_fragment_constraints_supported("this query") query = self.to_query_object() if self._scan_needs_row_id() or blob_sources: query.with_row_id = True return query + def _ensure_fragment_constraints_supported(self, operation: str) -> None: + _raise_unsupported_fragment_constraints( + self._fragments, + self._fragment_ids, + operation=operation, + ) + def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool: if blob_mode != "bytes": return False @@ -1826,12 +1852,51 @@ class LanceQueryBuilder(ABC): return self def with_fragments(self, fragments: Any) -> Self: - """Set the Lance fragments to scan for plain scanner-backed queries.""" + """Restrict an embedded plain-scan blob query to the given Lance fragments. + + Fragment selection is supported only when ``to_pandas()`` uses the + embedded Lance plain-scan path: the table is an embedded, non-memory + Lance dataset, the query is a plain scan (no vector, full-text, take, + postfilter, or ordering), and the selected output includes a blob + column. Other terminals and remote tables raise ``NotImplementedError`` + before scanning instead of silently scanning the full table. + Blob-specific ``to_pandas()`` fallbacks keep their existing validation + errors. + + Parameters + ---------- + fragments : list[lance.Fragment] + Fragments from ``table.to_lance().get_fragments()``. Pass fragments + from the same dataset snapshot. + + Returns + ------- + LanceQueryBuilder + The LanceQueryBuilder object. + """ self._fragments = fragments return self def fragment_ids(self, fragment_ids: List[int]) -> Self: - """Set the Lance fragment ids to scan for plain scanner-backed queries.""" + """Restrict an embedded plain-scan blob query to the given fragment ids. + + Fragment selection uses the same supported ``to_pandas()`` path as + ``with_fragments()``. On that path, an empty list selects no rows and + missing ids raise ``ValueError``. Other terminals and remote tables + raise ``NotImplementedError`` before scanning instead of silently + scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep + their existing validation errors. + + Parameters + ---------- + fragment_ids : list[int] + Fragment ids from ``table.to_lance().get_fragments()``. + + Returns + ------- + LanceQueryBuilder + The LanceQueryBuilder object. + """ self._fragment_ids = fragment_ids return self @@ -1887,6 +1952,7 @@ class LanceQueryBuilder(ABC): ------- plan : str """ # noqa: E501 + self._ensure_fragment_constraints_supported("explain_plan()") return self._table._explain_plan(self.to_query_object(), verbose=verbose) def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self: @@ -1961,6 +2027,7 @@ class LanceQueryBuilder(ABC): plan : str The physical query execution plan with runtime metrics. """ + self._ensure_fragment_constraints_supported("analyze_plan()") return self._table._analyze_plan( self.to_query_object(), distributed_metrics=distributed_metrics ) @@ -2629,6 +2696,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): For example, ``table.search("gripper closed", query_type="fts",`` ``operator="AND").where("active = true").count_rows()``. """ + self._ensure_fragment_constraints_supported("count_rows()") self._table._ensure_no_legacy_fts_index() query = self._table._table._sync_query_to_async(self.to_query_object()) assert isinstance(query, AsyncFTSQuery) @@ -3522,6 +3590,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): def _create_query_builders(self): """Set up and configure the vector and FTS query builders.""" + self._ensure_fragment_constraints_supported("this hybrid query") vector_query, fts_query = self._validate_query( self._query, self._vector, self._text ) @@ -3640,6 +3709,19 @@ class AsyncQueryBase(object): def _user_requested_row_id(self) -> bool: return self._with_row_id is True + def _ensure_fragment_constraints_supported(self, operation: str) -> None: + _raise_unsupported_fragment_constraints( + self._fragments, + self._fragment_ids, + operation=operation, + ) + + def _inherit_fragment_constraints(self, query: Any) -> Any: + """Carry a fragment selection across an async query conversion.""" + query._fragments = self._fragments + query._fragment_ids = self._fragment_ids + return query + def _blob_auto_row_id_enabled(self) -> bool: return self._blob_auto_row_id @@ -3750,15 +3832,30 @@ class AsyncQueryBase(object): return self def with_fragments(self, fragments: Any) -> Self: - """ - Restrict scanner-backed plain query results to the given Lance fragments. + """Restrict an embedded plain-scan blob query to the given Lance fragments. + + Fragment selection is supported only when ``to_pandas()`` uses the + embedded Lance plain-scan path: the table is an embedded, non-memory + Lance dataset, the query is a plain scan (no vector, full-text, take, + postfilter, or ordering), and the selected output includes a blob + column. The constraint is preserved when converting between async + query types. Other terminals and remote tables raise + ``NotImplementedError`` before scanning instead of silently scanning + the full table. Blob-specific ``to_pandas()`` fallbacks keep their + existing validation errors. """ self._fragments = fragments return self def fragment_ids(self, fragment_ids: List[int]) -> Self: - """ - Restrict scanner-backed plain query results to the given Lance fragment ids. + """Restrict an embedded plain-scan blob query to the given fragment ids. + + Fragment selection uses the same supported ``to_pandas()`` path as + ``with_fragments()``. On that path, an empty list selects no rows and + missing ids raise ``ValueError``. Other terminals and remote tables + raise ``NotImplementedError`` before scanning instead of silently + scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep + their existing validation errors. """ self._fragment_ids = fragment_ids return self @@ -3838,6 +3935,7 @@ class AsyncQueryBase(object): timeout: Optional[timedelta] = None, blob_sources: Optional[dict[str, str]] = None, ) -> AsyncRecordBatchReader: + self._ensure_fragment_constraints_supported("to_batches()") if ( blob_sources and not self._user_requested_row_id() @@ -4245,6 +4343,7 @@ class AsyncQueryBase(object): ------- plan : str """ # noqa: E501 + self._ensure_fragment_constraints_supported("explain_plan()") return await self._inner.explain_plan(verbose) async def analyze_plan( @@ -4262,6 +4361,7 @@ class AsyncQueryBase(object): ------- plan : str """ + self._ensure_fragment_constraints_supported("analyze_plan()") return await self._inner.analyze_plan(distributed_metrics) @@ -4501,11 +4601,17 @@ class AsyncQuery(AsyncStandardQuery): new_self = self._inner.nearest_to(query_vectors[0]) for v in query_vectors[1:]: new_self.add_query_vector(v) - return AsyncVectorQuery(new_self, self._table) + return self._inherit_fragment_constraints( + AsyncVectorQuery(new_self, self._table) + ) else: - return AsyncVectorQuery( - self._inner.nearest_to(AsyncQuery._query_vec_to_array(query_vector)), - self._table, + return self._inherit_fragment_constraints( + AsyncVectorQuery( + self._inner.nearest_to( + AsyncQuery._query_vec_to_array(query_vector) + ), + self._table, + ) ) def nearest_to_text( @@ -4545,18 +4651,22 @@ class AsyncQuery(AsyncStandardQuery): columns = [] if isinstance(query, str): - return AsyncFTSQuery( - self._inner.nearest_to_text( - { - "query": query, - "columns": columns, - "operator": fts_query.operator, - } - ), - self._table, + return self._inherit_fragment_constraints( + AsyncFTSQuery( + self._inner.nearest_to_text( + { + "query": query, + "columns": columns, + "operator": fts_query.operator, + } + ), + self._table, + ) ) # FullTextQuery object - return AsyncFTSQuery(self._inner.nearest_to_text({"query": query}), self._table) + return self._inherit_fragment_constraints( + AsyncFTSQuery(self._inner.nearest_to_text({"query": query}), self._table) + ) class AsyncFTSQuery(AsyncStandardQuery): @@ -4577,6 +4687,7 @@ class AsyncFTSQuery(AsyncStandardQuery): For example, ``await table.query().nearest_to_text("gripper closed",`` ``operator="AND").where("active = true").count_rows()``. """ + self._ensure_fragment_constraints_supported("count_rows()") try: return await self._inner.count_rows() except Exception as error: @@ -4662,11 +4773,17 @@ class AsyncFTSQuery(AsyncStandardQuery): new_self = self._inner.nearest_to(query_vectors[0]) for v in query_vectors[1:]: new_self.add_query_vector(v) - return AsyncHybridQuery(new_self, self._table) + return self._inherit_fragment_constraints( + AsyncHybridQuery(new_self, self._table) + ) else: - return AsyncHybridQuery( - self._inner.nearest_to(AsyncQuery._query_vec_to_array(query_vector)), - self._table, + return self._inherit_fragment_constraints( + AsyncHybridQuery( + self._inner.nearest_to( + AsyncQuery._query_vec_to_array(query_vector) + ), + self._table, + ) ) async def _execute_batches( @@ -5002,15 +5119,21 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): columns = [] if isinstance(query, str): - return AsyncHybridQuery( - self._inner.nearest_to_text( - {"query": query, "columns": columns, "operator": fts_query.operator} - ), - self._table, + return self._inherit_fragment_constraints( + AsyncHybridQuery( + self._inner.nearest_to_text( + { + "query": query, + "columns": columns, + "operator": fts_query.operator, + } + ), + self._table, + ) ) # FullTextQuery object - return AsyncHybridQuery( - self._inner.nearest_to_text({"query": query}), self._table + return self._inherit_fragment_constraints( + AsyncHybridQuery(self._inner.nearest_to_text({"query": query}), self._table) ) async def _execute_batches( @@ -5098,6 +5221,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): the hybrid query itself. The key the legs are fused on, if any, is left on `self._pk_fusion`. """ + self._ensure_fragment_constraints_supported("this hybrid query") fts_query = AsyncFTSQuery(self._inner.to_fts_query(), self._table) vec_query = AsyncVectorQuery(self._inner.to_vector_query(), self._table) @@ -5394,15 +5518,26 @@ class BaseQueryBuilder(object): return self def with_fragments(self, fragments: Any) -> Self: - """ - Restrict scanner-backed plain query results to the given Lance fragments. + """Restrict execution to the given Lance fragments. + + Fragment selection is supported only by embedded plain-scan blob + queries through ``to_pandas()``. Other terminals and remote tables + raise ``NotImplementedError`` before scanning instead of silently + scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep + their existing validation errors. """ self._inner.with_fragments(fragments) return self def fragment_ids(self, fragment_ids: List[int]) -> Self: - """ - Restrict scanner-backed plain query results to the given Lance fragment ids. + """Restrict execution to the given Lance fragment ids. + + Fragment selection is supported only by embedded plain-scan blob + queries through ``to_pandas()``. On that path, an empty list selects no + rows and missing ids raise ``ValueError``. Other terminals and remote + tables raise ``NotImplementedError`` before scanning instead of + silently scanning the full table. Blob-specific ``to_pandas()`` + fallbacks keep their existing validation errors. """ self._inner.fragment_ids(fragment_ids) return self diff --git a/python/python/tests/test_hybrid_query.py b/python/python/tests/test_hybrid_query.py index 443fdebc4..ec6060db3 100644 --- a/python/python/tests/test_hybrid_query.py +++ b/python/python/tests/test_hybrid_query.py @@ -81,6 +81,31 @@ async def test_async_hybrid_query_with_row_ids(table: AsyncTable): assert result["_rowid"].to_pylist() == [0, 3] +def test_hybrid_fragment_constraints_fail_loud(sync_table: Table): + query = ( + sync_table.search("dog", query_type="hybrid") + .vector([0.5, -0.5]) + .fragment_ids([0]) + ) + + with pytest.raises(NotImplementedError, match="fragment selection"): + query.to_arrow() + with pytest.raises(NotImplementedError, match="fragment selection"): + query.explain_plan() + + +@pytest.mark.asyncio +async def test_async_hybrid_fragment_constraints_fail_loud(table: AsyncTable): + query = ( + table.query().nearest_to([0.5, -0.5]).nearest_to_text("dog").fragment_ids([0]) + ) + + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.to_arrow() + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.analyze_plan() + + @pytest.mark.asyncio async def test_async_hybrid_query_filters(table: AsyncTable): # test that query params are passed down from the regular builder to diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index aee67d32a..88bed9c1f 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -69,6 +69,36 @@ def _blob_query_data(): ) +def _fragment_query_data(): + return pa.table( + { + "id": pa.array([1, 2, 3, 4], pa.int64()), + "text": pa.array(["one", "two", "three", "four"], pa.utf8()), + "vector": pa.array( + [[1.0, 0.0], [2.0, 0.0], [3.0, 0.0], [4.0, 0.0]], + type=pa.list_(pa.float32(), list_size=2), + ), + } + ) + + +def _fragment_query_table(db, name): + data = _fragment_query_data() + table = db.create_table(name, data.slice(0, 2)) + table.add(data.slice(2, 2)) + return table + + +def _apply_fragment_restriction(query, restriction, fragment): + if restriction == "ids": + return query.fragment_ids([fragment.fragment_id]) + if restriction == "empty": + return query.fragment_ids([]) + if restriction == "fragments": + return query.with_fragments([fragment]) + raise AssertionError(f"unknown restriction: {restriction}") + + def _create_blob_v2_query_table(db, name): schema = pa.schema( [ @@ -435,6 +465,207 @@ def test_plain_scan_query_to_pandas_scanner_state(tmp_db): ) assert df_by_fragment["id"].tolist() == [1, 2] + empty = ( + table.search() + .select(["id", "blob"]) + .fragment_ids([]) + .to_pandas(blob_mode="descriptions") + ) + assert empty.empty + with pytest.raises(ValueError, match="fragment_ids not found in dataset: 999"): + ( + table.search() + .select(["id", "blob"]) + .fragment_ids([999]) + .to_pandas(blob_mode="descriptions") + ) + + +@pytest.mark.parametrize( + "terminal", + [ + "to_arrow", + "to_batches", + "to_pandas", + "to_polars", + "to_list", + "explain_plan", + "analyze_plan", + ], +) +def test_fragment_constraints_fail_loud_on_unsupported_paths(tmp_db, terminal): + pytest.importorskip("lance") + table = _fragment_query_table(tmp_db, f"fragment_guard_{terminal}") + fragment_id = table.to_lance().get_fragments()[0].fragment_id + query = table.search().fragment_ids([fragment_id]) + + with pytest.raises(NotImplementedError, match="fragment selection"): + getattr(query, terminal)() + + +def test_with_fragments_fails_loud_on_plain_and_vector_queries(tmp_db): + pytest.importorskip("lance") + table = _fragment_query_table(tmp_db, "fragment_guard_with_fragments") + fragment = table.to_lance().get_fragments()[0] + + for query in ( + table.search().with_fragments([fragment]), + table.search([0.0, 0.0]).with_fragments([fragment]), + ): + with pytest.raises(NotImplementedError, match="fragment selection"): + query.to_arrow() + + +@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"]) +def test_fts_count_rows_rejects_fragment_constraints(tmp_db, restriction): + pytest.importorskip("lance") + table = _fragment_query_table(tmp_db, f"fts_count_rows_{restriction}") + table.create_index("text", config=FTS(with_position=False)) + fragment = table.to_lance().get_fragments()[1] + query = _apply_fragment_restriction( + table.search("one", query_type="fts"), restriction, fragment + ) + + with pytest.raises(NotImplementedError, match="fragment selection"): + query.count_rows() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "terminal", + [ + "to_arrow", + "to_batches", + "to_pandas", + "to_polars", + "to_list", + "explain_plan", + "analyze_plan", + ], +) +async def test_async_fragment_constraints_fail_loud_on_unsupported_paths( + tmp_db_async, terminal +): + pytest.importorskip("lance") + data = _fragment_query_data() + table = await tmp_db_async.create_table( + f"async_fragment_guard_{terminal}", data.slice(0, 2) + ) + await table.add(data.slice(2, 2)) + fragments = (await table.to_lance()).get_fragments() + query = table.query().fragment_ids([fragments[0].fragment_id]) + + with pytest.raises(NotImplementedError, match="fragment selection"): + await getattr(query, terminal)() + + +@pytest.mark.asyncio +async def test_async_with_fragments_fails_loud_on_plain_and_vector_queries( + tmp_db_async, +): + pytest.importorskip("lance") + data = _fragment_query_data() + table = await tmp_db_async.create_table( + "async_fragment_guard_with_fragments", data.slice(0, 2) + ) + await table.add(data.slice(2, 2)) + fragments = (await table.to_lance()).get_fragments() + + for query in ( + table.query().with_fragments([fragments[0]]), + table.query().nearest_to([0.0, 0.0]).with_fragments([fragments[0]]), + ): + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.to_arrow() + + +@pytest.mark.asyncio +async def test_async_plain_scan_fragment_constraints_preserved(tmp_db_async): + pytest.importorskip("lance") + data = _blob_query_data() + table = await tmp_db_async.create_table( + "async_fragment_supported", + data.slice(0, 2), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + await table.add(data.slice(2, 2)) + fragments = (await table.to_lance()).get_fragments() + + df = await ( + table.query() + .select(["id", "blob"]) + .fragment_ids([fragments[1].fragment_id]) + .to_pandas(blob_mode="descriptions") + ) + + assert df["id"].tolist() == [3, 4] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"]) +async def test_async_fts_count_rows_rejects_fragment_constraints( + tmp_db_async, restriction +): + pytest.importorskip("lance") + data = _fragment_query_data() + table = await tmp_db_async.create_table( + f"async_fts_count_rows_{restriction}", data.slice(0, 2) + ) + await table.add(data.slice(2, 2)) + await table.create_index("text", config=FTS(with_position=False)) + fragment = (await table.to_lance()).get_fragments()[1] + query = _apply_fragment_restriction( + table.query().nearest_to_text("one"), restriction, fragment + ) + + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.count_rows() + + transitioned = _apply_fragment_restriction( + table.query(), restriction, fragment + ).nearest_to_text("one") + with pytest.raises(NotImplementedError, match="fragment selection"): + await transitioned.count_rows() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"]) +@pytest.mark.parametrize( + "transition", + ["query_to_vector", "query_to_fts", "fts_to_hybrid", "vector_to_hybrid"], +) +async def test_async_fragment_constraints_survive_query_transitions( + tmp_db_async, transition, restriction +): + pytest.importorskip("lance") + data = _fragment_query_data() + table = await tmp_db_async.create_table( + f"async_transition_{transition}_{restriction}", data.slice(0, 2) + ) + await table.add(data.slice(2, 2)) + await table.create_index("text", config=FTS(with_position=False)) + fragment = (await table.to_lance()).get_fragments()[1] + + if transition == "query_to_vector": + query = _apply_fragment_restriction( + table.query(), restriction, fragment + ).nearest_to([0.0, 0.0]) + elif transition == "query_to_fts": + query = _apply_fragment_restriction( + table.query(), restriction, fragment + ).nearest_to_text("one") + elif transition == "fts_to_hybrid": + query = _apply_fragment_restriction( + table.query().nearest_to_text("one"), restriction, fragment + ).nearest_to([0.0, 0.0]) + else: + query = _apply_fragment_restriction( + table.query().nearest_to([0.0, 0.0]), restriction, fragment + ).nearest_to_text("one") + + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.to_arrow() + @pytest.mark.asyncio async def test_async_plain_scan_query_to_pandas_blob_projection(tmp_db_async): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index a2a26b595..ad46b5d3b 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -4163,6 +4163,36 @@ def query_test_table( yield table +def test_remote_fragment_constraints_fail_before_query(): + query_calls = 0 + + def query_handler(body): + nonlocal query_calls + query_calls += 1 + return pa.table({"text": ["unexpected"]}) + + with query_test_table(query_handler) as table: + with pytest.raises(NotImplementedError, match="fragment selection"): + table.search().fragment_ids([0]).to_arrow() + + assert query_calls == 0 + + +def test_remote_fts_count_rows_rejects_fragment_constraints(): + query_calls = 0 + + def query_handler(body): + nonlocal query_calls + query_calls += 1 + return pa.table({"text": ["unexpected"]}) + + with query_test_table(query_handler) as table: + with pytest.raises(NotImplementedError, match="fragment selection"): + table.search("hello", query_type="fts").fragment_ids([0]).count_rows() + + assert query_calls == 0 + + @pytest.mark.parametrize( "query,search_kwargs,expected_column", [ From 164aec17538b47b54d3e78643b3a32d76144d51a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:24:15 +0800 Subject: [PATCH 32/78] fix(python): start background event loop lazily (#5111) ## Summary Importing `lancedb` currently starts a daemon thread running a private asyncio loop, even when the process never performs a synchronous database operation. Start that loop on the first actual coroutine submission instead. Concurrent first callers share one initialization, and a forked child resets the singleton to the unstarted state without touching the inherited thread or lock, then starts fresh work lazily on first use. The Rust-side runtime and the existing fork/reopen contracts are unchanged. ## Validation - New import, first-use, concurrent first-use, and fork parent/child coverage passes. - Existing import, debugger-inspection, cancellation, and remote fork tests pass. - `ruff format --check .` and `ruff check .` pass. --- python/python/lancedb/background_loop.py | 62 +++-- python/python/tests/test_background_loop.py | 236 ++++++++++++++++++++ python/python/tests/test_remote_db.py | 6 +- 3 files changed, 285 insertions(+), 19 deletions(-) create mode 100644 python/python/tests/test_background_loop.py diff --git a/python/python/lancedb/background_loop.py b/python/python/lancedb/background_loop.py index 9e1fdfbd8..7e55e708b 100644 --- a/python/python/lancedb/background_loop.py +++ b/python/python/lancedb/background_loop.py @@ -13,22 +13,51 @@ class BackgroundEventLoop: A background event loop that can run futures. Used to bridge sync and async code, without messing with users event loops. + + The loop and its thread are created by the first call to :meth:`run`, not + by constructing this object, so importing lancedb does not leave an idle + background thread behind. """ def __init__(self): - self._start() + self.loop: asyncio.AbstractEventLoop | None = None + self.thread: threading.Thread | None = None + self._start_lock = threading.Lock() - def _start(self): - self.loop = asyncio.new_event_loop() - self.thread = threading.Thread( - target=self.loop.run_forever, - name="LanceDBBackgroundEventLoop", - daemon=True, - ) - self.thread.start() + def _start(self) -> asyncio.AbstractEventLoop: + loop = self.loop + if loop is not None: + return loop + with self._start_lock: + loop = self.loop + if loop is not None: + return loop + loop = asyncio.new_event_loop() + thread = threading.Thread( + target=loop.run_forever, + name="LanceDBBackgroundEventLoop", + daemon=True, + ) + thread.start() + # Publish the loop first and the thread last. Callers that reach + # _start while this is in progress wait on _start_lock, so they + # cannot observe a half-initialized loop/thread pair. + self.loop = loop + self.thread = thread + return loop + + def _reset_after_fork(self): + # Threads do not survive fork(). Reset to the unstarted state without + # calling into the inherited loop or thread: the thread is gone, and + # it may have held _start_lock when the fork happened. A fresh lock + # lets the child start a new loop on its first run(). + self.loop = None + self.thread = None + self._start_lock = threading.Lock() def run(self, future): - concurrent_future = asyncio.run_coroutine_threadsafe(future, self.loop) + loop = self._start() + concurrent_future = asyncio.run_coroutine_threadsafe(future, loop) try: return concurrent_future.result() except BaseException: @@ -60,12 +89,15 @@ _FORK_WARNED = False def _reset_after_fork(): - # Threads do not survive fork(), so the asyncio loop in LOOP.thread is - # dead in the child. Re-initialize the singleton in place so existing + # Threads do not survive fork(), so the loop in LOOP.thread is dead in + # the child. Reset the singleton in place so existing # `from .background_loop import LOOP` references in other modules see - # the new state. The Rust-side tokio runtime is reset analogously by a - # pthread_atfork hook installed in the _lancedb extension. - LOOP._start() + # the unstarted state and create a fresh loop on their first run(). Do + # not restart it here: the child may never use LanceDB, and the at-fork + # handler must not touch the vanished thread or acquire inherited locks. + # The Rust-side tokio runtime is reset analogously by a pthread_atfork + # hook installed in the _lancedb extension. + LOOP._reset_after_fork() # The embedding executor's worker threads are dead in the child as well. # Replace it with a fresh pool (threads are spawned lazily, so this is # cheap); we don't shut down the old one, since joining its dead workers diff --git a/python/python/tests/test_background_loop.py b/python/python/tests/test_background_loop.py new file mode 100644 index 000000000..52b8b1f73 --- /dev/null +++ b/python/python/tests/test_background_loop.py @@ -0,0 +1,236 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import multiprocessing as mp +import os +import subprocess +import sys +import textwrap +import traceback + +import pytest + + +BACKGROUND_THREAD_NAME = "LanceDBBackgroundEventLoop" + + +def _run_in_subprocess(code: str) -> subprocess.CompletedProcess: + env = os.environ.copy() + env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path) + return subprocess.run( + [sys.executable, "-c", textwrap.dedent(code)], + check=False, + capture_output=True, + text=True, + env=env, + timeout=30, + ) + + +def _assert_subprocess_ok(result: subprocess.CompletedProcess) -> None: + assert result.returncode == 0, result.stderr or result.stdout + + +def test_import_and_inspection_do_not_start_background_loop(): + result = _run_in_subprocess( + f""" + import threading + + import lancedb + from lancedb.background_loop import BackgroundEventLoop, LOOP + + def background_threads(): + return [ + thread + for thread in threading.enumerate() + if thread.name == {BACKGROUND_THREAD_NAME!r} + ] + + assert LOOP.thread is None + assert LOOP.loop is None + assert background_threads() == [] + + # Inspecting a fresh instance is also side-effect free. + loop = BackgroundEventLoop() + assert loop.thread is None + assert loop.loop is None + assert background_threads() == [] + """ + ) + _assert_subprocess_ok(result) + + +def test_first_sync_call_starts_one_daemon_thread(): + result = _run_in_subprocess( + f""" + import threading + + import lancedb + from lancedb.background_loop import LOOP + + def background_threads(): + return [ + thread + for thread in threading.enumerate() + if thread.name == {BACKGROUND_THREAD_NAME!r} + ] + + assert LOOP.thread is None + assert LOOP.loop is None + + db = lancedb.connect("memory://") + assert db.table_names() == [] + + worker = LOOP.thread + assert worker is not None + assert worker is background_threads()[0] + assert len(background_threads()) == 1 + assert worker.daemon + assert worker.is_alive() + assert LOOP.loop is not None + """ + ) + _assert_subprocess_ok(result) + + +def test_concurrent_first_use_initializes_one_background_thread(): + result = _run_in_subprocess( + f""" + import asyncio + import threading + + from lancedb.background_loop import LOOP + + worker_count = 8 + barrier = threading.Barrier(worker_count) + results = [] + errors = [] + results_lock = threading.Lock() + + def submit(index): + try: + barrier.wait(timeout=10) + value = LOOP.run(asyncio.sleep(0.05, result=index)) + with results_lock: + results.append(value) + except BaseException as exc: + with results_lock: + errors.append(repr(exc)) + + threads = [ + threading.Thread(target=submit, args=(index,)) + for index in range(worker_count) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=20) + + assert all(not thread.is_alive() for thread in threads) + assert errors == [] + assert sorted(results) == list(range(worker_count)) + + background_threads = [ + thread + for thread in threading.enumerate() + if thread.name == {BACKGROUND_THREAD_NAME!r} + ] + assert len(background_threads) == 1 + assert background_threads[0].daemon + """ + ) + _assert_subprocess_ok(result) + + +def _fork_child_starts_lazily(queue): + def background_threads(): + import threading + + return [ + thread + for thread in threading.enumerate() + if thread.name == BACKGROUND_THREAD_NAME + ] + + try: + from lancedb.background_loop import LOOP + + inherited_thread_is_none = LOOP.thread is None + inherited_loop_is_none = LOOP.loop is None + background_threads_before = [thread.name for thread in background_threads()] + + import lancedb + + db = lancedb.connect("memory://") + tables = db.table_names() + + worker = LOOP.thread + queue.put( + { + "error": None, + "inherited_thread_is_none": inherited_thread_is_none, + "inherited_loop_is_none": inherited_loop_is_none, + "background_threads_before": background_threads_before, + "tables": tables, + "thread_alive": False if worker is None else worker.is_alive(), + "thread_daemon": False if worker is None else worker.daemon, + "background_thread_count": len(background_threads()), + } + ) + except BaseException: + queue.put({"error": traceback.format_exc()}) + + +@pytest.mark.skipif( + sys.platform != "linux", + reason=( + "fork() is unavailable on Windows and unsafe on macOS " + "(Apple frameworks/TLS are not fork-safe)" + ), +) +def test_forked_child_starts_background_loop_lazily(): + import asyncio + + from lancedb.background_loop import LOOP + + assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before" + parent_thread = LOOP.thread + assert parent_thread is not None + + ctx = mp.get_context("fork") + queue = ctx.Queue() + + # Simulate forking while another thread held the initialization lock. The + # child must replace the inherited lock instead of trying to acquire it. + LOOP._start_lock.acquire() + try: + proc = ctx.Process(target=_fork_child_starts_lazily, args=(queue,)) + proc.start() + finally: + LOOP._start_lock.release() + + proc.join(timeout=20) + if proc.is_alive(): + proc.terminate() + proc.join(timeout=5) + if proc.is_alive(): + proc.kill() + proc.join() + pytest.fail("Forked child hung starting the background loop") + + assert proc.exitcode == 0, f"child exited with code {proc.exitcode}" + payload = queue.get(timeout=5) + queue.close() + assert payload["error"] is None, payload["error"] + assert payload["inherited_thread_is_none"] is True + assert payload["inherited_loop_is_none"] is True + assert payload["background_threads_before"] == [] + assert payload["tables"] == [] + assert payload["thread_alive"] is True + assert payload["thread_daemon"] is True + assert payload["background_thread_count"] == 1 + + # The child's reset must not disturb the parent's loop. + assert LOOP.thread is parent_thread + assert parent_thread.is_alive() + assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after" diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index ad46b5d3b..e3ab986e2 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5370,12 +5370,10 @@ def test_background_loop_cancellation(exception): mock_future = MagicMock() mock_future.result.side_effect = exception() - with ( - patch.object(BackgroundEventLoop, "__init__", return_value=None), - patch("asyncio.run_coroutine_threadsafe", return_value=mock_future), - ): + with patch("asyncio.run_coroutine_threadsafe", return_value=mock_future): loop = BackgroundEventLoop() loop.loop = MagicMock() + loop.thread = MagicMock() with pytest.raises(exception): loop.run(None) mock_future.cancel.assert_called_once() From b9a2807049ee13ab3688672b2633c82831d2416f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:25:06 +0800 Subject: [PATCH 33/78] fix(python): accept column names in order_by and validate early (#5119) ## Summary - Accept column names, `(column_name, "asc"|"desc")` tuples, `ColumnOrdering`, and `{"column_name": ...}` dicts in both sync and async `order_by`, including mixed lists. - Distinguish a bare direction tuple from a list of column names by container type; `None` and `[]` clear ordering. - Validate at setter time with actionable errors for unknown dict keys and invalid directions. - Export `ColumnOrdering` from `lancedb` and document the accepted forms with examples. - Reject non-empty ordering on sync hybrid queries explicitly instead of silently ignoring it. Fixes OSS-3108. Namespace pushdown (OSS-3126) is intentionally out of scope. ## Tests - `python/tests/test_query.py` (214 passed, 1 skipped) - `python/tests/test_query.py -k order_by` (7 passed) - `python/tests/test_fts.py -k order_by` (2 passed) - `python/tests/test_remote_db.py::test_query_sync_maximal` - `pytest --doctest-modules python/lancedb/query.py` (21 passed) - `ruff format` / `ruff check` --- docs/src/python/python.md | 2 + python/python/lancedb/__init__.py | 1 + python/python/lancedb/query.py | 172 ++++++++++++++++++++++++++++-- python/python/tests/test_query.py | 107 +++++++++++++++++++ 4 files changed, 271 insertions(+), 11 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 752bf540f..122a73019 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -793,6 +793,8 @@ of raw SQL strings with [where][lancedb.query.LanceQueryBuilder.where] and ::: lancedb.query.Query +::: lancedb.query.ColumnOrdering + ::: lancedb.query.LanceQueryBuilder ::: lancedb.query.LanceVectorQueryBuilder diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 129a4b1c5..5095fddb0 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -79,6 +79,7 @@ from .materialized_view import ( from .view import ViewDescription as ViewDescription from .graph import PropertyGraph, PropertyGraphDescription from .table import AsyncTable, CompactionOptions, Table +from .query import ColumnOrdering as ColumnOrdering from .types import BaseTokenizerType from ._lancedb import Session from .namespace import ( diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 60fab3b8e..76d98e4f6 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -589,11 +589,107 @@ def ensure_vector_query( class ColumnOrdering(pydantic.BaseModel): + """A single sort key for ``order_by``. + + Attributes + ---------- + column_name: str + The column to sort by. + ascending: bool, default True + Sort ascending when true, descending otherwise. + nulls_first: bool, default False + Place null values before non-null values when true. + """ + column_name: str ascending: bool = True nulls_first: bool = False +_OrderingItem = Union[str, Tuple[str, str], ColumnOrdering, Dict[str, Any]] +_OrderingInput = Optional[Union[_OrderingItem, List[_OrderingItem]]] +_COLUMN_ORDERING_KEYS = frozenset({"column_name", "ascending", "nulls_first"}) +_ORDERING_EXAMPLE = '[{"column_name": "uris", "ascending": True}]' + + +def _normalize_ordering(ordering: _OrderingInput) -> Optional[List[ColumnOrdering]]: + """Normalize the accepted ``order_by`` inputs into ``ColumnOrdering`` models. + + ``None`` and an empty list clear the ordering. A tuple is always a single + ``(column_name, "asc"|"desc")`` pair, while a list is always a sequence of + separate orderings, so ``("a", "desc")`` and ``["a", "desc"]`` differ. + """ + if ordering is None: + return None + if isinstance(ordering, tuple): + items: List[Any] = [ordering] + elif isinstance(ordering, list): + items = ordering + else: + items = [ordering] + + normalized = [ + _normalize_ordering_item(item, index) for index, item in enumerate(items) + ] + return normalized or None + + +def _normalize_ordering_item(item: Any, index: int) -> ColumnOrdering: + prefix = f"order_by entry {index}" + if isinstance(item, ColumnOrdering): + if not item.column_name: + raise ValueError(f"{prefix} has an empty column_name") + return item + if isinstance(item, str): + if not item: + raise ValueError(f"{prefix} is an empty column name") + return ColumnOrdering(column_name=item) + if isinstance(item, tuple): + if len(item) != 2: + raise ValueError( + f"{prefix} must be a (column_name, 'asc'|'desc') tuple; got {item!r}" + ) + column_name, direction = item + if not isinstance(column_name, str) or not column_name: + raise ValueError( + f"{prefix} must start with a non-empty column name; got {item!r}" + ) + if not isinstance(direction, str) or direction.lower() not in ("asc", "desc"): + raise ValueError( + f"{prefix} has invalid direction {direction!r}; " + "expected 'asc' or 'desc'" + ) + return ColumnOrdering( + column_name=column_name, ascending=direction.lower() == "asc" + ) + if isinstance(item, dict): + unknown_keys = set(item) - _COLUMN_ORDERING_KEYS + if unknown_keys: + raise ValueError( + f"{prefix} has unsupported key(s) {sorted(map(str, unknown_keys))}; " + f"expected keys: {sorted(_COLUMN_ORDERING_KEYS)}. " + f"Example: {_ORDERING_EXAMPLE}" + ) + if "column_name" not in item: + raise ValueError( + f"{prefix} is missing 'column_name'. Example: {_ORDERING_EXAMPLE}" + ) + try: + normalized = ColumnOrdering(**item) + except pydantic.ValidationError as err: + raise ValueError( + f"{prefix} is not a valid ordering: {err}. Example: {_ORDERING_EXAMPLE}" + ) from err + if not normalized.column_name: + raise ValueError(f"{prefix} has an empty column_name") + return normalized + raise TypeError( + f"{prefix} must be a column name, a (column_name, 'asc'|'desc') tuple, " + f"a ColumnOrdering, or a dict with 'column_name'; " + f"got {type(item).__name__}" + ) + + class FullTextQueryType(str, Enum): MATCH = "match" MATCH_PHRASE = "match_phrase" @@ -1955,22 +2051,37 @@ class LanceQueryBuilder(ABC): self._ensure_fragment_constraints_supported("explain_plan()") return self._table._explain_plan(self.to_query_object(), verbose=verbose) - def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self: + def order_by(self, ordering: _OrderingInput = None) -> Self: """ Set the ordering for the results. Parameters ---------- - ordering: Optional[List[ColumnOrdering]] - The ordering to use for the results. If None, then the default ordering - will be used. + ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]] + The ordering to use for the results. Each entry can be a column + name, a ``(column_name, "asc"|"desc")`` tuple, a + [ColumnOrdering][lancedb.query.ColumnOrdering], or a dict with a + ``column_name`` key. A bare tuple is a single direction pair, while + a list contains separate orderings, so ``("a", "desc")`` sorts by + ``a`` descending and ``["a", "desc"]`` sorts by both columns. + Pass ``None`` or an empty list to clear the ordering. Returns ------- LanceQueryBuilder The LanceQueryBuilder object. + + Examples + -------- + >>> import lancedb + >>> db = lancedb.connect("memory://") + >>> table = db.create_table("ordering", [{"name": "b"}, {"name": "a"}]) + >>> table.search().order_by(["name"]).to_list() + [{'name': 'a'}, {'name': 'b'}] + >>> table.search().order_by([("name", "desc")]).to_list() + [{'name': 'b'}, {'name': 'a'}] """ - self._order_by = ordering + self._order_by = _normalize_ordering(ordering) return self def analyze_plan( @@ -2930,6 +3041,29 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): # the reranker's own use, so it cannot answer "did the caller ask?". self._caller_requested_row_id = False + def order_by(self, ordering: _OrderingInput = None) -> Self: + """ + Set the ordering for the results. + + Hybrid results are fused and reranked, so ordering the two search legs + does not define the final result order. Order the returned rows after + reranking instead. + + Parameters + ---------- + ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]] + Must be ``None`` or an empty list. Any non-empty ordering raises + ``NotImplementedError``. + """ + normalized = _normalize_ordering(ordering) + if normalized: + raise NotImplementedError( + "order_by is not supported for hybrid queries; " + "sort the returned results after reranking instead." + ) + self._order_by = None + return self + def _validate_query(self, query, vector=None, text=None): if query is not None and (vector is not None or text is not None): raise ValueError( @@ -4434,20 +4568,36 @@ class AsyncStandardQuery(AsyncQueryBase): self._inner.offset(offset) return self - def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self: + def order_by(self, ordering: _OrderingInput = None) -> Self: """ Set the ordering for the results. Parameters ---------- - ordering: Optional[List[ColumnOrdering]] - The ordering to use for the results. If None, then the default ordering - will be used. + ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]] + The ordering to use for the results. Each entry can be a column + name, a ``(column_name, "asc"|"desc")`` tuple, a + [ColumnOrdering][lancedb.query.ColumnOrdering], or a dict with a + ``column_name`` key. A bare tuple is a single direction pair, while + a list contains separate orderings, so ``("a", "desc")`` sorts by + ``a`` descending and ``["a", "desc"]`` sorts by both columns. + Pass ``None`` or an empty list to clear the ordering. + + Examples + -------- + >>> import lancedb + >>> db = await lancedb.connect_async("memory://") # doctest: +SKIP + >>> table = await db.create_table( # doctest: +SKIP + ... "ordering", [{"name": "b"}, {"name": "a"}] + ... ) + >>> await table.query().order_by(["name"]).to_list() # doctest: +SKIP + [{'name': 'a'}, {'name': 'b'}] """ - if ordering is None: + normalized = _normalize_ordering(ordering) + if normalized is None: self._inner.order_by(None) else: - self._inner.order_by([o.model_dump() for o in ordering]) + self._inner.order_by([o.model_dump() for o in normalized]) return self def fast_search(self) -> Self: diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 88bed9c1f..82b40f9c6 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1042,6 +1042,113 @@ async def test_order_by_async_query(mem_db_async: AsyncConnection): ] +def test_order_by_accepts_strings_tuples_and_dicts(mem_db): + table = mem_db.create_table( + "test_order_by_forms", + pa.table( + { + "group": [1, 1, 1, 2], + "score": [None, 1.0, 1.0, 0.5], + "name": ["z", "b", "a", "c"], + } + ), + ) + + rows = ( + table.search() + .order_by( + [ + "group", + ("score", "desc"), + {"column_name": "name", "ascending": True}, + ] + ) + .select(["name"]) + .to_list() + ) + assert rows == [{"name": "a"}, {"name": "b"}, {"name": "z"}, {"name": "c"}] + + # A bare tuple is one direction pair; a list holds separate orderings. + assert table.search().order_by("name").select(["name"]).to_list() == [ + {"name": "a"}, + {"name": "b"}, + {"name": "c"}, + {"name": "z"}, + ] + assert table.search().order_by(("name", "desc")).select(["name"]).to_list() == [ + {"name": "z"}, + {"name": "c"}, + {"name": "b"}, + {"name": "a"}, + ] + assert table.search().order_by(["group", "name"]).select(["name"]).to_list() == [ + {"name": "a"}, + {"name": "b"}, + {"name": "z"}, + {"name": "c"}, + ] + + +def test_order_by_clears_with_none_and_empty_list(mem_db): + table = mem_db.create_table("test_order_by_clear", [{"name": "a"}]) + + query = table.search().order_by("name") + assert query.to_query_object().order_by is not None + assert query.order_by(None).to_query_object().order_by is None + assert query.order_by([]).to_query_object().order_by is None + + +def test_order_by_rejects_invalid_input_early(mem_db): + table = mem_db.create_table("test_order_by_invalid", [{"name": "a"}]) + + with pytest.raises(ValueError, match="unsupported key\\(s\\)"): + table.search().order_by([{"column": "name", "ascending": True}]) + with pytest.raises(ValueError, match="missing 'column_name'"): + table.search().order_by({"ascending": True}) + with pytest.raises(ValueError, match="invalid direction"): + table.search().order_by([("name", "sideways")]) + with pytest.raises(TypeError, match="must be a column name"): + table.search().order_by([42]) + + +@pytest.mark.asyncio +async def test_order_by_async_accepts_dicts_and_clears(mem_db_async: AsyncConnection): + table = await mem_db_async.create_table( + "test_order_by_async_forms", + pa.table({"name": ["z", "b", "a", "c"]}), + ) + + rows = await ( + table.query().order_by([{"column_name": "name", "ascending": False}]).to_arrow() + ) + assert rows["name"].to_pylist() == ["z", "c", "b", "a"] + + query = table.query().order_by("name") + assert query.to_query_object().order_by is not None + assert query.order_by(None).to_query_object().order_by is None + assert query.order_by([]).to_query_object().order_by is None + + with pytest.raises(ValueError, match="unsupported key\\(s\\)"): + table.query().order_by([{"column": "name"}]) + + +def test_column_ordering_is_exported_at_top_level(): + assert lancedb.ColumnOrdering is ColumnOrdering + + +def test_order_by_hybrid_sync_is_explicitly_unsupported(table): + query = table.search(query_type="hybrid").vector([1.0, 2.0]).text("a") + + with pytest.raises(NotImplementedError, match="order_by is not supported"): + query.order_by(["id"]) + + # Clearing is still allowed, and invalid input still fails on its own terms. + query.order_by(None) + query.order_by([]) + with pytest.raises(ValueError, match="unsupported key\\(s\\)"): + query.order_by([{"column": "id"}]) + + def test_query_builder(table): rs = ( LanceVectorQueryBuilder(table, [0, 0], "vector") From 121de72cc449e7aacf88e0f66a6a6c64018a6e19 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:26:40 +0800 Subject: [PATCH 34/78] fix(python): keep Permutation builder copies shallow (#5121) ## Summary `Permutation`'s `with_*` builders use `copy.copy`, but `Permutation` had no `__copy__`. Python therefore fell back to `__getstate__`/`__setstate__`, which calls `permutation_table.to_arrow()` (unsupported for remote tables) and rebuilds the base table and reader on every builder call. Add a targeted `__copy__` that shallow-copies the instance state. The copy keeps the existing table handles and reader and can change its own attributes without affecting the original. Pickle serialization and persist semantics are unchanged. Refs OSS-2857. The persist feature remains open. --- python/python/lancedb/permutation.py | 14 ++++++++ python/python/tests/test_permutation.py | 45 ++++++++++++++++++++++++- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index c8e6f84e0..fcdbaa397 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -788,6 +788,20 @@ class Permutation: self.reader = None self._pid = None + def __copy__(self) -> "Permutation": + """Return a shallow copy without going through the pickle path. + + The ``with_*`` builders use ``copy.copy`` to derive a new permutation. + The default copy protocol would use ``__getstate__``/``__setstate__``, + which materializes the permutation table with ``to_arrow()`` (not + supported for remote tables) and rebuilds the base table and reader. + A shallow copy instead keeps the existing table handles and reader; + the caller replaces only the attribute it is changing. + """ + new = self.__class__.__new__(self.__class__) + new.__dict__ = self.__dict__.copy() + return new + def _ensure_open(self) -> None: pid = os.getpid() if self.reader is not None and getattr(self, "_pid", None) == pid: diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 165172622..a52aa420e 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -7,7 +7,13 @@ import pytest from lancedb import DBConnection, Table, connect from lancedb.background_loop import LOOP -from lancedb.permutation import Permutation, Permutations, permutation_builder +from lancedb.permutation import ( + DEFAULT_BATCH_SIZE, + Permutation, + Permutations, + Transforms, + permutation_builder, +) from utils import ( MockPermutationServer, assert_server_safe_row_id_requests, @@ -81,6 +87,43 @@ def test_pickled_permutation_reads_pinned_version(tmp_path): assert sorted(row["idx"] for row in rows) == list(range(20)) +def test_builder_copy_is_shallow_and_does_not_materialize( + some_table: Table, some_perm_table: Table, monkeypatch +): + """The with_* builders use copy.copy, which must stay a shallow copy. + + Without ``Permutation.__copy__`` the copy falls back to the pickle path, + which materializes the permutation table with ``to_arrow()`` before + rebuilding the base table and reader. That is expensive for in-memory + tables and fails for remote permutation tables. + """ + permutation = Permutation.from_tables(some_table, some_perm_table) + + def fail_materialize(*args, **kwargs): + raise AssertionError("copy.copy must not materialize the permutation table") + + def fail_getstate(_self): + raise AssertionError("copy.copy must not pickle the permutation") + + monkeypatch.setattr(permutation.permutation_table, "to_arrow", fail_materialize) + monkeypatch.setattr(Permutation, "__getstate__", fail_getstate) + + formatted = permutation.with_format("arrow") + assert formatted is not permutation + assert formatted.transform_fn is Transforms.arrow2arrow + assert permutation.transform_fn is Transforms.arrow2python + assert formatted.base_table is permutation.base_table + assert formatted.permutation_table is permutation.permutation_table + assert formatted.reader is permutation.reader + + resized = permutation.with_batch_size(7) + assert resized.batch_size == 7 + assert permutation.batch_size == DEFAULT_BATCH_SIZE + assert resized.selection is permutation.selection + resized.selection = {"id": "id"} + assert permutation.selection is not resized.selection + + def test_split_random_counts(mem_db): """Test random splitting with absolute counts.""" tbl = mem_db.create_table( From 3c9851966cab18b4290a0e0806524e809a14b1f6 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:28:47 +0800 Subject: [PATCH 35/78] chore(python): clarify package summary and search keywords (#5124) Replace the placeholder `lancedb` PyPI summary with factual wording covering vector, full-text, and hybrid search on Lance tables. Narrow the keywords to `lance`, `vector-search`, `full-text-search`, `dataset`, and `versioning`. Metadata-only change; runtime behavior is unchanged. Refs OSS-2883 --- python/pyproject.toml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/python/pyproject.toml b/python/pyproject.toml index ff64d9772..69130e16c 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -12,17 +12,17 @@ dependencies = [ "tqdm>=4.27.0", "lance-namespace>=0.13.0" ] -description = "lancedb" +description = "Embedded database for vector, full-text and hybrid search on Lance tables" authors = [{ name = "LanceDB Devs", email = "dev@lancedb.com" }] license = { file = "LICENSE" } readme = "README.md" requires-python = ">=3.10" keywords = [ - "data-format", - "data-science", - "machine-learning", - "arrow", - "data-analytics", + "lance", + "vector-search", + "full-text-search", + "dataset", + "versioning", ] classifiers = [ "Development Status :: 3 - Alpha", From 56638a9e71d89d043d2e680e4fbf8008c42607f5 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:34:49 +0800 Subject: [PATCH 36/78] fix(python): reject Expr inputs on unregistered Function definitions (#5125) `FunctionDefinition.__call__` ran the decorated Python callable with any value it was given, so `my_function(value=col("value"))` executed user code against an `Expr` or silently returned one, with errors such as `float() argument must be a string or a real number, not 'Expr'`. A column reference is not a local value: it binds only on a registered `FunctionVersion`. An unregistered definition now rejects `Expr` positional and keyword arguments with `TypeError` before the callable runs, and names the supported path: `create_function`/`create_function_async`, then `col(...)` on the returned version. Plain Python and Arrow arguments, and the class `__init__`/`__call__` lifecycle, are unchanged. The Function authoring guide's batch example did not register either: a `pyarrow.Array` annotation carries no element types, so `score_batch` raised `TypeError` for missing `input_schema` and `output_schema`, and the page claimed one `pa.RecordBatch` parameter could read several columns. The example now passes both schemas, shows one `pa.Array` parameter per input column for multi-column functions, and states that `input_schema` matches parameters one to one, so a `RecordBatch` parameter binds one input column. The GPU class example on the same page had the same missing-schema defect and is fixed too. Compatibility: code that passed `col(...)` to an unregistered definition now gets `TypeError` instead of running user code against an `Expr`. That call was never a supported binding and produced no usable result; no supported call changes. --- docs/src/python/python.md | 4 +- docs/web/curation/create-function.mdx | 35 +++++++++++++-- python/python/lancedb/functions.py | 28 +++++++++++- .../python/tests/test_function_packaging.py | 43 +++++++++++++++++++ 4 files changed, 103 insertions(+), 7 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 122a73019..dfd2752b8 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -449,7 +449,9 @@ and then call the returned instance; call `close()` if the class defines it. Thi path uses the current Python environment and does not create a registered `FunctionVersion`, build the declared remote runtime, resolve Secrets, or execute the remote Arrow adapter. A registered `FunctionVersion` call instead binds -`col(...)` inputs and returns a remote `FunctionApplication`. +`col(...)` inputs and returns a remote `FunctionApplication`. Passing an `Expr` +such as `col("value")` to a definition raises `TypeError` before the callable +runs; bind it on the registered `FunctionVersion` instead. ```python from lancedb import function diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 0342849b4..109846bea 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -98,10 +98,12 @@ is not a substitute for `lancedb.blob`. ## Batch: once per call, many rows at a time {#batch} -A function is called once per batch instead of once per row when its -parameters are annotated `pyarrow.Array`, or when it takes a single -`pyarrow.RecordBatch` parameter to read more than one column together. The -same doubling logic, vectorized over a whole batch at once: +A function is called once per batch instead of once per row when all of its +parameters are annotated `pyarrow.Array`. Those annotations say that a whole +column arrives in one call, but not which Arrow type the column holds, so a +batch function also passes `input_schema` and `output_schema`; every field of +`input_schema` matches a parameter by name and by order. The same doubling +logic, vectorized over a whole batch at once: ```python Python icon="python" @@ -111,6 +113,8 @@ from lancedb import function @function( pip=["numpy==2.2.0"], + input_schema=pa.schema([pa.field("value", pa.float64(), nullable=False)]), + output_schema=pa.float64(), batch_size=32, max_concurrency=4, row_timeout_seconds=90, @@ -120,6 +124,27 @@ def score_batch(value: pa.Array) -> pa.Array: ``` +Read several columns in one call by taking one `pa.Array` parameter per +column, with one schema field for each: + +```python +@function( + input_schema=pa.schema([ + pa.field("value", pa.float64(), nullable=False), + pa.field("weight", pa.float64(), nullable=False), + ]), + output_schema=pa.float64(), +) +def weighted_score(value: pa.Array, weight: pa.Array) -> pa.Array: + return pc.multiply(value, weight) +``` + +A single `pyarrow.RecordBatch` parameter is also a batch function, but it does +not read several columns at once: `input_schema` declares one field per +parameter, so a `RecordBatch` parameter binds one input column and receives +that column as a batch. A schema with more fields than the callable has +parameters is rejected at decoration. + Batching amortizes per-call overhead across many rows, which matters most once a function also does something with real fixed cost per call -- loading a model, opening a connection, making a network round trip. @@ -185,6 +210,8 @@ gpu_class = next( gpu=True, gpu_class=gpu_class, pip=["torch==2.12.0", "sentence-transformers==5.7.0"], + input_schema=pa.schema([pa.field("text", pa.string(), nullable=True)]), + output_schema=pa.list_(pa.float32(), 384), ) class embed_text: def __init__(self, model_name: str = "all-MiniLM-L6-v2"): diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 2d369e3ec..43226fdf3 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -3182,6 +3182,12 @@ class FunctionDefinition: remote application or build the declared remote runtime, and it does not need the private implementation attribute. + Arguments to this call are Python and Arrow values. An + [Expr][lancedb.expr.Expr] argument, such as ``col("value")``, is a column + binding that only a registered + [FunctionVersion][lancedb.functions.FunctionVersion] can carry, so this + call rejects it with ``TypeError`` instead of running the callable. + Remote execution adapts the callable to the internal Arrow batch ABI described by the registration artifact. By default it invokes the callable once per row. A callable whose parameters are all annotated as @@ -3451,6 +3457,16 @@ class FunctionDefinition: return self._request._copy(update={"secret_bindings": resolved}) def __call__(self, *args, **kwargs): + from lancedb.expr import Expr + + if any(isinstance(value, Expr) for value in (*args, *kwargs.values())): + raise TypeError( + "a FunctionDefinition runs locally on Python and Arrow values; " + "an Expr input binds only on a registered FunctionVersion. " + "Register the definition with create_function or " + "create_function_async, then bind col(...) on the returned " + "version." + ) return self._function(*args, **kwargs) @@ -3541,7 +3557,12 @@ def function( it takes one ``pyarrow.RecordBatch``. These batch annotations require both ``input_schema`` and ``output_schema`` explicitly: the annotations do not specify Arrow element types or fields. This also applies to a class's - ``__call__`` method. A decorated class is the same callable with state: + ``__call__`` method. Each ``input_schema`` field names one parameter, so + several input columns take one ``pyarrow.Array`` parameter each, while a + single ``pyarrow.RecordBatch`` parameter binds one input column and + receives it as a batch. The + [Function authoring guide](https://lancedb.com/docs/curation/create-function#batch) + has the worked examples. A decorated class is the same callable with state: each remote instance calls ``__init__`` once, calls ``__call__`` for every row or batch of every input it processes, and calls ``close()``, if defined, once when it retires. Load models, open clients, @@ -3803,7 +3824,10 @@ def function( remote environment, resolve Secrets, or run the remote Arrow adapter or sandbox. A registered ``FunctionVersion`` call is different: it binds ``col(...)`` inputs and returns a remote - [FunctionApplication][lancedb.functions.FunctionApplication]. + [FunctionApplication][lancedb.functions.FunctionApplication]. Passing an + [Expr][lancedb.expr.Expr] to a definition raises ``TypeError`` before the + callable runs, because a column reference binds only on a registered + version. ```python scaled = scale(factor=2.0) diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 874dd809f..8d2d282a9 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -20,6 +20,7 @@ from typing import Annotated, Optional, get_type_hints import numpy as np import pyarrow as pa +import pyarrow.compute as pc import pytest from lancedb import col @@ -582,6 +583,48 @@ def test_array_batch_annotations_accept_explicit_schemas(): assert identity(values).equals(values) +def test_batch_functions_take_one_array_parameter_per_input_column(): + @function( + input_schema=pa.schema( + [ + pa.field("value", pa.float64(), nullable=False), + pa.field("weight", pa.float64(), nullable=False), + ] + ), + output_schema=pa.float64(), + ) + def weighted_score(value: pa.Array, weight: pa.Array) -> pa.Array: + return pc.multiply(value, weight) + + signature = weighted_score.registration_request.signature + assert [parameter.name for parameter in signature.inputs] == ["value", "weight"] + result = weighted_score(pa.array([1.0, 2.0]), pa.array([3.0, 4.0])) + assert result.to_pylist() == [3.0, 8.0] + + +@pytest.mark.parametrize( + "invoke", + [ + lambda definition: definition(col("value")), + lambda definition: definition(value=col("value")), + lambda definition: definition(value=col("value") * 2), + ], + ids=["positional", "keyword", "derived"], +) +def test_definition_calls_reject_expr_inputs_before_user_code(invoke): + @function + def double(value: float) -> float: + raise AssertionError("user code ran") + + with pytest.raises(TypeError, match="registered FunctionVersion"): + invoke(double) + + +def test_class_definition_binds_initialization_only_on_a_version(): + with pytest.raises(TypeError, match="registered FunctionVersion"): + scale(factor=col("factor"), label="x") + + @pytest.mark.parametrize("class_function", [False, True]) @pytest.mark.parametrize("postponed", [False, True]) @pytest.mark.parametrize( From f460c34bdd62e03145b8bddd1670c734829648ef Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:36:29 +0800 Subject: [PATCH 37/78] fix: pin native permutation builds to one snapshot (#5126) ## Problem `PermutationBuilder` pinned backends that returned a snapshot handle, but `NativeTable` returned `None`. A namespace-backed latest handle could count and record the local table version while its row-id scan was pushed to a server that returned newer rows. A native handle with read refresh enabled could also advance between the version read, count, and scan. The result was a permutation whose recorded version, row count, and row ids did not describe one snapshot. ## Fix - Return an independent pinned native handle from `NativeTable::snapshot_at_current_version()`, so one build's version, count, and scan share a dataset. - Report `scan_order_is_deterministic()` false when a main/latest native handle may push queries to a namespace server, whose `QueryTable` request carries no order. Local scans remain deterministic at a fixed version. Refs OSS-3109 The query `scan_in_order` API and Python dispatch remain a separate slice. --- .../src/dataloader/permutation/builder.rs | 187 +++++++++++++++++- .../src/dataloader/permutation/split.rs | 4 +- rust/lancedb/src/table.rs | 22 ++- 3 files changed, 204 insertions(+), 9 deletions(-) diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs index 15f8c3cd3..770a956eb 100644 --- a/rust/lancedb/src/dataloader/permutation/builder.rs +++ b/rust/lancedb/src/dataloader/permutation/builder.rs @@ -249,10 +249,10 @@ impl PermutationBuilder { /// Builds the permutation table and stores it in the given database. pub async fn build(mut self) -> Result { - // Remote tables resolve latest independently for each request. Use a - // separate pinned handle so count, projection, and scan all refer to one - // snapshot without changing the caller's table checkout state. Native - // tables return `None` here and retain their existing behavior. + // Remote tables resolve latest independently for each request, and a + // native handle can refresh or answer a query from a namespace server. + // Use a separate pinned handle so count, projection, and scan all refer + // to one snapshot without changing the caller's table checkout state. if let Some(snapshot) = self .base_table .base_table() @@ -396,6 +396,51 @@ mod tests { use super::*; + /// Stands in for a namespace server whose table has advanced past the local + /// dataset. A pushed-down query reads this newer row instead of the local + /// snapshot. + #[derive(Debug, Default)] + struct ServerLatestNamespace { + query_table_calls: std::sync::atomic::AtomicUsize, + latest_row_id: u64, + } + + #[async_trait::async_trait] + impl lance_namespace::LanceNamespace for ServerLatestNamespace { + fn namespace_id(&self) -> String { + "server-latest".to_string() + } + + async fn query_table( + &self, + _request: lance_namespace::models::QueryTableRequest, + ) -> lance::Result { + self.query_table_calls + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + use arrow_array::UInt64Array; + use arrow_schema::{DataType, Field, Schema}; + + let schema = Arc::new(Schema::new(vec![Field::new( + ROW_ID, + DataType::UInt64, + false, + )])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(UInt64Array::from(vec![self.latest_row_id]))], + ) + .unwrap(); + let mut body = Vec::new(); + { + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &schema).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + Ok(bytes::Bytes::from(body)) + } + } + #[tokio::test] async fn test_permutation_table_only_stores_row_id_and_split_id() { let temp_dir = tempfile::tempdir().unwrap(); @@ -451,6 +496,140 @@ mod tests { // Native tables skip the canonicalizing sort; remote does not. assert!(table.base_table().scan_order_is_deterministic()); + + // A main/latest handle may answer from a namespace server, and its + // QueryTable request carries no order. The local native scan guarantee + // does not extend to that path. + let mut pushed_down = table.as_native().unwrap().clone(); + pushed_down.namespace_client = Some(Arc::new(ServerLatestNamespace::default())); + pushed_down + .pushdown_operations + .insert(crate::connection::NamespaceClientPushdownOperation::QueryTable); + let pushed_down: Arc = Arc::new(pushed_down); + let pushed_down = Table::from(pushed_down); + assert!(!pushed_down.base_table().scan_order_is_deterministic()); + } + + /// The builder must pin one native snapshot before it counts or scans. A + /// namespace-backed latest handle can otherwise count local rows, scan + /// server-latest rows, and record the local version as if they agreed. + #[tokio::test] + async fn test_native_permutation_builder_pins_namespace_pushdown() { + use std::sync::atomic::Ordering; + + use arrow_array::{cast::AsArray, types::UInt64Type}; + + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(10), BatchCount::from(1)); + let table = db.create_table("base_tbl", data).execute().await.unwrap(); + + let namespace = Arc::new(ServerLatestNamespace { + latest_row_id: 10, + ..Default::default() + }); + let mut native = table.as_native().unwrap().clone(); + native.namespace_client = Some(namespace.clone()); + native + .pushdown_operations + .insert(crate::connection::NamespaceClientPushdownOperation::QueryTable); + let native: Arc = Arc::new(native); + let table = Table::from(native); + + let permutation = PermutationBuilder::new(table.clone()) + .build() + .await + .unwrap(); + + assert_eq!( + namespace.query_table_calls.load(Ordering::SeqCst), + 0, + "the builder must read its pinned local snapshot, not server-latest rows" + ); + assert_eq!(permutation.count_rows(None).await.unwrap(), 10); + + let batches: Vec = permutation + .query() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let ids: Vec = batches + .iter() + .flat_map(|batch| { + batch[SRC_ROW_ID_COL] + .as_primitive::() + .values() + .to_vec() + }) + .collect(); + assert_eq!(ids, (0..10).collect::>()); + + let recorded = permutation + .schema() + .await + .unwrap() + .metadata + .get(BASE_VERSION_CONFIG_KEY) + .expect("permutation should record its base version") + .parse::() + .unwrap(); + assert_eq!(recorded, table.version().await.unwrap()); + } + + /// `snapshot_at_current_version` is the builder's one-snapshot hook. With + /// read refresh enabled, the caller can advance while the pin stays put. + #[tokio::test] + async fn test_native_snapshot_pins_count_scan_and_version() { + use std::time::Duration; + + use crate::connection::ConnectBuilder; + + let temp_dir = tempfile::tempdir().unwrap(); + let db = ConnectBuilder::new(temp_dir.path().to_str().unwrap()) + .read_consistency_interval(Duration::ZERO) + .execute() + .await + .unwrap(); + let data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(10), BatchCount::from(1)); + let table = db.create_table("base_tbl", data).execute().await.unwrap(); + + let snapshot = table + .base_table() + .snapshot_at_current_version() + .await + .unwrap() + .expect("native tables should provide an independent pinned handle"); + let version = snapshot.version().await.unwrap(); + assert_eq!(snapshot.count_rows(None).await.unwrap(), 10); + + let more_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(5), BatchCount::from(1)); + table.add(more_data).execute().await.unwrap(); + assert!(table.version().await.unwrap() > version); + + assert_eq!(snapshot.version().await.unwrap(), version); + assert_eq!(snapshot.count_rows(None).await.unwrap(), 10); + let batches: Vec = Table::from(snapshot) + .query() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 10); + assert_eq!(table.count_rows(None).await.unwrap(), 15); } #[cfg(feature = "remote")] diff --git a/rust/lancedb/src/dataloader/permutation/split.rs b/rust/lancedb/src/dataloader/permutation/split.rs index b4e5deac1..0fb7f669b 100644 --- a/rust/lancedb/src/dataloader/permutation/split.rs +++ b/rust/lancedb/src/dataloader/permutation/split.rs @@ -406,8 +406,8 @@ impl Splitter { .collect::>(); let row_ids = arrow::compute::concat(&row_id_arrays)?; // Sample against however many rows this scan actually returned, not the - // separately computed `num_rows` count checked by `validate` -- that count and - // this scan are two different queries, not pinned to one snapshot, so a + // separately computed `num_rows` count checked by `validate`. `apply` does + // not require its caller to pass a count and scan from one snapshot, so a // concurrent append or delete between them could otherwise push // `random_range` out of `row_ids`'s real bounds. let num_eligible_rows = row_ids.len() as u64; diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 4d663649e..045517968 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -4172,10 +4172,18 @@ impl BaseTable for NativeTable { self } - /// Lance scans fragments in order (`Scanner::ordered` defaults to true, and we - /// never clear it), so repeated identical scans agree. + /// Lance scans fragments in order at one dataset version (`Scanner::ordered` + /// defaults to true, and we never clear it), so repeated scans of a local + /// handle agree. A main/latest handle that may push its query to a namespace + /// server does not: the QueryTable request carries no order. fn scan_order_is_deterministic(&self) -> bool { - true + let may_push_down_namespace_query = self.namespace_client.is_some() + && self + .pushdown_operations + .contains(&NamespaceClientPushdownOperation::QueryTable) + && self.dataset.current_branch().is_none() + && self.dataset.time_travel_version().is_none(); + !may_push_down_namespace_query } fn name(&self) -> &str { @@ -4217,6 +4225,14 @@ impl BaseTable for NativeTable { })) } + async fn snapshot_at_current_version(&self) -> Result>> { + // A native handle can advance between requests when read consistency + // refreshes, and a namespace-backed handle can answer a query from a + // different snapshot than the local count/version. Hand the caller an + // independent time-travel handle so one build sees one dataset. + Ok(Some(self.checkout_current().await?)) + } + async fn checkout(&self, version: u64) -> Result<()> { self.dataset.as_time_travel(version).await } From ea4f1a38cf720ba7dd9d7c7d1350f8dfca99d293 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:45:03 +0800 Subject: [PATCH 38/78] fix: keep nonempty order_by out of namespace query pushdown (#5122) ## Problem With namespace `QueryTable` pushdown enabled, a query with a nonempty `order_by` was sent to the namespace server even though the request schema has no `order_by` field. With `limit(1)` this returned the wrong top row instead of the requested ordering. ## Fix Treat a nonempty `order_by` as requiring local execution in both the Python and Rust namespace pushdown gates. `None` or an empty ordering still uses pushdown. Local execution preserves branch, version and RTE semantics; if local storage cannot be read, the query fails explicitly rather than silently dropping the ordering. ## Validation - Public Python sync `search().order_by(...).limit(1).to_arrow()` and async `query().order_by(...).limit(1).to_arrow()` against a namespace mock: returned id 1 with zero pushdown calls. - `python/tests/test_namespace.py`: 83 passed. - Rust namespace pushdown tests: 5 passed; `table::query::tests`: 21 passed. - `cargo fmt`, `cargo clippy`, and Ruff clean. Fixes [OSS-3126](https://linear.app/lancedb/issue/OSS-3126/bug-namespace-querytable-pushdown-silently-drops-order-by). --- python/python/lancedb/namespace.py | 16 ++++-- python/python/lancedb/table.py | 3 ++ python/python/tests/test_namespace.py | 37 +++++++++++++- rust/lancedb/src/connection.rs | 7 +++ rust/lancedb/src/table/query.rs | 70 +++++++++++++++++++++++++-- 5 files changed, 124 insertions(+), 9 deletions(-) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 1de49d935..735eab51e 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -509,7 +509,9 @@ class LanceNamespaceDBConnection(DBConnection): Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a + nonempty ``order_by`` execute locally and require the client to + access the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1208,7 +1210,9 @@ class AsyncLanceNamespaceDBConnection: Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a + nonempty ``order_by`` execute locally and require the client to + access the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1811,7 +1815,9 @@ def connect_namespace( Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a nonempty + ``order_by`` execute locally and require the client to access the + table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1902,7 +1908,9 @@ def connect_namespace_async( Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a nonempty + ``order_by`` execute locally and require the client to access the + table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index ea9dee024..492526344 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -146,6 +146,9 @@ def _requires_local_namespace_execution(query: Query) -> bool: or query.take_row_ids is not None or query.search_effort is not None or query.approx_mode is not None + # The namespace QueryTable request has no order_by field. Pushing a + # nonempty ordering down would drop it and return the wrong top-K rows. + or bool(query.order_by) or ( query.full_text_query is not None and query.fast_search is True diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index c965618cd..937572cc0 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -29,7 +29,7 @@ from lancedb.namespace import ( LanceNamespaceDBConnection, _query_to_namespace_request, ) -from lancedb.query import FullTextSearchQuery, Query +from lancedb.query import ColumnOrdering, FullTextSearchQuery, Query from lancedb.table import AsyncTable, LanceTable @@ -1772,6 +1772,23 @@ class TestPushdownOperations: assert request.maximum_nprobes == 0 assert request.to_dict()["maximum_nprobes"] == 0 + def test_lance_table_order_by_is_not_pushed_down(self, tmp_path): + namespace_client = _NamespaceClient() + db = lancedb.connect(str(tmp_path / "db")) + table = db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}]) + table._namespace_path = ["geneva"] + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = table._execute_query( + Query(limit=1, order_by=[ColumnOrdering(column_name="id")]) + ).read_all() + + # Pushing this query down would drop order_by and return id 3. + assert result.column("id").to_pylist() == [1] + assert namespace_client.requests == [] + @pytest.mark.asyncio class TestAsyncPushdownOperations: @@ -1834,6 +1851,24 @@ class TestAsyncPushdownOperations: assert [request.k for request in namespace_client.requests] == [_MAX_QUERY_K] assert all(r.k <= 2**31 - 1 for r in namespace_client.requests) + async def test_async_table_order_by_is_not_pushed_down(self, tmp_path): + namespace_client = _NamespaceClient() + db = await lancedb.connect_async(str(tmp_path / "db")) + table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}]) + table._namespace_path = ["geneva"] + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = await table._execute_query( + Query(limit=1, order_by=[ColumnOrdering(column_name="id")]) + ) + + # Pushing this query down would drop order_by and return id 3. + batches = await result.read_all() + assert pa.Table.from_batches(batches).column("id").to_pylist() == [1] + assert namespace_client.requests == [] + @pytest.mark.parametrize( "query_kwargs", [ diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index db6aa2ba8..d413b2b78 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -2138,6 +2138,9 @@ use std::collections::HashSet; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum NamespaceClientPushdownOperation { /// Execute queries on the namespace server via `query_table()` instead of locally. + /// + /// Queries with a nonempty `order_by` execute locally and require client access + /// to the table storage. QueryTable, /// Execute table creation on the namespace server via `create_table()` /// instead of using `declare_table` + local write. @@ -2253,6 +2256,10 @@ impl ConnectNamespaceBuilder { /// - [`NamespaceClientPushdownOperation::QueryTable`]: Execute queries via `namespace.query_table()` /// - [`NamespaceClientPushdownOperation::CreateTable`]: Execute table creation via `namespace.create_table()` /// + /// Some query options cannot be represented in the namespace request. A query + /// with a nonempty `order_by` executes locally and requires client access to + /// the table storage. + /// /// By default, no operations are pushed down (all executed locally). pub fn pushdown_operation(mut self, operation: NamespaceClientPushdownOperation) -> Self { self.pushdown_operations.insert(operation); diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 7d98dc001..6789714e1 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -120,10 +120,18 @@ async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> R } fn requires_local_namespace_execution(query: &AnyQuery) -> bool { - // The namespace QueryTable request cannot represent approx_mode, search_effort or use_rte. - // For use_rte that is worse than a tuning miss: RTE read routing lives only - // in `create_plan`, so a pushed-down query would return stale base-only data. - if query.base().use_rte.is_some() || query.base().has_take() { + // The namespace QueryTable request cannot represent approx_mode, search_effort, + // use_rte or order_by. For use_rte that is worse than a tuning miss: RTE read + // routing lives only in `create_plan`, so a pushed-down query would return + // stale base-only data. A dropped order_by would return the wrong top-K rows. + if query.base().use_rte.is_some() + || query.base().has_take() + || query + .base() + .order_by + .as_ref() + .is_some_and(|order_by| !order_by.is_empty()) + { return true; } if matches!(query, AnyQuery::Query(query) if query.fast_search && query.full_text_search.is_some()) @@ -1858,6 +1866,60 @@ mod tests { assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); } + #[tokio::test] + async fn test_execute_query_order_by_with_namespace_pushdown_runs_locally() { + use crate::connect; + use crate::query::ColumnOrdering; + use crate::table::query::execute_query; + use arrow_array::{Int32Array, RecordBatch}; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + // Insertion order differs from ascending id, so a pushed-down query that + // drops order_by would return 3 instead of the correct top-1 row 1. + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![3, 1, 2]))]).unwrap(); + + let table = conn + .create_table("test_order_by_namespace_fallback", vec![batch]) + .execute() + .await + .unwrap(); + let namespace_client = Arc::new(CountingNamespaceClient::default()); + let mut native_table = table.as_native().unwrap().clone(); + native_table.namespace_client = Some(namespace_client.clone()); + native_table + .pushdown_operations + .insert(NamespaceClientPushdownOperation::QueryTable); + + let query = AnyQuery::Query(QueryRequest { + limit: Some(1), + order_by: Some(vec![ColumnOrdering::asc_nulls_first("id".to_string())]), + ..Default::default() + }); + + let stream = execute_query(&native_table, &query, QueryExecutionOptions::default()) + .await + .unwrap(); + let batches = stream.try_collect::>().await.unwrap(); + let ids: Vec = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect(); + + assert_eq!(ids, vec![1]); + assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); + } + #[tokio::test] async fn test_query_snapshot_disables_namespace_pushdown() { use crate::connect; From df8bf9ea5a3eb57a884da7710247afb4d97085ae Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:47:50 +0800 Subject: [PATCH 39/78] fix: reject unsupported layout options in remote add (#5118) ## Summary `RemoteTable::add` only transmits the write mode to the remote insert endpoint, so non-default layout options in `lance_write_params` were silently ignored. This rejects them before schema lookup and before either single-request or multipart transmission. Guarded fields: - `max_rows_per_file` - `max_rows_per_group` - `max_bytes_per_file` Default `WriteParams` and `mode = Overwrite` keep their existing behavior. Other write parameters remain untouched. ## Tests - Focused remote-table regressions cover each guarded field on both single-request and multipart paths, and verify default, `Create`, `Append`, and `Overwrite` behavior. - `cargo fmt --all -- --check` - `cargo clippy --quiet --features remote -p lancedb --tests` - Targeted `cargo test --features remote -p lancedb --lib remote::table::tests::...` Refs OSS-2882. This is the P0 hotfix; the table-level persistent layout design remains tracked separately in OSS-2882 and is not closed by this PR. --- rust/lancedb/src/remote/table.rs | 131 ++++++++++++++++++++++++++++++- rust/lancedb/src/table.rs | 4 + 2 files changed, 134 insertions(+), 1 deletion(-) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 54b7ea7b2..4c7f3a105 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -79,7 +79,7 @@ use http::{HeaderName, StatusCode}; use lance::arrow::json::{JsonDataType, JsonSchema}; use lance::dataset::refs::TagContents; use lance::dataset::scanner::DatasetRecordBatchStream; -use lance::dataset::{ColumnAlteration, NewColumnTransform, Version}; +use lance::dataset::{ColumnAlteration, NewColumnTransform, Version, WriteParams}; use lance_core::datatypes::Schema as LanceSchema; use lance_datafusion::exec::{OneShotExec, execute_plan}; use reqwest::{RequestBuilder, Response}; @@ -2647,6 +2647,44 @@ impl RemoteTable { } } +/// Reject per-write layout options that the remote insert protocol cannot carry. +/// +/// Remote inserts only transmit `mode`; file and row-group sizing is managed by +/// the server. Silently dropping these values would produce a different layout +/// than the caller requested. +fn ensure_remote_add_supports_write_params(write_params: Option<&WriteParams>) -> Result<()> { + let Some(write_params) = write_params else { + return Ok(()); + }; + let defaults = WriteParams::default(); + let unsupported: Vec<&str> = [ + ( + "max_rows_per_file", + write_params.max_rows_per_file != defaults.max_rows_per_file, + ), + ( + "max_rows_per_group", + write_params.max_rows_per_group != defaults.max_rows_per_group, + ), + ( + "max_bytes_per_file", + write_params.max_bytes_per_file != defaults.max_bytes_per_file, + ), + ] + .into_iter() + .filter_map(|(name, differs)| differs.then_some(name)) + .collect(); + if unsupported.is_empty() { + return Ok(()); + } + Err(Error::NotSupported { + message: format!( + "write_options.lance_write_params layout options are not supported when adding data to a LanceDB Enterprise table: {}; only mode=overwrite is supported", + unsupported.join(", ") + ), + }) +} + #[async_trait] impl BaseTable for RemoteTable { fn as_any(&self) -> &dyn std::any::Any { @@ -3301,6 +3339,7 @@ impl BaseTable for RemoteTable { } async fn add(&self, mut add: AddDataBuilder) -> Result { self.check_mutable().await?; + ensure_remote_add_supports_write_params(add.write_options.lance_write_params.as_ref())?; if add.allow_external_blob_outside_bases { return Err(Error::NotSupported { @@ -5460,6 +5499,96 @@ mod tests { assert!(err.to_string().contains("LanceDB Embedded")); } + #[rstest] + #[case("max_rows_per_file")] + #[case("max_rows_per_group")] + #[case("max_bytes_per_file")] + #[tokio::test] + async fn add_rejects_layout_write_params_before_any_request(#[case] field: &str) { + for write_parallelism in [None, Some(2)] { + let table = Table::new_with_handler::("my_table", |request| { + panic!("Unexpected request: {}", request.url().path()) + }); + let data = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); + let mut params = WriteParams::default(); + match field { + "max_rows_per_file" => params.max_rows_per_file = 50_000, + "max_rows_per_group" => params.max_rows_per_group = 100, + "max_bytes_per_file" => params.max_bytes_per_file = 64 * 1024 * 1024, + other => panic!("unexpected field: {other}"), + } + + let mut add = table.add(data).write_options(crate::table::WriteOptions { + lance_write_params: Some(params), + }); + if let Some(write_parallelism) = write_parallelism { + add = add.write_parallelism(write_parallelism); + } + + let err = add.execute().await.unwrap_err(); + assert!( + matches!(err, Error::NotSupported { .. }), + "{field}: {err:?}" + ); + let message = err.to_string(); + assert!(message.contains(field), "{field}: {message}"); + assert!( + message.contains("only mode=overwrite is supported"), + "{field}: {message}" + ); + } + } + + #[rstest] + #[case(None, false)] + #[case(Some(lance::dataset::WriteMode::Create), false)] + #[case(Some(lance::dataset::WriteMode::Append), false)] + #[case(Some(lance::dataset::WriteMode::Overwrite), true)] + #[tokio::test] + async fn add_preserves_supported_write_params( + #[case] mode: Option, + #[case] expect_overwrite: bool, + ) { + let data = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); + let describe_body = describe_response(&data.schema()); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_body.clone()) + .unwrap(), + "/v1/table/my_table/insert/" => { + let mode = request + .url() + .query_pairs() + .find(|(k, _)| k == "mode") + .map(|(_, v)| v.into_owned()); + assert_eq!( + mode.as_deref(), + expect_overwrite.then_some("overwrite"), + "unexpected insert mode for {mode:?}" + ); + http::Response::builder() + .status(200) + .body(r#"{"version": 9}"#.to_string()) + .unwrap() + } + path => panic!("Unexpected request path: {}", path), + }); + + let mut add = table.add(data); + if let Some(mode) = mode { + add = add.write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + mode, + ..Default::default() + }), + }); + } + + assert_eq!(add.execute().await.unwrap().version, 9); + } + #[tokio::test] async fn add_string_blob_becomes_uri_struct_without_the_local_flag() { let table_schema = Schema::new(vec![ diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 045517968..fd7358e9a 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -283,6 +283,10 @@ pub struct WriteOptions { /// /// Overlapping `OpenTableBuilder` options (e.g. [AddDataBuilder::mode]) will take /// precedence over their counterparts in `WriteOptions` (e.g. [WriteParams::mode]). + /// + /// In LanceDB Enterprise, `add` returns [`Error::NotSupported`] when + /// `max_rows_per_file`, `max_rows_per_group`, or `max_bytes_per_file` is + /// non-default, because the remote insert protocol only transmits the write mode. pub lance_write_params: Option, } From 122e5e91d738c2c8a51ec799c57808548498d6b6 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:48:37 +0800 Subject: [PATCH 40/78] fix(python): isolate tokio runtime shutdown across fork generations (#5113) ## Problem A Python process that forks while LanceDB work is in flight inherits the parent's tokio runtime and its outstanding-call count, but the worker threads that would release that count do not survive the fork. A child that exits without using LanceDB can wait for parent work and try to shut down the inherited runtime; a child that creates its own runtime can have stale guards decrement its fresh counter. ## Behavior In-flight calls are now counted per fork generation. An inherited guard only updates the counter it was created with, and `shutdown` waits only for the current generation. A runtime tagged with an older generation is removed and leaked in the child instead of being shut down or joined. The at-fork child handler still only increments the generation counter. The fork hook is installed at the start of the first top-level call, before generation accounting, closing the window where a fork between accounting and runtime initialization could leave the child sharing the parent counter. ## Validation - New fork regressions cover parent work held across fork, child exit without and with its own runtime, and an inherited guard. Each passes when run alone in a fresh process. - `cargo test --quiet --features remote -p lancedb-python --lib runtime::tests` passes 8 tests in both default parallel and serial modes. - `cargo clippy --quiet --features remote -p lancedb-python --tests --examples` and `cargo fmt --all -- --check` pass. - Rebuilt the PyO3 extension; `test_remote_connection_after_fork` and `test_inherited_remote_table_reopens_after_fork` pass. --- python/src/runtime.rs | 537 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 475 insertions(+), 62 deletions(-) diff --git a/python/src/runtime.rs b/python/src/runtime.rs index 8891e2bf2..85d536939 100644 --- a/python/src/runtime.rs +++ b/python/src/runtime.rs @@ -21,37 +21,47 @@ //! rests on three separate mechanisms, each solving one problem the others //! cannot: //! -//! **`OUTSTANDING`, not `Arc::strong_count`, decides when the runtime is -//! idle.** Early versions tried to infer "is anything still using this -//! runtime" from how many `Arc` clones existed. That signal is -//! wrong in both directions: a clone taken only for the instant a task is -//! *submitted* says nothing about whether that task has actually finished -//! running (`Runtime::shutdown_timeout` gives spawned, non-blocking tasks -//! no grace period at all -- a task "keeps running until it yields, then is -//! dropped" -- so a reclaim landing right after submission would silently -//! abandon it before it ever got to run); and a clone held for a task's -//! *whole* lifetime can end up making that task the final owner of the -//! `Runtime`, so completing it drops the `Runtime` from inside one of its -//! own worker threads, which tokio itself forbids ("cannot drop a runtime -//! in a context where blocking is not allowed") and panics. `OUTSTANDING` -//! is an explicit courtesy counter instead: every top-level `spawn`, -//! `spawn_blocking`, or `block_on` call increments it before it starts and -//! decrements it (via [`OutstandingGuard`]) when it is truly done, entirely -//! decoupled from how many `Arc` clones exist at any instant. `shutdown` -//! waits for it to reach zero before ever touching the runtime, which also -//! closes a narrower race: because the counter is incremented *before* -//! `get_runtime()` is even called, an install already in progress when -//! `shutdown` runs is never invisible to it the way an empty slot would be. -//! If the counter never reaches zero within the bound, `shutdown` stops -//! waiting and forces the retirement attempt anyway -- silently returning -//! with the runtime and its workers still fully alive would just recreate -//! the exact race this function exists to close, for any call slower than -//! the grace period. +//! **A per-generation counter, not `Arc::strong_count`, decides when the +//! runtime is idle.** Early versions tried to infer "is anything still +//! using this runtime" from how many `Arc` clones existed. That +//! signal is wrong in both directions: a clone taken only for the instant a +//! task is *submitted* says nothing about whether that task has actually +//! finished running (`Runtime::shutdown_timeout` gives spawned, non-blocking +//! tasks no grace period at all -- a task "keeps running until it yields, +//! then is dropped" -- so a reclaim landing right after submission would +//! silently abandon it before it ever got to run); and a clone held for a +//! task's *whole* lifetime can end up making that task the final owner of +//! the `Runtime`, so completing it drops the `Runtime` from inside one of +//! its own worker threads, which tokio itself forbids ("cannot drop a +//! runtime in a context where blocking is not allowed") and panics. +//! [`GenerationCalls`] is an explicit courtesy counter instead: every +//! top-level `spawn`, `spawn_blocking`, or `block_on` call increments it +//! before it starts and decrements it (via [`OutstandingGuard`]) when it is +//! truly done, entirely decoupled from how many `Arc` clones exist at any +//! instant. `shutdown` waits for the current generation's counter to reach +//! zero before ever touching the runtime, which also closes a narrower +//! race: because the counter is incremented *before* `get_runtime()` is +//! even called, an install already in progress when `shutdown` runs is +//! never invisible to it the way an empty slot would be. If the counter +//! never reaches zero within the bound, `shutdown` stops waiting and forces +//! the retirement attempt anyway -- silently returning with the runtime and +//! its workers still fully alive would just recreate the exact race this +//! function exists to close, for any call slower than the grace period. //! -//! **Tasks never hold an `Arc`.** Because `OUTSTANDING` (not -//! reference counting) is what `shutdown` waits on, a top-level task only -//! needs to carry an `OutstandingGuard` -- a token whose `Drop` is a plain -//! atomic decrement -- not a clone of the runtime itself. That is what +//! **The counter is scoped to a fork generation, not the process.** A +//! single process-wide count cannot survive `fork()`: the child inherits the +//! parent's in-flight value, but the tasks that would decrement it do not +//! run there, and a guard copied onto the forking thread would later +//! decrement the child's count even though it belongs to the parent. Every +//! [`OutstandingGuard`] therefore holds an `Arc` for the +//! generation it was created in. A stale guard can only decrement its own +//! counter, while the child's first call lazily creates a fresh counter, and +//! `shutdown` only waits on the counter matching the live generation. +//! +//! **Tasks never hold an `Arc`.** Because the generation counter +//! (not reference counting) is what `shutdown` waits on, a top-level task +//! only needs to carry an `OutstandingGuard` -- a token whose `Drop` is a +//! plain atomic decrement -- not a clone of the runtime itself. That is what //! makes it impossible for a task's completion to become the final, //! worker-thread-side drop of the `Runtime`: nothing a task holds ever //! *is* the `Runtime`. @@ -74,11 +84,18 @@ //! installed runtime was built in against the live counter on every call, //! from ordinary (non-signal) context, and treats a mismatch as "stale, //! rebuild" -- exactly the check `atfork_child` used to perform directly. +//! [`shutdown`] makes the same comparison, because a child that exits +//! without ever installing its own runtime still finds the parent's stale +//! [`Tagged`] in the slot. It removes that slot and deliberately leaks the +//! instance instead of calling `shutdown_timeout` on it: its worker threads +//! do not exist in this process, so waiting for its counter or trying to +//! join them would hang, and a leaked reference prevents any inherited +//! `Arc` clone from becoming the final owner that drops it. use std::future::Future; use std::pin::Pin; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::time::{Duration, Instant}; use arc_swap::ArcSwapOption; @@ -110,12 +127,21 @@ static RUNTIME: ArcSwapOption = ArcSwapOption::const_empty(); /// access -- just one atomic add, which is all a `pthread_atfork` child /// handler is ever safe to do. static GENERATION: AtomicU64 = AtomicU64::new(0); -/// Count of top-level `spawn`/`spawn_blocking`/`block_on` calls that have -/// started but not yet finished. See the module docs for why this, and not -/// `Arc::strong_count`, is what `shutdown` waits on. -static OUTSTANDING: AtomicU64 = AtomicU64::new(0); +/// In-flight top-level calls for one fork generation. Guards hold an `Arc` +/// to this object for their whole lifetime, so one inherited across `fork()` +/// can only decrement the counter it was created against, never the child's +/// fresh one. +struct GenerationCalls { + generation: u64, + outstanding: AtomicUsize, +} +static CALLS: ArcSwapOption = ArcSwapOption::const_empty(); static ATFORK_INSTALLED: AtomicBool = AtomicBool::new(false); +#[cfg(test)] +static TEST_WORKER_THREADS: AtomicUsize = AtomicUsize::new(0); + +#[cfg(not(test))] fn create_runtime() -> runtime::Runtime { runtime::Builder::new_multi_thread() .enable_all() @@ -124,9 +150,68 @@ fn create_runtime() -> runtime::Runtime { .expect("Failed to build tokio runtime") } +#[cfg(test)] +fn create_runtime() -> runtime::Runtime { + let mut builder = runtime::Builder::new_multi_thread(); + builder.enable_all().thread_name("lancedb-tokio-worker"); + // Fork tests hold two runtimes open at once. Keeping their worker count + // small avoids turning an unrelated parallel build on the same host into + // an apparent hang when the process thread limit is close to full. + let worker_threads = TEST_WORKER_THREADS.load(Ordering::Relaxed); + if worker_threads != 0 { + builder.worker_threads(worker_threads); + } + builder.build().expect("Failed to build tokio runtime") +} + +/// Register the fork-child handler once, before any generation-scoped state +/// is created. +/// +/// The first top-level call deliberately installs the hook before it starts +/// counting itself. Otherwise a fork between taking that first counter and +/// `get_runtime()` installing the hook would leave the child sharing the +/// parent's counter with no generation change to separate them. +fn ensure_atfork_installed() { + if !ATFORK_INSTALLED.fetch_or(true, Ordering::SeqCst) { + install_atfork(); + } +} + +/// Get the in-flight counter for the current fork generation, creating it on +/// the first top-level call after a fork. +fn current_calls() -> Arc { + ensure_atfork_installed(); + let current_gen = GENERATION.load(Ordering::SeqCst); + loop { + let existing = CALLS.load_full(); + if let Some(existing) = &existing + && existing.generation == current_gen + { + return Arc::clone(existing); + } + let candidate = Arc::new(GenerationCalls { + generation: current_gen, + outstanding: AtomicUsize::new(0), + }); + let previous = CALLS.compare_and_swap(&existing, Some(Arc::clone(&candidate))); + let won = match (&*previous, &existing) { + (None, None) => true, + (Some(prev), Some(exist)) => Arc::ptr_eq(prev, exist), + _ => false, + }; + if won { + // A stale counter is only an integer: unlike a runtime it has no + // worker threads to join, so letting the slot's old reference go + // here is safe even in a forked child. + return candidate; + } + } +} + /// Get a live, owned handle to the shared runtime, rebuilding it if the /// installed one predates the most recent `fork()`. fn get_runtime() -> Arc { + ensure_atfork_installed(); let current_gen = GENERATION.load(Ordering::SeqCst); loop { let existing = RUNTIME.load_full(); @@ -135,9 +220,6 @@ fn get_runtime() -> Arc { { return Arc::clone(existing); } - if !ATFORK_INSTALLED.fetch_or(true, Ordering::SeqCst) { - install_atfork(); - } // Built optimistically, outside any lock: on the rare race where two // threads both find the slot empty (or stale), one candidate wins // the compare-and-swap below and the other is simply dropped here, @@ -167,23 +249,26 @@ fn get_runtime() -> Arc { } } -/// RAII token tracked by [`OUTSTANDING`]. Held for the duration of a -/// top-level `block_on` call, or moved into a top-level `spawn`/ -/// `spawn_blocking` task so it decrements only once that task's *entire* -/// body -- including anything it nested-spawns and awaits -- has run to -/// completion or been dropped without completing. -struct OutstandingGuard; +/// RAII token tracked by the current [`GenerationCalls`] counter. Held for +/// the duration of a top-level `block_on` call, or moved into a top-level +/// `spawn`/`spawn_blocking` task so it decrements only once that task's +/// *entire* body -- including anything it nested-spawns and awaits -- has run +/// to completion or been dropped without completing. +struct OutstandingGuard { + calls: Arc, +} impl OutstandingGuard { fn new() -> Self { - OUTSTANDING.fetch_add(1, Ordering::SeqCst); - Self + let calls = current_calls(); + calls.outstanding.fetch_add(1, Ordering::SeqCst); + Self { calls } } } impl Drop for OutstandingGuard { fn drop(&mut self) { - OUTSTANDING.fetch_sub(1, Ordering::SeqCst); + self.calls.outstanding.fetch_sub(1, Ordering::SeqCst); } } @@ -219,13 +304,15 @@ where /// Gracefully quiesce the shared runtime, meant to run at normal process exit. /// -/// Waits (bounded by `timeout`) for [`OUTSTANDING`] to reach zero -- i.e. -/// for every top-level call already under way to actually finish, not just -/// for `Arc::strong_count` to look low -- before ever touching the runtime. -/// If the bound elapses first, it stops waiting and attempts retirement -/// anyway: leaving the runtime and its worker threads untouched would just -/// recreate the exact race this function exists to close, for any call -/// slower than the grace period. +/// Waits (bounded by `timeout`) for the current generation's +/// [`GenerationCalls`] counter to reach zero -- i.e. for every top-level call +/// already under way in *this* process to actually finish, not just for +/// `Arc::strong_count` to look low -- before ever touching the runtime. Work +/// inherited from a parent process at `fork()` belongs to an older +/// generation and is never waited on. If the bound elapses first, it stops +/// waiting and attempts retirement anyway: leaving the runtime and its worker +/// threads untouched would just recreate the exact race this function exists +/// to close, for any call slower than the grace period. /// /// Retirement itself removes the runtime from the slot and calls /// `shutdown_timeout` rather than a bare `drop`: dropping a tokio `Runtime` @@ -238,14 +325,22 @@ where /// the slot and finishing its own call, this abandons the runtime instead /// of forcing the issue -- the same trade `atfork_child` already makes. /// +/// A runtime tagged with a generation older than the live counter was +/// inherited through `fork()` and is never retired here; see the module docs. +/// /// Neither of the two ways this can fail to cleanly retire the runtime -- /// the wait timing out, or `try_unwrap` losing that race -- has any other /// signal to report through (`shutdown_timeout` itself returns nothing), /// so both log a warning instead of failing silently. pub fn shutdown(timeout: Duration) { let deadline = Instant::now() + timeout; + let generation = GENERATION.load(Ordering::SeqCst); + let calls = CALLS.load_full(); + let calls = calls + .as_ref() + .filter(|calls| calls.generation == generation); loop { - let outstanding = OUTSTANDING.load(Ordering::SeqCst); + let outstanding = calls.map_or(0, |calls| calls.outstanding.load(Ordering::SeqCst)); if outstanding == 0 { break; } @@ -260,6 +355,18 @@ pub fn shutdown(timeout: Duration) { let Some(current) = RUNTIME.load_full() else { return; }; + if current.generation != generation { + // The child inherited the parent's installed runtime. Its worker + // threads do not exist here, so waiting on its counter or calling + // `shutdown_timeout` would wait for work that can never finish and + // join threads that can never exit. Remove the slot in ordinary + // context and deliberately leak the instance: inherited `Arc` clones + // may still be dropped in this process, and the leaked reference + // keeps a dropped clone from becoming the final owner. + RUNTIME.compare_and_swap(&Some(Arc::clone(¤t)), None); + std::mem::forget(current); + return; + } RUNTIME.compare_and_swap(&Some(Arc::clone(¤t)), None); match Arc::try_unwrap(current) { Ok(tagged) => { @@ -320,7 +427,7 @@ impl Runtime for LanceRuntime { /// awaits its `JoinHandle`. `Handle::try_current` pins that nested call /// to whatever runtime is already executing it, so only the first, /// outermost call of a chain -- one running on a thread outside any - /// runtime -- ever consults [`get_runtime`] or [`OUTSTANDING`]. + /// runtime -- ever consults [`get_runtime`] or [`OutstandingGuard`]. fn spawn(fut: F) -> Self::JoinHandle where F: Future + Send + 'static, @@ -391,14 +498,14 @@ where mod tests { use super::*; - // RUNTIME, GENERATION, OUTSTANDING, and ATFORK_INSTALLED are process-wide + // RUNTIME, CALLS, GENERATION, and ATFORK_INSTALLED are process-wide // statics, and Rust's test harness runs tests in parallel by default, // so separate test functions below would otherwise race each other // through this shared state (this reproduced in CI: one test's // in-flight task got reclaimed by a *different* test's concurrent - // `shutdown()` call, and another observed `OUTSTANDING` left non-zero - // by a still-running sibling). Every test takes this lock first so - // only one of them touches the shared runtime state at a time; a + // `shutdown()` call, and another observed the in-flight counter left + // non-zero by a still-running sibling). Every test takes this lock first + // so only one of them touches the shared runtime state at a time; a // poisoned lock (a previous test's genuine failure) is still honored // rather than cascading into every later test as an unrelated panic. static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -570,7 +677,7 @@ mod tests { use std::sync::mpsc; let _lock = lock_runtime_state_for_test(); - // Clean slate: no runtime installed, OUTSTANDING at zero. + // Clean slate: no runtime installed, no in-flight calls. shutdown(Duration::from_secs(5)); let (installer_ready_tx, installer_ready_rx) = mpsc::channel::<()>(); @@ -596,6 +703,312 @@ mod tests { // shutdown must have waited for the install to finish and then // retired it, not returned early and left it stranded. assert!(RUNTIME.load_full().is_none()); - assert_eq!(OUTSTANDING.load(Ordering::SeqCst), 0); + let calls = CALLS + .load_full() + .expect("install race left no generation counter"); + assert_eq!(calls.outstanding.load(Ordering::SeqCst), 0); + } + + /// Keep fork-test runtimes small; see [`TEST_WORKER_THREADS`]. + #[cfg(target_os = "linux")] + struct TestWorkerThreads(usize); + + #[cfg(target_os = "linux")] + impl TestWorkerThreads { + fn new(worker_threads: usize) -> Self { + Self(TEST_WORKER_THREADS.swap(worker_threads, Ordering::SeqCst)) + } + } + + #[cfg(target_os = "linux")] + impl Drop for TestWorkerThreads { + fn drop(&mut self) { + TEST_WORKER_THREADS.store(self.0, Ordering::SeqCst); + } + } + + /// Run `f` in a forked child and return the `i32` it reports, or `None` + /// if the child did not report within the bound. The child leaves with + /// `_exit` so it never runs destructors inherited from the test process. + #[cfg(target_os = "linux")] + fn run_in_forked_child(f: F) -> Option + where + F: FnOnce() -> i32, + { + let mut pipe = [0; 2]; + assert_eq!(unsafe { libc::pipe(pipe.as_mut_ptr()) }, 0, "pipe failed"); + let (read_fd, write_fd) = (pipe[0], pipe[1]); + + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + unsafe { libc::close(read_fd) }; + let result = f(); + let bytes = result.to_ne_bytes(); + let written = unsafe { libc::write(write_fd, bytes.as_ptr().cast(), bytes.len()) }; + unsafe { libc::close(write_fd) }; + unsafe { + libc::_exit(if written == bytes.len() as isize { + 0 + } else { + 1 + }) + }; + } + + unsafe { libc::close(write_fd) }; + let mut poll_fd = libc::pollfd { + fd: read_fd, + events: libc::POLLIN, + revents: 0, + }; + let ready = loop { + let ready = unsafe { libc::poll(&mut poll_fd, 1, 10_000) }; + if ready >= 0 { + break ready; + } + let error = std::io::Error::last_os_error(); + assert_eq!( + error.kind(), + std::io::ErrorKind::Interrupted, + "poll failed: {error}" + ); + }; + if ready == 0 { + unsafe { libc::kill(pid, libc::SIGKILL) }; + } + + let mut result = None; + if ready == 1 { + let mut bytes = [0u8; std::mem::size_of::()]; + let read = loop { + let read = unsafe { libc::read(read_fd, bytes.as_mut_ptr().cast(), bytes.len()) }; + if read >= 0 { + break read; + } + let error = std::io::Error::last_os_error(); + assert_eq!( + error.kind(), + std::io::ErrorKind::Interrupted, + "read failed: {error}" + ); + }; + if read == bytes.len() as isize { + result = Some(i32::from_ne_bytes(bytes)); + } + } + unsafe { libc::close(read_fd) }; + + let mut status = 0; + loop { + let waited = unsafe { libc::waitpid(pid, &mut status, 0) }; + if waited == pid { + break; + } + let error = std::io::Error::last_os_error(); + assert_eq!( + error.kind(), + std::io::ErrorKind::Interrupted, + "waitpid failed: {error}" + ); + } + if ready == 0 { + return None; + } + assert_eq!(status, 0, "forked child did not exit successfully"); + result + } + + // The child inherits the parent's installed runtime and its outstanding + // count, but not the worker thread that would ever release that count. + // Its exit-time shutdown must therefore ignore both: waiting for parent + // work would burn the whole grace period, and retiring the inherited + // runtime would try to join worker threads that do not exist here. + #[cfg(target_os = "linux")] + #[test] + fn test_forked_child_shutdown_does_not_wait_for_parent_work() { + use std::sync::mpsc; + use tokio::sync::oneshot; + + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(2); + shutdown(Duration::from_secs(5)); + + let (started_tx, started_rx) = mpsc::channel(); + let (release_tx, release_rx) = oneshot::channel::<()>(); + let (done_tx, done_rx) = mpsc::channel::<()>(); + drop(LanceRuntime::spawn(async move { + started_tx.send(()).unwrap(); + let _ = release_rx.await; + let _ = done_tx.send(()); + })); + started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task did not start"); + + let child_result = run_in_forked_child(|| { + // Much longer than the watchdog: if this waits for inherited + // parent work at all, the child fails to report in time instead + // of the test comparing two elapsed durations. + shutdown(Duration::from_secs(30)); + i32::from(RUNTIME.load_full().is_some()) + }); + assert_eq!( + child_result, + Some(0), + "child shutdown waited for parent work or retired the inherited runtime" + ); + + release_tx.send(()).unwrap(); + done_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task was disturbed by the forked child"); + shutdown(Duration::from_secs(5)); + } + + // A child that builds its own runtime must drain that runtime's own + // work, and only that work: the parent's held task is still outstanding + // in the inherited copy of the counter but can never finish here. + #[cfg(target_os = "linux")] + #[test] + fn test_forked_child_drains_its_own_runtime_without_waiting_for_parent_work() { + use std::sync::mpsc; + use tokio::sync::oneshot; + + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(2); + shutdown(Duration::from_secs(5)); + + let (started_tx, started_rx) = mpsc::channel(); + let (release_tx, release_rx) = oneshot::channel::<()>(); + let (done_tx, done_rx) = mpsc::channel::<()>(); + drop(LanceRuntime::spawn(async move { + started_tx.send(()).unwrap(); + let _ = release_rx.await; + let _ = done_tx.send(()); + })); + started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task did not start"); + + let child_result = run_in_forked_child(|| { + let child_done = Arc::new(AtomicBool::new(false)); + let child_done_flag = Arc::clone(&child_done); + let (task_started_tx, task_started_rx) = mpsc::channel(); + let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>(); + let (child_tx, child_rx) = mpsc::channel(); + drop(LanceRuntime::spawn(async move { + task_started_tx.send(()).unwrap(); + let _ = release_rx.await; + child_done_flag.store(true, Ordering::SeqCst); + let _ = child_tx.send(()); + })); + task_started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("child task did not start"); + + // Keep the child's own task outstanding while shutdown starts, + // then release it once the shutdown thread is about to enter. + let (shutdown_ready_tx, shutdown_ready_rx) = mpsc::channel(); + let shutdown_thread = std::thread::spawn(move || { + shutdown_ready_tx.send(()).unwrap(); + shutdown(Duration::from_secs(30)); + }); + shutdown_ready_rx.recv().unwrap(); + release_tx.send(()).unwrap(); + shutdown_thread.join().unwrap(); + + let drained = child_rx.recv_timeout(Duration::from_secs(5)).is_ok() + && child_done.load(Ordering::SeqCst); + let retired = RUNTIME.load_full().is_none(); + let rebuilt = block_on(async { 40 + 2 }) == 42; + shutdown(Duration::from_secs(30)); + i32::from(!(drained && retired && rebuilt)) + }); + assert_eq!( + child_result, + Some(0), + "child did not drain its own runtime or waited for parent work" + ); + + release_tx.send(()).unwrap(); + done_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task was disturbed by the forked child"); + shutdown(Duration::from_secs(5)); + } + + // A guard created before `fork()` belongs to the parent generation. If + // the child drops that inherited guard, it must decrement the counter it + // was created against, not the child's fresh counter (a naive reset in + // the child would underflow here and make shutdown wait forever). The + // second parent guard stays held across the fork without being dropped + // in the child, so this also proves the child does not wait for work + // that can only finish in the parent. + #[cfg(target_os = "linux")] + #[test] + fn test_inherited_guard_does_not_corrupt_child_generation_counter() { + use std::sync::mpsc; + use tokio::sync::oneshot; + + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(2); + shutdown(Duration::from_secs(5)); + + // This test forks before any runtime exists, so make the hook + // initialization explicit through the same path the first top-level + // call uses; otherwise this test only works after a preceding test + // has installed the process-wide hook. + ensure_atfork_installed(); + // Stands in for a top-level call that was in progress when the + // parent forked and is dropped by the child after it starts work. + let inherited_guard = OutstandingGuard::new(); + // Stays outstanding in the parent for the whole fork, as parent work + // that no child task can ever complete. + let parent_guard = OutstandingGuard::new(); + + let child_result = run_in_forked_child(move || { + let child_done = Arc::new(AtomicBool::new(false)); + let child_done_flag = Arc::clone(&child_done); + let (task_started_tx, task_started_rx) = mpsc::channel(); + let (release_tx, release_rx) = oneshot::channel::<()>(); + let (child_tx, child_rx) = mpsc::channel(); + drop(LanceRuntime::spawn(async move { + task_started_tx.send(()).unwrap(); + let _ = release_rx.await; + child_done_flag.store(true, Ordering::SeqCst); + let _ = child_tx.send(()); + })); + task_started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("child task did not start"); + + // Drop the inherited guard while the child has its own task + // outstanding, so a shared or reset counter would visibly + // perturb the child's accounting. + drop(inherited_guard); + + let (shutdown_ready_tx, shutdown_ready_rx) = mpsc::channel(); + let shutdown_thread = std::thread::spawn(move || { + shutdown_ready_tx.send(()).unwrap(); + shutdown(Duration::from_secs(30)); + }); + shutdown_ready_rx.recv().unwrap(); + release_tx.send(()).unwrap(); + shutdown_thread.join().unwrap(); + + let drained = child_rx.recv_timeout(Duration::from_secs(5)).is_ok() + && child_done.load(Ordering::SeqCst); + let retired = RUNTIME.load_full().is_none(); + i32::from(!(drained && retired)) + }); + assert_eq!( + child_result, + Some(0), + "inherited guard corrupted the child generation counter" + ); + + drop(parent_guard); + shutdown(Duration::from_secs(5)); } } From dcded7fb70e09206cdacb63366f6acb1c7cab77b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 21:01:25 +0800 Subject: [PATCH 41/78] feat(python): default StreamingDataLoader workers to forkserver (#5112) ## Problem `StreamingDataLoader` left PyTorch's platform default in place for worker processes, which is `fork` on Linux. Forked workers inherit the parent process's native runtime and connections, which is the failure mode behind the fork-isolation work. ## Behavior When `num_workers > 0` and `multiprocessing_context` is omitted or `None`, workers now use `forkserver` when the platform provides it, otherwise `spawn`. Explicit start-method names and context objects are unchanged. With `num_workers == 0`, no context is selected, preserving PyTorch's single-process handling. Callbacks and worker state must be picklable under the selected start method, following PyTorch's DataLoader rules. Existing `StreamingDataset` serialization is sufficient for the default worker path. This does not change the explicit fork opt-in or the native client reopen path in #3851. --- docs/web/training/checkpointing.mdx | 2 + python/python/lancedb/streaming.py | 21 +++- .../python/tests/test_elastic_dataloader.py | 100 ++++++++++++++++++ 3 files changed, 122 insertions(+), 1 deletion(-) diff --git a/docs/web/training/checkpointing.mdx b/docs/web/training/checkpointing.mdx index 119601d98..99124549a 100644 --- a/docs/web/training/checkpointing.mdx +++ b/docs/web/training/checkpointing.mdx @@ -54,6 +54,8 @@ Python's built-in `torch.utils.data.DataLoader` produces a safe checkpoint when alongside every internal batch and commits it to the parent `StreamingDataset` only when that batch is returned to the trainer. The trainer receives the same collated batch it would receive from a standard `DataLoader`. +With `num_workers > 0` and `multiprocessing_context` omitted or `None`, `StreamingDataLoader` uses `forkserver` where the platform provides it and falls back to `spawn`. Callback functions and worker state must be picklable under that start method. Multi-worker scripts should keep their entry point behind the standard `if __name__ == "__main__":` guard so spawned workers can import the module safely. + ```py Python icon=Python from lancedb.streaming import StreamingDataset, StreamingDataLoader diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index 810911e28..23a81c135 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -30,7 +30,7 @@ import warnings from collections import deque from concurrent.futures import ThreadPoolExecutor from copy import deepcopy -from multiprocessing import RawArray, get_context +from multiprocessing import RawArray, get_all_start_methods, get_context from typing import Any, Callable, cast, Iterator, Literal, NamedTuple, Optional, Union import pyarrow as pa @@ -60,6 +60,13 @@ DEFAULT_PREFETCH_BATCHES = 4 _UNSET = object() +def _default_worker_start_method() -> str: + """Return the worker start method used when the caller omits a context.""" + if "forkserver" in get_all_start_methods(): + return "forkserver" + return "spawn" + + class _WorkerSample(NamedTuple): data: Any dataset: "StreamingDataset" @@ -1999,6 +2006,14 @@ class StreamingDataLoader(DataLoader): because the custom iterator cannot provide the exact per-yield checkpoint snapshots required by this loader. + When ``num_workers > 0`` and ``multiprocessing_context`` is omitted or + ``None``, workers default to the ``forkserver`` start method when the + platform provides it, and to ``spawn`` otherwise. Explicit start-method + names and context objects are used unchanged. With ``num_workers == 0``, + no context is selected, leaving PyTorch's single-process behavior intact. + Callbacks and worker state must be picklable under the selected start + method, following PyTorch's DataLoader rules. + Examples -------- >>> # dataset = StreamingDataset(table, num_splits=2) @@ -2028,6 +2043,10 @@ class StreamingDataLoader(DataLoader): ) self._streaming_dataset = dataset super().__init__(_StreamingDatasetAdapter(dataset), *args, **kwargs) + # Fill the default only after DataLoader has handled an explicit context; + # num_workers=0 keeps whatever PyTorch decided. + if self.num_workers > 0 and self.multiprocessing_context is None: + self.multiprocessing_context = _default_worker_start_method() if self.drop_last: raise ValueError( "StreamingDataLoader does not support drop_last=True because " diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py index e9fb56c8a..6e6ab45d1 100644 --- a/python/python/tests/test_elastic_dataloader.py +++ b/python/python/tests/test_elastic_dataloader.py @@ -32,6 +32,7 @@ Parameters used throughout: import dataclasses import logging +import multiprocessing as mp import threading from unittest.mock import patch @@ -1028,6 +1029,105 @@ def test_multi_worker_elastic_det_across_worker_counts(lance_table): ) +# ── Worker start method defaults ───────────────────────────────────────────── + + +def _loader_start_method(loader: StreamingDataLoader) -> str: + context = loader.multiprocessing_context + if isinstance(context, str): + return context + assert context is not None + return context.get_start_method() + + +def _platform_worker_start_method() -> str: + return "forkserver" if "forkserver" in mp.get_all_start_methods() else "spawn" + + +def test_default_worker_start_method_prefers_forkserver(): + with patch.object( + streaming, + "get_all_start_methods", + return_value=["fork", "spawn", "forkserver"], + ): + assert streaming._default_worker_start_method() == "forkserver" + + +def test_streaming_dataloader_falls_back_to_spawn_without_forkserver(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + with patch.object(streaming, "get_all_start_methods", return_value=["spawn"]): + loader = StreamingDataLoader(dataset, batch_size=2, num_workers=1) + + assert _loader_start_method(loader) == "spawn" + + +def test_streaming_dataloader_omitted_context_uses_platform_method(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=2, num_workers=1) + + assert _loader_start_method(loader) == _platform_worker_start_method() + + +def test_streaming_dataloader_treats_none_context_as_omitted(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=1, + multiprocessing_context=None, + ) + + assert _loader_start_method(loader) == _platform_worker_start_method() + + +def test_streaming_dataloader_preserves_explicit_start_method(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=1, + multiprocessing_context="spawn", + ) + + assert _loader_start_method(loader) == "spawn" + + +def test_streaming_dataloader_preserves_explicit_context_object(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + context = mp.get_context("spawn") + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=1, + multiprocessing_context=context, + ) + + assert loader.multiprocessing_context is context + + +def test_streaming_dataloader_zero_workers_leave_context_unset(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=12, num_workers=0) + + assert loader.multiprocessing_context is None + ids = [row_id for batch in loader for row_id in batch["id"].tolist()] + assert sorted(ids) == list(range(NUM_ROWS)) + + +def test_streaming_dataloader_default_context_runs_real_worker(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=12, num_workers=1) + assert _loader_start_method(loader) == _platform_worker_start_method() + + iterator = iter(loader) + try: + ids = [row_id for batch in iterator for row_id in batch["id"].tolist()] + finally: + iterator._shutdown_workers() + + assert sorted(ids) == list(range(NUM_ROWS)) + + # ── Resumability with num_workers ───────────────────────────────────────────── From 97996869864ff3c9b59a87532881f498a31f329b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 21:30:40 +0800 Subject: [PATCH 42/78] perf(python): add native eager collection for to_arrow (#5127) ## Summary `to_arrow()` currently collects results one Python future per batch: both sync and async paths call `to_batches()`, which crosses the Python/Rust bridge for every default 1024-row batch. Vector queries also materialize the whole native stream even when no reranker is configured. This adds a shared Rust eager collector. `execute_to_reader` collects the batches in Rust, asks the core to skip the default 1024-row output slicing, and exposes the result through the Arrow C Stream interface, so Python builds the Table without a Python future per batch. Sync and async `to_arrow`, including FTS, vector and hybrid eager paths, use it. `AsyncVectorQuery.to_batches` no longer materializes results when there is no reranker and now honors `max_batch_length`. Schema, empty results, timeout, cancellation, and error behavior are preserved. The existing fragment guard is enforced on the new fast path, and namespace-pushdown routing keeps its existing Python/Rust split. ## Benchmark Development-profile editable build, full scans on one revision, 1 warmup + 5 measured runs. Absolute values are not release-profile numbers; compare before/after on the same build. | Workload | Before | After | |---|---|---| | 5M rows x 3 columns, async | 3.054 s | 0.087 s (35.1x) | | 5M rows x 3 columns, sync | 3.462 s | 0.090 s (38.3x) | | 200k rows x 129 columns, async | 0.354 s | 0.082 s (4.3x) | | 200k rows x 129 columns, sync | 0.387 s | 0.085 s (4.5x) | The narrow scan returned 4,883 batches capped at 1,024 rows before and 611 batches up to 8,192 rows after. --- python/python/lancedb/_lancedb.pyi | 12 +++ python/python/lancedb/query.py | 107 ++++++++++++++++++-- python/python/lancedb/remote/table.py | 8 ++ python/python/lancedb/table.py | 47 +++++++++ python/python/tests/test_eager_collector.py | 57 +++++++++++ python/python/tests/test_fts.py | 6 +- python/python/tests/test_query.py | 3 +- python/src/arrow.rs | 45 +++++++- python/src/query.rs | 64 ++++++++++++ 9 files changed, 333 insertions(+), 16 deletions(-) create mode 100644 python/python/tests/test_eager_collector.py diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 5a89f100b..962000c99 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -962,6 +962,9 @@ class Query: async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> RecordBatchStream: ... + async def execute_to_reader( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -974,6 +977,9 @@ class TakeQuery: def use_rte(self, enable: bool): ... async def output_schema(self) -> pa.Schema: ... async def execute(self) -> RecordBatchStream: ... + async def execute_to_reader( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -1000,6 +1006,9 @@ class FTSQuery: async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> RecordBatchStream: ... + async def execute_to_reader( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -1009,6 +1018,9 @@ class FTSQuery: class VectorQuery: async def output_schema(self) -> pa.Schema: ... async def execute(self) -> RecordBatchStream: ... + async def execute_to_reader( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... def where(self, filter: str): ... def where_expr(self, expr: PyExpr): ... def select(self, columns: List[Tuple[str, str]]): ... diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 76d98e4f6..ce75dd68c 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -2567,10 +2567,24 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): columns and raises for blobs inside lists. """ blob_sources = self._validated_blob_sources(blob_mode) + if blob_mode != "lazy": + return self._finalize_blob_query_table( + self.to_batches(timeout=timeout).read_all(), + blob_mode=blob_mode, + blob_sources=blob_sources, + ) + + self._ensure_fragment_constraints_supported("to_arrow()") + results = self._table._execute_arrow( + self._query_for_scan(blob_sources), timeout=timeout + ) + if self._reranker is not None: + source = results + results = self._reranker.rerank_vector(self._str_query, results) + check_reranker_result(results) + results = _merge_query_snapshot(results, source) return self._finalize_blob_query_table( - self.to_batches(timeout=timeout).read_all(), - blob_mode=blob_mode, - blob_sources=blob_sources, + results, blob_mode=blob_mode, blob_sources=blob_sources ) def to_query_object(self) -> Query: @@ -2895,8 +2909,12 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): blob_sources = self._validated_blob_sources(blob_mode) self._table._ensure_no_legacy_fts_index() + self._ensure_fragment_constraints_supported("to_arrow()") query = self._query_for_scan(blob_sources) - results = self._table._execute_query(query, timeout=timeout).read_all() + if blob_mode == "lazy": + results = self._table._execute_arrow(query, timeout=timeout) + else: + results = self._table._execute_query(query, timeout=timeout).read_all() if self._reranker is not None: source = results results = self._reranker.rerank_fts(self._query, results) @@ -2945,8 +2963,18 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): blob_sources = self._validated_blob_sources(blob_mode) if blob_mode == "bytes" and blob_sources: return self.to_batches(timeout=timeout, blob_mode=blob_mode).read_all() + if blob_mode != "lazy": + return self._finalize_blob_query_table( + self.to_batches(timeout=timeout).read_all(), + blob_mode=blob_mode, + blob_sources=blob_sources, + ) + + self._ensure_fragment_constraints_supported("to_arrow()") return self._finalize_blob_query_table( - self.to_batches(timeout=timeout).read_all(), + self._table._execute_arrow( + self._query_for_scan(blob_sources), timeout=timeout + ), blob_mode=blob_mode, blob_sources=blob_sources, ) @@ -4062,6 +4090,17 @@ class AsyncQueryBase(object): return AsyncRecordBatchReader._from_batches(schema, batches()) + async def _execute_eager( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + """Execute with the native eager collector used by ``to_arrow``.""" + self._ensure_fragment_constraints_supported("to_arrow()") + await self._maybe_add_blob_row_id() + reader = await self._inner.execute_to_reader(None, timeout) + return pa.Table.from_batches(reader, schema=reader.schema) + async def _execute_batches( self, *, @@ -4187,10 +4226,17 @@ class AsyncQueryBase(object): if blob_mode == "bytes" and blob_sources: reader = await self.to_batches(timeout=timeout, blob_mode=blob_mode) return pa.Table.from_batches(await reader.read_all(), schema=reader.schema) - batch_iter = await self.to_batches(timeout=timeout) - tbl = self._finalize_blob_query_table( - pa.Table.from_batches(await batch_iter.read_all(), schema=batch_iter.schema) - ) + if blob_mode != "lazy": + batch_iter = await self.to_batches(timeout=timeout) + tbl = self._finalize_blob_query_table( + pa.Table.from_batches( + await batch_iter.read_all(), schema=batch_iter.schema + ) + ) + else: + tbl = self._finalize_blob_query_table( + await self._execute_eager(timeout=timeout) + ) return await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources) async def to_list( @@ -4936,6 +4982,22 @@ class AsyncFTSQuery(AsyncStandardQuery): ) ) + async def _execute_eager( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + try: + results = await super()._execute_eager(timeout=timeout) + except Exception as error: + _add_fts_position_error_note(error) + raise + if self._reranker: + source = results + results = self._reranker.rerank_fts(self.get_query(), results) + results = _merge_query_snapshot(results, source) + return results + async def _execute_batches( self, *, @@ -5286,6 +5348,18 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): AsyncHybridQuery(self._inner.nearest_to_text({"query": query}), self._table) ) + async def _execute_eager( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + results = await super()._execute_eager(timeout=timeout) + if self._reranker: + source = results + results = self._reranker.rerank_vector(self._query_string, results) + results = _merge_query_snapshot(results, source) + return results + async def _execute_batches( self, *, @@ -5294,8 +5368,12 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): blob_sources: Optional[dict[str, str]] = None, ) -> AsyncRecordBatchReader: reader = await super()._execute_batches( - timeout=timeout, blob_sources=blob_sources + max_batch_length=max_batch_length, + timeout=timeout, + blob_sources=blob_sources, ) + if self._reranker is None: + return reader results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: source = results @@ -5421,6 +5499,15 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): return fts_query, vec_query, limit, offset + async def _execute_eager( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + self._ensure_fragment_constraints_supported("to_arrow()") + reader = await self._execute_batches(timeout=timeout) + return pa.Table.from_batches(await reader.read_all(), schema=reader.schema) + async def _execute_batches( self, *, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 51a656a52..47d0d048f 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -927,6 +927,14 @@ class RemoteTable(Table): return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync()) + def _execute_arrow( + self, + query: Query, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + return LOOP.run(self._table._execute_arrow(query, timeout=timeout)) + def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: return LOOP.run(self._table._explain_plan(query, verbose)) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 492526344..863671bd5 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2926,6 +2926,15 @@ class Table(ABC): timeout: Optional[timedelta] = None, ) -> pa.RecordBatchReader: ... + def _execute_arrow( + self, + query: Query, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + """Execute a query and collect the whole result eagerly.""" + return self._execute_query(query, timeout=timeout).read_all() + @abstractmethod def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: ... @@ -5968,6 +5977,26 @@ class LanceTable(Table): return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync()) + def _execute_arrow( + self, + query: Query, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + # Keep the Python namespace pushdown path, including its branch rule. + if ( + _should_push_down_query_table( + self._namespace_client, self._pushdown_operations + ) + and not self._route_pushdown_to_rust + and self.current_branch() is None + and not _requires_local_namespace_execution(query) + ): + return self._execute_query(query, timeout=timeout).read_all() + + async_query = self._table._sync_query_to_async(query) + return LOOP.run(async_query._execute_eager(timeout=timeout)) + def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: return LOOP.run(self._table._explain_plan(query, verbose)) @@ -8485,6 +8514,24 @@ class AsyncTable: max_batch_length=batch_size, timeout=timeout ) + async def _execute_arrow( + self, + query: Query, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + if ( + _should_push_down_query_table( + self._namespace_client, self._pushdown_operations + ) + and not self._route_pushdown_to_rust + and not _requires_local_namespace_execution(query) + ): + return (await self._execute_query(query, timeout=timeout)).read_all() + + async_query = self._sync_query_to_async(query) + return await async_query._execute_eager(timeout=timeout) + async def _explain_plan(self, query: Query, verbose: Optional[bool]) -> str: # This method is used by the sync table async_query = self._sync_query_to_async(query) diff --git a/python/python/tests/test_eager_collector.py b/python/python/tests/test_eager_collector.py new file mode 100644 index 000000000..1eaed9678 --- /dev/null +++ b/python/python/tests/test_eager_collector.py @@ -0,0 +1,57 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from datetime import timedelta + +import pyarrow as pa +import pytest + +import lancedb + + +@pytest.mark.asyncio +async def test_execute_to_reader_collects_without_default_slicing(tmp_path): + db = await lancedb.connect_async(tmp_path) + rows = 5000 + data = pa.table( + { + "id": pa.array(range(rows), type=pa.int64()), + "text": pa.array([f"row-{i}" for i in range(rows)]), + } + ) + table = await db.create_table("test", data) + + reader = await table._inner.query().execute_to_reader(None, None) + batches = list(reader) + + assert sum(batch.num_rows for batch in batches) == rows + assert max(batch.num_rows for batch in batches) > 1024 + + +@pytest.mark.asyncio +async def test_execute_to_reader_preserves_empty_schema(tmp_path): + db = await lancedb.connect_async(tmp_path) + data = pa.table( + { + "id": pa.array([1, 2], type=pa.int64()), + "text": pa.array(["a", "b"]), + } + ) + table = await db.create_table("test", data) + + query = table._inner.query() + query.where("id < 0") + reader = await query.execute_to_reader(None, None) + result = pa.Table.from_batches(reader, schema=reader.schema) + + assert result.num_rows == 0 + assert result.schema == await table.query().where("id < 0").output_schema() + + +@pytest.mark.asyncio +async def test_execute_to_reader_propagates_timeout(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("test", data=[{"id": 1}, {"id": 2}]) + + with pytest.raises(Exception, match="Query timeout"): + await table._inner.query().execute_to_reader(None, timedelta(0)) diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index 26ce5e528..1bf019fc2 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -1655,7 +1655,9 @@ def test_fts_phrase_query_is_preserved_in_query_object(): def test_fts_phrase_query_execution_preserves_user_text(): table = mock.Mock() table.schema = pa.schema([]) - table._execute_query.return_value = pa.table({"text": ["result"]}).to_reader() + # to_arrow() collects through the eager path; keep a real Table so the + # reranker still receives and returns the real result contract. + table._execute_arrow.return_value = pa.table({"text": ["result"]}) class CapturingReranker: score = "relevance" @@ -1677,7 +1679,7 @@ def test_fts_phrase_query_execution_preserves_user_text(): query.to_arrow() - backend_query = table._execute_query.call_args.args[0] + backend_query = table._execute_arrow.call_args.args[0] assert ( backend_query.full_text_query.query, reranker.queries, diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 82b40f9c6..3b0f3d5a2 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1739,7 +1739,7 @@ def test_query_builder_with_different_vector_column(): ds = mock.Mock() table.to_lance.return_value = ds builder.to_arrow() - table._execute_query.assert_called_once_with( + table._execute_arrow.assert_called_once_with( Query( vector=query, filter="b < 10", @@ -1748,7 +1748,6 @@ def test_query_builder_with_different_vector_column(): columns=["b"], vector_column="foo_vector", ), - batch_size=None, timeout=None, ) diff --git a/python/src/arrow.rs b/python/src/arrow.rs index f0b4bceed..0384f2b2a 100644 --- a/python/src/arrow.rs +++ b/python/src/arrow.rs @@ -2,15 +2,20 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use std::sync::Arc; +use std::time::Duration; use crate::error::PythonErrorExt; use crate::runtime::future_into_py; use arrow::{ datatypes::SchemaRef, pyarrow::{IntoPyArrow, ToPyArrow}, + record_batch::{RecordBatchIterator, RecordBatchReader as ArrowRecordBatchReader}, +}; +use futures::{TryStreamExt, stream::StreamExt}; +use lancedb::{ + arrow::SendableRecordBatchStream, + query::{ExecutableQuery, QueryExecutionOptions}, }; -use futures::stream::StreamExt; -use lancedb::arrow::SendableRecordBatchStream; use pyo3::{ Bound, Py, PyAny, PyRef, PyResult, Python, exceptions::PyStopAsyncIteration, pyclass, pymethods, }; @@ -63,3 +68,39 @@ impl RecordBatchStream { }) } } + +/// Execute `query` and collect every batch in Rust before returning to Python. +/// +/// `to_arrow()` needs the complete table, so the default 1024-row output +/// slicing only adds work. Returning an Arrow C Stream reader also avoids a +/// Python future per batch while python materializes the table. +/// +/// The stream is collected inside the returned future, so timeout and +/// cancellation keep the same observable behavior as reading the stream from +/// Python: errors surface from the awaited call and dropping the future drops +/// the underlying stream. +pub fn execute_to_reader( + py: Python<'_>, + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + future_into_py(py, async move { + let mut options = QueryExecutionOptions::default(); + // `None` means the caller wants one eager result, not the core's + // default batch size. An explicit value is still honored. + options.max_batch_length = max_batch_length.unwrap_or(0); + options.timeout = timeout; + let stream = query.execute_with_options(options).await.infer_error()?; + let schema = stream.schema(); + let batches = stream.try_collect::>().await.infer_error()?; + let reader: Box = Box::new(RecordBatchIterator::new( + batches.into_iter().map(Ok), + schema, + )); + Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) + }) +} diff --git a/python/src/query.rs b/python/src/query.rs index 9864d7d74..3c6d9d662 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -696,6 +696,20 @@ impl Query { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -784,6 +798,20 @@ impl TakeQuery { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -909,6 +937,28 @@ impl FTSQuery { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader( + self_.py(), + self_ + .inner + .clone() + .full_text_search(self_.fts_query.clone()), + max_batch_length, + timeout, + ) + } + pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult> { let mut inner = self_ .inner @@ -1148,6 +1198,20 @@ impl VectorQuery { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { From 85f966a9a9619a659ddadb613fa8420f56939ac0 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 22:08:29 +0800 Subject: [PATCH 43/78] fix: add dataset path hint and sync open_table location (#5128) ## Summary - Expose `location=` on sync `LanceDBConnection.open_table()`, matching the existing async entry point while leaving remote and namespace APIs unchanged. - When a `ListingDatabase` connection URI ends in `.lance`, append a parent-directory and table-stem hint to the derived-URI `TableNotFound` error. The error classification and source chain are preserved, and no extra storage probes are made. Context: OSS-2858 remains canceled. This is only the narrow embedded DX follow-up; it does not add a top-level `lancedb.open_table(uri)` API. ## Verification - Rust targeted listing tests for the `.lance` hint and the explicit-location path. - Python sync `open_table` tests for `location=` and the `.lance` hint. - Pickle round-trip of a sync `location=` table after #5114. - `cargo check --features remote --tests --examples`, `cargo fmt --check`, Ruff format/check. --- docs/src/python/python.md | 8 ++ python/python/lancedb/db.py | 6 + python/python/tests/test_db.py | 29 +++++ rust/lancedb/src/database/listing.rs | 159 +++++++++++++++++++++++---- rust/lancedb/src/error.rs | 46 +++++++- 5 files changed, 227 insertions(+), 21 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index dfd2752b8..5c31d0bb6 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -37,6 +37,14 @@ embedding_functions`. Prefer keyword arguments for optional parameters. ::: lancedb.db.DBConnection +Embedded connections support `location=` on `open_table` to open a table from an +explicit dataset URI instead of the derived `/.lance` path: + +```python +db = lancedb.connect("./data") +table = db.open_table("events", location="./datasets/events.lance") +``` + Use `db.server_info()` (or `await db.server_info()` on an asynchronous connection) to include the responding server's release, Git revision, build date and Function runtime information in a bug report. It returns a JSON-compatible dictionary and diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index aa1d73b29..7a4a85cb6 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -2197,6 +2197,7 @@ class LanceDBConnection(DBConnection): namespace_path: Optional[List[str]] = None, storage_options: Optional[Dict[str, str]] = None, index_cache_size: Optional[int] = None, + location: Optional[str] = None, branch: Optional[str] = None, version: Optional[int] = None, ) -> LanceTable: @@ -2209,6 +2210,10 @@ class LanceDBConnection(DBConnection): namespace_path: List[str], optional The namespace to open the table from. When non-empty, the table is resolved through the directory namespace client. + location: str, optional + The explicit location (URI) of the table. If provided, the table will be + opened from this location instead of deriving it from the database URI + and table name. branch: str, optional If provided, open a handle scoped to this branch instead of the default branch. Reads and writes operate in the branch's context. @@ -2242,6 +2247,7 @@ class LanceDBConnection(DBConnection): namespace_path=namespace_path, storage_options=storage_options, index_cache_size=index_cache_size, + location=location, ) except (RuntimeError, ValueError) as e: if namespace_path and ( diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index fa09a9e19..764d082eb 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -869,6 +869,35 @@ def test_open_table_sync(tmp_db: lancedb.DBConnection): tmp_db.open_table("does_not_exist") +def test_open_table_sync_with_location(tmp_path): + db = lancedb.connect(tmp_path / "db") + db.create_table("test", data=[{"id": 0}]) + dataset_path = tmp_path / "db" / "test.lance" + + other_db = lancedb.connect(tmp_path / "other") + opened = other_db.open_table("test", location=str(dataset_path)) + assert opened.name == "test" + assert opened.count_rows() == 1 + + +def test_open_table_sync_lance_dataset_path_hint(tmp_path): + data_dir = tmp_path / "data" + lancedb.connect(data_dir).create_table("embeddings", data=[{"id": 0}]) + dataset_db = lancedb.connect(data_dir / "embeddings.lance") + + with pytest.raises(ValueError) as exc_info: + dataset_db.open_table("embeddings") + message = str(exc_info.value) + assert "Table 'embeddings' was not found" in message + assert "points to a Lance dataset rather than a database directory" in message + assert f"parent directory '{data_dir}'" in message + assert "open table 'embeddings' instead" in message + + with pytest.raises(ValueError) as exc_info: + dataset_db.open_table("missing", location=str(tmp_path / "missing.lance")) + assert "points to a Lance dataset" not in str(exc_info.value) + + @pytest.mark.asyncio async def test_open_table(tmp_path): from conftest import pandas_string_type diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index 765c8af3d..17ecfadff 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -22,7 +22,7 @@ use crate::blob::ensure_blob_storage_version; use crate::connection::ConnectRequest; use crate::database::ReadConsistency; use crate::database::namespace::LanceNamespaceDatabase; -use crate::error::{CreateDirSnafu, Error, Result}; +use crate::error::{BoxError, CreateDirSnafu, Error, Result, TableNotFoundHint}; use crate::io::object_store::MirroringObjectStoreWrapper; use crate::table::NativeTable; use crate::utils::validate_table_name; @@ -698,6 +698,22 @@ impl ListingDatabase { Ok(()) } + /// Explain a miss caused by connecting to a Lance dataset as if it were a + /// database directory. The connection URI is enough to name the parent and + /// table stem, so this needs no storage probe. + fn lance_dataset_path_hint(&self) -> Option { + let uri = self.uri.trim_end_matches(['/', '\\']); + let (parent, file_name) = uri.rsplit_once(['/', '\\'])?; + let stem = file_name.strip_suffix(".lance")?; + if stem.is_empty() { + return None; + } + let parent = if parent.is_empty() { "." } else { parent }; + Some(format!( + ". The connection URI ends with '.lance', which points to a Lance dataset rather than a database directory. Connect to the parent directory '{parent}' and open table '{stem}' instead." + )) + } + /// Get the URI of a table in the database. fn table_uri(&self, name: &str) -> Result { validate_table_name(name)?; @@ -1180,6 +1196,7 @@ impl Database for ListingDatabase { if !request.namespace_path.is_empty() { return self.namespace_database().open_table(request).await; } + let derived_location = request.location.is_none(); // Use provided location if available, otherwise derive from table name let table_uri = match request.location.clone() { Some(location) => location, @@ -1233,20 +1250,29 @@ impl Database for ListingDatabase { }); read_params.session(self.session.clone()); - let native_table = Arc::new( - NativeTable::open_with_params( - &table_uri, - &request.name, - request.namespace_path, - self.store_wrapper.clone(), - Some(read_params), - self.read_consistency_interval, - request.namespace_client, - HashSet::new(), // listing database doesn't support server-side queries - request.managed_versioning, // Pass through managed_versioning from request - ) - .await?, - ); + let native_table = match NativeTable::open_with_params( + &table_uri, + &request.name, + request.namespace_path, + self.store_wrapper.clone(), + Some(read_params), + self.read_consistency_interval, + request.namespace_client, + HashSet::new(), // listing database doesn't support server-side queries + request.managed_versioning, // Pass through managed_versioning from request + ) + .await + { + Ok(table) => Arc::new(table), + Err(Error::TableNotFound { name, source }) if derived_location => { + let source: BoxError = match self.lance_dataset_path_hint() { + Some(hint) => Box::new(TableNotFoundHint::new(hint, source)), + None => source, + }; + return Err(Error::TableNotFound { name, source }); + } + Err(error) => return Err(error), + }; Ok(native_table) } @@ -1843,10 +1869,100 @@ mod tests { } } - async fn setup_database() -> (tempfile::TempDir, ListingDatabase) { + /// A connection made to a dataset path cannot also be a database directory. The + /// miss names the parent and table stem so the caller can fix the connection. + #[tokio::test] + async fn test_open_table_dataset_path_hint() { let tempdir = tempdir().unwrap(); - let uri = tempdir.path().to_str().unwrap(); + let data_dir = tempdir.path().join("data"); + let data_db = setup_database_at(data_dir.to_str().unwrap()).await; + create_tables(&data_db, &["embeddings"]).await; + let dataset_path = data_dir.join("embeddings.lance"); + let dataset_db = setup_database_at(dataset_path.to_str().unwrap()).await; + let error = dataset_db + .open_table(OpenTableRequest { + name: "embeddings".to_string(), + namespace_path: vec![], + index_cache_size: None, + lance_read_params: None, + location: None, + namespace_client: None, + managed_versioning: None, + }) + .await + .unwrap_err(); + + assert!( + matches!(&error, Error::TableNotFound { name, .. } if name == "embeddings"), + "the dataset path miss changed classification: {error:?}" + ); + let message = error.to_string(); + assert!( + message.contains("points to a Lance dataset rather than a database directory"), + "the hint did not explain the dataset path: {message}" + ); + assert!( + message.contains(&format!("parent directory '{}'", data_dir.display())), + "the hint did not name the parent directory: {message}" + ); + assert!( + message.contains("open table 'embeddings' instead"), + "the hint did not name the table stem: {message}" + ); + } + + /// The hint belongs only to a derived URI. An explicit location is the caller's + /// own choice, so a miss there keeps the original message. + #[tokio::test] + async fn test_open_table_explicit_location_skips_dataset_path_hint() { + let tempdir = tempdir().unwrap(); + let data_dir = tempdir.path().join("data"); + let data_db = setup_database_at(data_dir.to_str().unwrap()).await; + create_tables(&data_db, &["embeddings"]).await; + let dataset_path = data_dir.join("embeddings.lance"); + let dataset_db = setup_database_at(dataset_path.to_str().unwrap()).await; + + let table = dataset_db + .open_table(OpenTableRequest { + name: "alias".to_string(), + namespace_path: vec![], + index_cache_size: None, + lance_read_params: None, + location: Some(dataset_path.to_str().unwrap().to_string()), + namespace_client: None, + managed_versioning: None, + }) + .await + .unwrap(); + assert_eq!(table.count_rows(None).await.unwrap(), 0); + + let missing_path = tempdir.path().join("missing.lance"); + let error = dataset_db + .open_table(OpenTableRequest { + name: "missing".to_string(), + namespace_path: vec![], + index_cache_size: None, + lance_read_params: None, + location: Some(missing_path.to_str().unwrap().to_string()), + namespace_client: None, + managed_versioning: None, + }) + .await + .unwrap_err(); + assert!( + matches!(&error, Error::TableNotFound { name, .. } if name == "missing"), + "the explicit location miss changed classification: {error:?}" + ); + assert!( + !error + .to_string() + .contains("points to a Lance dataset rather than a database directory"), + "an explicit location still received the connection hint: {error}" + ); + } + + async fn setup_database_at(uri: &str) -> ListingDatabase { let request = ConnectRequest { uri: uri.to_string(), #[cfg(feature = "remote")] @@ -1857,11 +1973,14 @@ mod tests { read_consistency_interval: None, session: None, }; - - let db = ListingDatabase::connect_with_options(&request) + ListingDatabase::connect_with_options(&request) .await - .unwrap(); + .unwrap() + } + async fn setup_database() -> (tempfile::TempDir, ListingDatabase) { + let tempdir = tempdir().unwrap(); + let db = setup_database_at(tempdir.path().to_str().unwrap()).await; (tempdir, db) } diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 6aed94d71..3c8a485f9 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -344,6 +344,46 @@ fn server_build_suffix(_source: &(dyn std::error::Error + Send + Sync + 'static) String::new() } +/// Actionable guidance attached to a [`Error::TableNotFound`]. +/// +/// The hint is kept in the error source chain so the missing-table +/// classification and the original failure stay unchanged. +#[derive(Debug)] +pub(crate) struct TableNotFoundHint { + hint: String, + source: BoxError, +} + +impl TableNotFoundHint { + pub(crate) fn new(hint: impl Into, source: BoxError) -> Self { + Self { + hint: hint.into(), + source, + } + } +} + +impl Display for TableNotFoundHint { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.write_str(&self.hint) + } +} + +impl std::error::Error for TableNotFoundHint { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(self.source.as_ref()) + } +} + +fn table_not_found_hint<'a>( + source: &'a (dyn std::error::Error + Send + Sync + 'static), +) -> &'a str { + source + .downcast_ref::() + .map(|hint| hint.hint.as_str()) + .unwrap_or_default() +} + #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { @@ -351,7 +391,11 @@ pub enum Error { InvalidTableName { name: String, reason: String }, #[snafu(display("Invalid input, {message}"))] InvalidInput { message: String }, - #[snafu(display("Table '{name}' was not found{}", server_build_suffix(source.as_ref())))] + #[snafu(display( + "Table '{name}' was not found{}{}", + server_build_suffix(source.as_ref()), + table_not_found_hint(source.as_ref()) + ))] TableNotFound { name: String, source: BoxError }, #[snafu(display( "Table '{name}' exists but could not be loaded (it may be corrupt or incomplete): {source}" From d46754cad456a95e8a5cb5b9d76eeebf8e225852 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 22:17:47 +0800 Subject: [PATCH 44/78] feat: register blob bases during table creation (#5117) ## Summary `create_table` / `create_empty_table` now accept registered storage bases and the embedded opt-in for blob URIs outside them. A create with data registers `initial_bases` in the same commit, so external Blob v2 references no longer need an empty create followed by `add`. - Rust `CreateTableBuilder::initial_bases` / `allow_external_blob_outside_bases`, with `BasePath` re-exported. - PyO3 and Python sync/async create paths accept lightweight `BasePath`, dicts, and duck-typed `lance.DatasetBasePath`; `id=None` lets Lance assign an ID and explicit `0` or duplicate explicit IDs are rejected. - `blob_uri_array` builds the standard four-field `lance.blob.v2` array without pylance and keeps field metadata such as `lancedb:logical_type=mp4`. - Enterprise create rejects non-empty `initial_bases` and the true opt-in before normalization, input iteration, or HTTP; empty/false defaults remain an ordinary create. - Native namespace create merges namespace and connection storage options into the caller's store parameters instead of replacing them. This is reconciled with #5114's refresh layering, so caller-scoped options survive create, refresh, and reopen while namespace-vended values keep their precedence. - The outside-base opt-in applies to one write: setting it on create does not carry over to a later `add()`. ## Validation - `cargo fmt --all -- --check`, `cargo check --quiet --features remote --tests --examples`, `cargo clippy --quiet --features remote --tests --examples`. - Rust: `blob_integration` 66 passed, `database::namespace` 23, `connection::create_table` 16, `remote::db` 128. - Python: `test_blob.py` 263 passed / 1 skipped, `test_blob_array.py` 4, remote create 12, `test_db.py -k "pickle or create_table"` 15, `test_namespace.py -k "pickle or refresh or create"` 29, `test_table.py -k pickle` 8; ruff 0.9.9 and pyright from `python/`. - `test_blob.py` also passes with pylance and pandas removed (177 passed / 87 skipped), matching the CI no-pylance suite. The lightweight and dict create cases keep version, schema, reopen, and exact-range assertions there; only the pylance-only manifest introspection moved into the `DatasetBasePath` case. - Rust and sync Python two-base probes assert that base 1's scoped option fails its read while base 2 still returns exact bytes after reopen. A separate async namespace test covers create and reopen with exact ranges. - `test_namespace_refresh_layers_caller_scoped_options` covers the expired namespace seed: create-time `base_1.caller_scoped` survives refresh, vended `timeout` is replaced (7s to 8s), fresh namespace values appear, and reopen with the caller option returns exact blob range bytes through the registered base. - Updated `main` through #5127 (including #5114) is merged; `rust/lancedb/src/database/namespace.rs` and `rust/lancedb/src/table.rs` match `main`, and no #5114 code was stacked before it merged. ## Dependency note The Lance dependency stays pinned at the `v15.0.0-beta.25` release on `main`. With that pin, mixing an automatic base ID (`id=0`) and an explicit non-zero ID may still collide; the approved upstream fix is https://github.com/lance-format/lance/pull/11307. Use distinct explicit non-zero IDs for multi-base creates, or automatic IDs for every base, until a Lance release containing that fix is pinned. A failed mixed create can leave the table name listed but unopenable; retrying with distinct explicit IDs succeeds. Multi-base validation here uses explicit IDs and bootstrap uses a single automatic ID, so the mixed-ID case is not claimed as verified until a Lance release containing that fix is pinned. --- docs/src/python/python.md | 43 ++- python/python/lancedb/__init__.py | 4 +- python/python/lancedb/_lancedb.pyi | 5 + python/python/lancedb/db.py | 64 ++++ python/python/lancedb/namespace.py | 8 + python/python/lancedb/remote/db.py | 16 + python/python/lancedb/schema.py | 199 ++++++++++ python/python/lancedb/table.py | 18 + python/python/tests/test_blob.py | 390 ++++++++++++++++++++ python/python/tests/test_blob_array.py | 130 +++++++ python/python/tests/test_remote_db.py | 120 ++++++ python/src/connection.rs | 156 +++++++- rust/lancedb/src/connection/create_table.rs | 81 ++++ rust/lancedb/src/lib.rs | 1 + rust/lancedb/src/remote/db.rs | 107 ++++++ rust/lancedb/tests/blob_integration.rs | 374 +++++++++++++++++++ 16 files changed, 1708 insertions(+), 8 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 5c31d0bb6..1581a21b9 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -948,9 +948,42 @@ PyArrow's `RecordBatch.from_pylist(..., schema=...)` cannot convert raw bytes into the blob extension type; use `blob_array` and `RecordBatch.from_arrays` when constructing batches explicitly. -For external blob references, construct the descriptor struct described by -[blob][lancedb.schema.blob], then wrap it with `pa.ExtensionArray.from_storage`. -Inline `data` and external `uri` representations are mutually exclusive. +For external blob references, use [blob_uri_array][lancedb.blob_uri_array]. It builds the +same extension type from URI strings and optional `(position, size)` byte +ranges without requiring pylance. Inline `data` and external `uri` representations +are mutually exclusive. + +Register the object prefix with [BasePath][lancedb.BasePath] on +`create_table(..., initial_bases=[...])` to store a matched absolute blob URI +relative to a base and to scope credentials with `base_. @@ -74,19 +84,26 @@ sampling with replacement. In Rust, an explicit nonempty `QueryBase::order_by` list overrides the requested order; limits and offsets apply after restoring repeated rows. -`take_offsets` also preserves repeated offsets, but does not guarantee -input order. It tracks `_rowoffset` internally to restore repeated rows -and drops that column from the output unless you explicitly `select` it. -Add `_rowoffset` to your selection when you need to align a `take_offsets` -result with the input offsets. +`take_offsets` preserves repeated offsets. By default, it does not guarantee +input order and returns found rows as they arrive. Python sync and async +builders accept `preserve_order=True`, and Rust accepts `.preserve_order()`, +to return found rows in input order, including repeated offsets. Missing +non-negative offsets are omitted; negative offsets are rejected and are not +Python-style relative indices. The default unordered path remains the +existing incremental behavior. + +The method tracks `_rowoffset` internally to restore repeated rows and drops +that column from the output unless you explicitly `select` it. Add +`_rowoffset` to your selection when you need to align a `take_offsets` result +with the input offsets. -Ordered takes by row ID collect all matching batches, combine them into one -batch and reorder the rows before returning output batches. Even -`to_batches(max_batch_length=1)` only limits the returned batch size; it -does not bound working memory. For large requests or rows with large -column values, split the input IDs into smaller requests and use -`.select(...)` to fetch only the columns you need. +Ordered takes by row ID, and ordered offset takes with `preserve_order=True`, +collect all matching batches, combine them into one batch and reorder the rows +before returning output batches. Even `to_batches(max_batch_length=1)` only +limits the returned batch size; it does not bound working memory. For large +requests or rows with large column values, split the input IDs or offsets into +smaller requests and use `.select(...)` to fetch only the columns you need. Offsets are mostly useful for sampling: the valid range is always diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 9a53d8985..6bdcfffd1 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -985,6 +985,7 @@ class Query: class TakeQuery: def select(self, columns: List[str]): ... def with_row_id(self): ... + def preserve_order(self): ... def use_rte(self, enable: bool): ... async def output_schema(self) -> pa.Schema: ... async def execute(self) -> RecordBatchStream: ... @@ -1092,6 +1093,7 @@ class PyQueryRequest: offset: Optional[int] take_offsets: Optional[List[int]] take_row_ids: Optional[List[int]] + preserve_order: Optional[bool] filter: Optional[Union[str, bytes]] full_text_search: Optional[FullTextQuery] select: Optional[Union[str, List[str]]] diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 845386181..6d3cf818b 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -1186,6 +1186,9 @@ class Query(pydantic.BaseModel): # Row IDs whose requested order and duplicate occurrences must be restored. take_row_ids: Optional[List[int]] = None + # Restore take-offset duplicates in the exact input order. + preserve_order: Optional[bool] = None + # if true, will only search the indexed data fast_search: Optional[bool] = None @@ -1212,6 +1215,7 @@ class Query(pydantic.BaseModel): query.offset = req.offset query.take_offsets = req.take_offsets query.take_row_ids = req.take_row_ids + query.preserve_order = req.preserve_order query.filter = req.filter query.full_text_query = req.full_text_search query.columns = req.select diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 47d0d048f..dba3a9eaf 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1556,9 +1556,15 @@ class RemoteTable(Table): return LOOP.run(self._table.uri()) def take_offsets( - self, offsets: list[int], *, with_row_id: bool = False + self, + offsets: list[int], + *, + with_row_id: bool = False, + preserve_order: bool = False, ) -> LanceTakeQueryBuilder: - builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets)) + builder = LanceTakeQueryBuilder( + self._table.take_offsets(offsets, preserve_order=preserve_order) + ) if with_row_id: builder.with_row_id() return builder diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 2a44d0221..52ae6b9fd 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2660,7 +2660,11 @@ class Table(ABC): @abstractmethod def take_offsets( - self, offsets: list[int], *, with_row_id: bool = False + self, + offsets: list[int], + *, + with_row_id: bool = False, + preserve_order: bool = False, ) -> LanceTakeQueryBuilder: """ Take a list of offsets from the table. @@ -2672,9 +2676,13 @@ class Table(ABC): Offsets are mostly useful for sampling as the set of all valid offsets is easily known in advance to be [0, len(table)). - No guarantees are made regarding the order in which results are returned. - Repeated offsets produce repeated rows, which makes this method suitable for - sampling with replacement. + By default, no guarantees are made regarding the order in which results + are returned. Repeated offsets produce repeated rows, which makes this + method suitable for sampling with replacement. Set ``preserve_order=True`` + to return found rows in input order, including repeated offsets. Missing + non-negative offsets are omitted. Negative offsets are rejected and are + not Python-style relative indices. ``preserve_order`` cannot be combined + with an explicit ``order_by``. Parameters ---------- @@ -2682,6 +2690,10 @@ class Table(ABC): The offsets to take. with_row_id: bool, default False If True, include the "_rowid" column in the results. + preserve_order: bool, default False + If True, return found rows in input order. Rust take queries apply + limit/offset after restoration; Python take builders and Query + conversion do not expose pagination. Returns ------- @@ -4533,9 +4545,15 @@ class LanceTable(Table): return LOOP.run(self._table.version()) def take_offsets( - self, offsets: list[int], *, with_row_id: bool = False + self, + offsets: list[int], + *, + with_row_id: bool = False, + preserve_order: bool = False, ) -> LanceTakeQueryBuilder: - builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets)) + builder = LanceTakeQueryBuilder( + self._table.take_offsets(offsets, preserve_order=preserve_order) + ) if with_row_id: builder.with_row_id() return builder @@ -8449,10 +8467,18 @@ class AsyncTable: if query.take_offsets is not None or query.take_row_ids is not None: if query.take_offsets is not None and query.take_row_ids is not None: raise ValueError("Only one of take_offsets and take_row_ids may be set") + if query.preserve_order is True and query.take_offsets is None: + raise ValueError("preserve_order only supports take_offsets") + if query.preserve_order is True and query.order_by: + raise ValueError( + "preserve_order cannot be combined with an explicit order_by" + ) take_query = ( self.take_row_ids(query.take_row_ids) if query.take_row_ids is not None - else self.take_offsets(query.take_offsets) + else self.take_offsets( + query.take_offsets, preserve_order=query.preserve_order is True + ) ) if query.columns is not None: columns = query.columns @@ -9662,7 +9688,11 @@ class AsyncTable: await self._inner.restore(version) def take_offsets( - self, offsets: list[int], *, with_row_id: bool = False + self, + offsets: list[int], + *, + with_row_id: bool = False, + preserve_order: bool = False, ) -> AsyncTakeQuery: """ Take a list of offsets from the table. @@ -9674,8 +9704,12 @@ class AsyncTable: Offsets are mostly useful for sampling as the set of all valid offsets is easily known in advance to be [0, len(table)). - No guarantees are made regarding the order in which results are returned. - Repeated offsets produce repeated rows. + By default, no guarantees are made regarding the order in which results + are returned. Repeated offsets produce repeated rows. Set + ``preserve_order=True`` to return found rows in input order, including + repeated offsets. Missing non-negative offsets are omitted. Negative + offsets are rejected and are not Python-style relative indices. + ``preserve_order`` cannot be combined with an explicit ``order_by``. Parameters ---------- @@ -9683,6 +9717,10 @@ class AsyncTable: The offsets to take. with_row_id: bool, default False If True, include the "_rowid" column in the results. + preserve_order: bool, default False + If True, return found rows in input order. Rust take queries apply + limit/offset after restoration; Python take builders and Query + conversion do not expose pagination. Returns ------- @@ -9691,6 +9729,8 @@ class AsyncTable: offsets. """ query = AsyncTakeQuery(self._inner.take_offsets(offsets), self) + if preserve_order: + query._inner.preserve_order() if with_row_id: query.with_row_id() return query diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index 7373bbdf4..57dbc09ff 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -1017,6 +1017,11 @@ def test_take_queries_honor_blob_mode(): 1: b"one", 2: b"two", } + ordered = table.take_offsets([1, 0], preserve_order=True).to_arrow( + blob_mode="bytes" + ) + assert ordered["id"].to_pylist() == [2, 1] + assert ordered["image"].to_pylist() == [b"two", b"one"] assert [ row["image"] for row in table.take_row_ids([0]).to_list(blob_mode="bytes") ] == [b"one"] diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index c9a96167c..ec747bd40 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -975,6 +975,10 @@ async def test_async_take_query_to_pandas_blob_v2_bytes(tmp_db_async): df = await table.take_offsets([1, 2]).to_pandas(blob_mode="bytes") assert set(df["blob"]) == {b"two", b"three"} + ordered = await table.take_offsets([2, 1], preserve_order=True).to_pandas( + blob_mode="bytes" + ) + assert ordered["blob"].tolist() == [b"three", b"two"] def test_order_by_plain_query(mem_db): @@ -2815,6 +2819,86 @@ def test_take_queries(tmp_path): assert table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list() == [5, 2, 17] +def test_take_offsets_preserve_order_sync(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("test", pa.table({"idx": range(4)})) + table.add(pa.table({"idx": range(4, 8)})) + table.delete("idx IN (1, 6)") + requested = [5, 0, 5, 2, 99, 4, 0] + expected = [7, 0, 7, 3, 5, 0] + + actual = ( + table.take_offsets(requested, preserve_order=True).select(["idx"]).to_arrow() + ) + assert actual.column_names == ["idx"] + assert actual["idx"].to_pylist() == expected + + batches = list( + table.take_offsets(requested, preserve_order=True) + .select(["idx"]) + .to_batches(max_batch_length=1) + ) + assert all(batch.num_rows <= 1 for batch in batches) + assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected + + # The default path keeps its unspecified-order behavior. + default = table.take_offsets(requested).select(["idx"]).to_arrow() + assert sorted(default["idx"].to_pylist()) == sorted(expected) + + assert table.take_offsets(requested).to_query_object().preserve_order is None + query = ( + table.take_offsets(requested, preserve_order=True) + .select(["idx"]) + .to_query_object() + ) + assert query.preserve_order is True + assert table._execute_query(query).read_all()["idx"].to_pylist() == expected + + empty = table.take_offsets([], preserve_order=True).select(["idx"]).to_arrow() + assert empty.num_rows == 0 + assert empty.column_names == ["idx"] + + query.order_by = [ColumnOrdering(column_name="idx")] + with pytest.raises( + ValueError, match="preserve_order cannot be combined with an explicit order_by" + ): + table._execute_query(query) + + +@pytest.mark.asyncio +async def test_take_offsets_preserve_order_async(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("test", pa.table({"idx": range(4)})) + await table.add(pa.table({"idx": range(4, 8)})) + await table.delete("idx IN (1, 6)") + requested = [5, 0, 5, 2, 99, 4, 0] + expected = [7, 0, 7, 3, 5, 0] + + actual = ( + await table.take_offsets(requested, preserve_order=True) + .select(["idx"]) + .to_arrow() + ) + assert actual.column_names == ["idx"] + assert actual["idx"].to_pylist() == expected + + reader = ( + await table.take_offsets(requested, preserve_order=True) + .select(["idx"]) + .to_batches(max_batch_length=1) + ) + batches = [batch async for batch in reader] + assert all(batch.num_rows <= 1 for batch in batches) + assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected + + query = ( + table.take_offsets(requested, preserve_order=True) + .select(["idx"]) + .to_query_object() + ) + assert query.preserve_order is True + + @pytest.mark.parametrize("selection", [None, [], ["idx"], {"_rowid": "100 - idx"}]) @pytest.mark.parametrize("empty", [False, True]) def test_take_row_ids_order_and_roundtrip(tmp_path, selection, empty): @@ -2921,6 +3005,13 @@ def test_getitems(tmp_path): assert table.__getitems__(offsets) == pa.table({"idx": offsets}) +def test_getitems_rejects_missing_offsets(tmp_path): + table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": range(3)})) + + with pytest.raises(pa.ArrowIndexError, match="out of bounds"): + table.__getitems__([0, 99]) + + @pytest.mark.asyncio async def test_query_timeout_async(tmp_path): db = await lancedb.connect_async(tmp_path) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index a4edd78a0..7089f1e0b 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1404,6 +1404,12 @@ def test_remote_permutation_is_picklable(): {"a": 2}, {"a": 4}, ] + assert table.take_offsets([0, 2, 0, 4], preserve_order=True).to_list() == [ + {"a": 0}, + {"a": 2}, + {"a": 0}, + {"a": 4}, + ] permutation = Permutation.identity(table) restored = pickle.loads(pickle.dumps(permutation)) @@ -6083,14 +6089,26 @@ def blob_remote_table( if requests is not None: requests.append(("query", body)) columns = body.get("columns") - assert columns in ( + take_offsets_query = isinstance(columns, list) and "_rowoffset" in columns + assert take_offsets_query or columns in ( None, ["id", "image"], ["id"], ["image"], {"payload": "image"}, ) - if isinstance(columns, dict): + if take_offsets_query: + response_table = blob_query_response_table().append_column( + "_rowoffset", pa.array(range(3), type=pa.uint64()) + ) + response_table = response_table.select( + [name for name in columns if name != "_rowid"] + ) + if body.get("with_row_id", False): + response_table = response_table.append_column( + "_rowid", blob_query_response_table()["_rowid"] + ) + elif isinstance(columns, dict): response_table = blob_query_response_table().select(["image", "_rowid"]) response_table = response_table.rename_columns(["payload", "_rowid"]) if not body.get("with_row_id", False): @@ -6725,6 +6743,18 @@ def test_remote_blob_fetch_accepts_metadata_free_query_table(api): handle.close() +def test_remote_take_offsets_preserve_order_with_blob_bytes(): + with blob_remote_table() as table: + hits = ( + table.take_offsets([2, 0, 2], preserve_order=True) + .select(["id", "image"]) + .to_arrow(blob_mode="bytes") + ) + + assert hits["id"].to_pylist() == [3, 1, 3] + assert hits["image"].to_pylist() == [b"gamma", b"alpha", b"gamma"] + + @pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"]) def test_remote_blob_fetch_from_query_result_keeps_query_snapshot(api): requests = [] diff --git a/python/src/query.rs b/python/src/query.rs index 3c6d9d662..2c1a606eb 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -357,6 +357,7 @@ pub struct PyQueryRequest { pub offset: Option, pub take_offsets: Option>, pub take_row_ids: Option>, + pub preserve_order: Option, pub filter: Option, pub full_text_search: Option>, pub select: PySelect, @@ -390,6 +391,7 @@ impl From for PyQueryRequest { offset: query_request.offset, take_offsets: query_request.take_offsets, take_row_ids: query_request.take_row_ids, + preserve_order: query_request.preserve_order.then_some(true), filter: query_request.filter.map(PyQueryFilter), full_text_search: query_request .full_text_search @@ -423,6 +425,7 @@ impl From for PyQueryRequest { offset: vector_query.base.offset, take_offsets: vector_query.base.take_offsets, take_row_ids: vector_query.base.take_row_ids, + preserve_order: vector_query.base.preserve_order.then_some(true), filter: vector_query.base.filter.map(PyQueryFilter), full_text_search: None, select_source_columns: PySelect::source_columns(&vector_query.base.select), @@ -765,6 +768,10 @@ impl TakeQuery { self.inner = self.inner.clone().with_row_id(); } + pub fn preserve_order(&mut self) { + self.inner = self.inner.clone().preserve_order(); + } + pub fn use_rte(&mut self, enable: bool) { self.inner = self.inner.clone().use_rte(enable); } diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 157440910..57af7f28d 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -867,6 +867,13 @@ pub struct QueryRequest { #[doc(hidden)] pub take_row_ids: Option>, + /// Restore `take_offsets` occurrences in the exact requested input order. + /// + /// This is client-side execution metadata and is not sent to remote + /// services. It cannot be combined with an explicit `order_by`. + #[doc(hidden)] + pub preserve_order: bool, + /// Apply filter to the returned rows. pub filter: Option, @@ -937,6 +944,7 @@ impl Default for QueryRequest { offset: None, take_offsets: None, take_row_ids: None, + preserve_order: false, filter: None, filter_error: None, full_text_search: None, @@ -2065,7 +2073,6 @@ impl ExecutionPlan for TakeRestoreExec { pub struct TakeQuery { parent: Arc, request: QueryRequest, - preserve_order: bool, } struct TakeLookup { @@ -2100,7 +2107,6 @@ impl TakeQuery { take_offsets: Some(offsets), ..Default::default() }, - preserve_order: false, } } @@ -2122,16 +2128,17 @@ impl TakeQuery { take_row_ids: Some(row_ids), ..Default::default() }, - preserve_order: false, } } /// Preserve the requested offset order when restoring duplicate occurrences. /// - /// This is reserved for readers whose API explicitly guarantees ordering. - pub(crate) fn preserve_order(mut self) -> Self { + /// Found rows follow the input order, including repeated offsets. Missing + /// non-negative offsets are omitted. This cannot be combined with an + /// explicit `order_by`. + pub fn preserve_order(mut self) -> Self { debug_assert!(self.request.take_offsets.is_some()); - self.preserve_order = true; + self.request.preserve_order = true; self } @@ -2203,8 +2210,25 @@ impl TakeQuery { }); } }; - let preserve_order = - preserve_order || (by_row_id && request.order_by.as_ref().is_none_or(Vec::is_empty)); + // The explicit flag only applies to offset takes. Row-id takes retain + // their existing implicit ordering behavior: input order when no sort is + // requested, and the explicit sort otherwise. + let explicit_preserve_order = !by_row_id && (preserve_order || request.preserve_order); + if explicit_preserve_order + && request + .order_by + .as_ref() + .is_some_and(|order_by| !order_by.is_empty()) + { + return Err(Error::InvalidInput { + message: "preserve_order cannot be combined with an explicit order_by".to_string(), + }); + } + let preserve_order = if by_row_id { + request.order_by.as_ref().is_none_or(Vec::is_empty) + } else { + explicit_preserve_order + }; let (mut request, ordering_column, drop_ordering_column, output_projection) = if by_row_id { let mut request = request.clone(); let with_row_id = request.with_row_id; @@ -2527,7 +2551,7 @@ impl ExecutableQuery for TakeQuery { self.parent.as_ref(), &self.request, options, - self.preserve_order, + self.request.preserve_order, ) .await; } @@ -2564,7 +2588,7 @@ impl ExecutableQuery for TakeQuery { self.parent.as_ref(), &self.request, verbose, - self.preserve_order, + self.request.preserve_order, ) .await; } @@ -4295,6 +4319,53 @@ mod tests { ); } + async fn make_preserve_order_test_table(tmp_dir: &tempfile::TempDir) -> Table { + let dataset_path = tmp_dir.path().join("preserve_order.lance"); + let conn = connect(dataset_path.to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = conn + .create_table( + "my_table", + RecordBatch::try_from_iter([( + "idx", + Arc::new(Int32Array::from(vec![0, 1, 2, 3])) as Arc, + )]) + .unwrap(), + ) + .execute() + .await + .unwrap(); + table + .add( + RecordBatch::try_from_iter([( + "idx", + Arc::new(Int32Array::from(vec![4, 5, 6, 7])) as Arc, + )]) + .unwrap(), + ) + .execute() + .await + .unwrap(); + table.delete("idx IN (1, 6)").await.unwrap(); + table + } + + fn collect_ids(batches: &[RecordBatch]) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch + .column_by_name("idx") + .unwrap() + .as_primitive::() + .values() + .to_vec() + }) + .collect() + } + #[tokio::test] async fn test_take_offsets_applies_pagination_after_restoration() { let tmp_dir = tempdir().unwrap(); @@ -4345,6 +4416,104 @@ mod tests { ); } + #[tokio::test] + async fn test_take_offsets_preserve_order_across_fragments_deletes_and_batches() { + let tmp_dir = tempdir().unwrap(); + let table = make_preserve_order_test_table(&tmp_dir).await; + let offsets = vec![5, 0, 5, 2, 99, 4, 0]; + let expected = vec![7, 0, 7, 3, 5, 0]; + + let batches = table + .take_offsets(offsets.clone()) + .preserve_order() + .select(Select::Columns(vec!["idx".to_string()])) + .execute_with_options(QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + + assert!(batches.iter().all(|batch| batch.num_rows() <= 1)); + assert_eq!(collect_ids(&batches), expected); + + let converted = table + .take_offsets(offsets) + .preserve_order() + .select(Select::Columns(vec!["idx".to_string()])) + .into_request(); + let batches = table + .base_table() + .query( + &AnyQuery::Query(converted), + QueryExecutionOptions::default(), + ) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_ids(&batches), expected); + + let batches = table + .take_offsets(vec![]) + .preserve_order() + .select(Select::Columns(vec!["idx".to_string()])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 0); + } + + #[tokio::test] + async fn test_take_offsets_preserve_order_paginates_after_restoration() { + let tmp_dir = tempdir().unwrap(); + let table = make_preserve_order_test_table(&tmp_dir).await; + + let batches = table + .take_offsets(vec![5, 0, 5, 2, 4, 0]) + .preserve_order() + .select(Select::Columns(vec!["idx".to_string()])) + .offset(2) + .limit(4) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_ids(&batches), vec![7, 3, 5, 0]); + } + + #[tokio::test] + async fn test_take_offsets_preserve_order_rejects_order_by() { + let tmp_dir = tempdir().unwrap(); + let table = make_preserve_order_test_table(&tmp_dir).await; + + let error = table + .take_offsets(vec![0, 2]) + .preserve_order() + .order_by(Some(vec![ColumnOrdering::asc_nulls_first( + "idx".to_string(), + )])) + .execute() + .await + .err() + .unwrap(); + assert!( + error + .to_string() + .contains("preserve_order cannot be combined with an explicit order_by"), + "{error}" + ); + } + #[tokio::test] async fn test_take_offsets_create_plan_restores_occurrences() { let tmp_dir = tempdir().unwrap(); @@ -4613,6 +4782,35 @@ mod tests { } } + #[tokio::test] + async fn test_take_row_ids_ignores_offset_preserve_flag_with_explicit_sort() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + let mut request = table + .take_row_ids(vec![17, 5, 1, 5]) + .order_by(Some(vec![ColumnOrdering::asc_nulls_first( + "id".to_string(), + )])) + .offset(1) + .limit(2) + .into_request(); + request.preserve_order = true; + + let batches = table + .base_table() + .query(&AnyQuery::Query(request), QueryExecutionOptions::default()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!( + actual["id"].as_primitive::().values().as_ref(), + &[5, 5] + ); + } + #[tokio::test] async fn test_take_row_ids_explicit_order_by() { let tmp_dir = tempdir().unwrap(); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 4c7f3a105..760ab83fe 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3420,7 +3420,8 @@ impl BaseTable for RemoteTable { if let AnyQuery::Query(request) = query && request.has_take() { - return crate::query::create_take_plan(self, request, options, false).await; + return crate::query::create_take_plan(self, request, options, request.preserve_order) + .await; } let streams = self.execute_query(query, &options).await?; @@ -3444,8 +3445,13 @@ impl BaseTable for RemoteTable { if let AnyQuery::Query(request) = query && request.has_take() { - let plan = - crate::query::create_take_plan(self, request, options.clone(), false).await?; + let plan = crate::query::create_take_plan( + self, + request, + options.clone(), + request.preserve_order, + ) + .await?; let inner = execute_plan(plan, Default::default())?; let inner = MaxBatchLengthStream::new_boxed(inner, options.max_batch_length as usize); let inner = if let Some(timeout) = options.timeout { @@ -3508,7 +3514,8 @@ impl BaseTable for RemoteTable { if let AnyQuery::Query(request) = query && request.has_take() { - return crate::query::explain_take_plan(self, request, verbose, false).await; + return crate::query::explain_take_plan(self, request, verbose, request.preserve_order) + .await; } let base_request = self @@ -8601,8 +8608,8 @@ mod tests { Field::new("_rowoffset", DataType::UInt64, false), ])), vec![ - Arc::new(Int32Array::from(vec![5])), - Arc::new(arrow_array::UInt64Array::from(vec![5])), + Arc::new(Int32Array::from(vec![1, 5])), + Arc::new(arrow_array::UInt64Array::from(vec![1, 5])), ], ) .unwrap(); @@ -8614,7 +8621,8 @@ mod tests { }); let request = table - .take_offsets(vec![5, 5]) + .take_offsets(vec![5, 1, 5]) + .preserve_order() .select(crate::query::Select::columns(&["id"])) .into_request(); let batches = table @@ -8626,12 +8634,24 @@ mod tests { .await .unwrap(); - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 2); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 3); assert!( batches .iter() .all(|batch| batch.schema().fields().len() == 1) ); + let ids = batches + .iter() + .flat_map(|batch| { + batch + .column_by_name("id") + .unwrap() + .as_primitive::() + .values() + .to_vec() + }) + .collect::>(); + assert_eq!(ids, vec![5, 1, 5]); } #[rstest::rstest] diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 6789714e1..b69b85cb3 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -180,7 +180,8 @@ pub async fn create_plan( if let AnyQuery::Query(request) = &query && request.has_take() { - return crate::query::create_take_plan(table, request, options, false).await; + return crate::query::create_take_plan(table, request, options, request.preserve_order) + .await; } let query = match query { From 13fe33581e6fa0c9433f0ff99e6981eab4ba1a07 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 04:41:11 +0800 Subject: [PATCH 52/78] perf(python): add direct sync query execution (#5141) ## Summary Route ordinary local `table.search(...).to_arrow()` queries through private synchronous schema and eager-collection bindings instead of the Python background event loop. Plain scans, vector searches (including default vector-column inference), and native FTS in lazy Blob mode now complete with zero `LOOP.run` submissions. The synchronous path reuses the existing query lowering, core query execution, eager collector, Arrow ownership, projection validation, fragments, row ids, Blob finalization, reranking, and snapshot handling. It uses the generation-scoped Tokio runtime and `OutstandingGuard`, releases the GIL while waiting, checks CPython signals on the caller thread at a bounded interval, and aborts and drops collected state when a handler raises. Multi-threaded Tokio callback re-entry uses `block_in_place`; current-thread contexts return a Python error. Namespace, RemoteTable, Enterprise, streaming, take, and non-lazy Blob routing are unchanged. No public API is added. ## Benchmark Workload: 200,000 rows, 64 dimensions, BTREE on `id`, IVF_PQ on `vector`; 50 warmups + 500 calls, p50/p99 of three alternating runs. Build: `release-with-debug`. Baseline Python package from `03fc5404` ran against the same candidate extension as the candidate, so this isolates the Python event-loop route; a separately built matching baseline extension is a follow-up validation target. The host had competing Rust builds, so these numbers are preliminary, not isolated release throughput. | Workload | LOOP/schema per call before -> after | p50 before -> after | p99 before -> after | |---|---|---|---| | plain point lookup `to_arrow()` | 2 / 1 -> 0 / 1 | 2.32 / 3.26 / 2.64 ms -> 1.64 / 1.89 / 1.80 ms | 3.87 / 3.92 / 3.69 ms -> 2.42 / 2.63 / 2.62 ms | | indexed vector `to_arrow()` | 3 / 2 -> 0 / 2 | 5.20 / 5.13 / 3.79 ms -> 4.65 / 4.22 / 4.31 ms | 7.18 / 7.52 / 6.45 ms -> 6.29 / 6.01 / 6.43 ms | `to_batches()` remains on the existing streaming path. OSS-2868 1/2/4/8/16-thread scaling and fully matched build artifacts remain separate follow-up. ## Validation - `test_sync_query_direct.py`: plain/vector/native FTS with `LOOP.run` patched to fail, default vector inference, empty schema, timeout, single-worker progress-callback re-entry, and SIGINT/runtime reuse. - `test_query.py` with direct tests: 253 passed, 1 skipped. - `test_blob.py`: 266 passed, 1 skipped. - `test_fts.py` + `test_rerankers.py`: 163 passed, 13 skipped. - `test_table.py` + `test_namespace.py` + `test_sync_api_parity.py`: 649 passed, 17 skipped. - Remote query/blob/schema subset: 206 passed. - Runtime unit tests: 12 passed; `cargo check`, `cargo clippy`, `cargo fmt --check`, and Python ruff passed. The SIGINT case is marked slow and was run in focused validation; it is not part of the default suite. Refs OSS-2867 (non-closing). --- python/python/lancedb/_lancedb.pyi | 10 + python/python/lancedb/query.py | 60 ++++++ python/python/lancedb/table.py | 15 +- python/python/tests/test_query.py | 8 +- python/python/tests/test_sync_query_direct.py | 160 ++++++++++++++ python/src/arrow.rs | 53 +++-- python/src/query.rs | 50 +++++ python/src/runtime.rs | 200 +++++++++++++++++- python/src/table.rs | 10 +- 9 files changed, 546 insertions(+), 20 deletions(-) create mode 100644 python/python/tests/test_sync_query_direct.py diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 6bdcfffd1..eb8536f3e 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -575,6 +575,7 @@ class Table: def _is_native(self) -> bool: ... def close(self) -> None: ... async def schema(self) -> pa.Schema: ... + def schema_sync(self) -> pa.Schema: ... async def add( self, data: pa.RecordBatchReader, @@ -976,6 +977,9 @@ class Query: async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... + def execute_to_reader_sync( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -1021,6 +1025,9 @@ class FTSQuery: async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... + def execute_to_reader_sync( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -1033,6 +1040,9 @@ class VectorQuery: async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... + def execute_to_reader_sync( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... def where(self, filter: str): ... def where_expr(self, expr: PyExpr): ... def select(self, columns: List[Tuple[str, str]]): ... diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 6d3cf818b..19e9051f7 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -4033,6 +4033,26 @@ class AsyncQueryBase(object): self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys()) self._inner.with_row_id() + def _maybe_add_blob_row_id_sync(self) -> None: + if self._table is None: + self._blob_auto_row_id = False + self._blob_paths = () + return + + req = self._inner.to_query_request() + schema = self._table._schema_sync() + projection = _query_request_projection(req) + self._blob_auto_row_id = blob_auto_row_id_for_scan( + schema, + projection, + with_row_id=self._with_row_id, + ) + if not self._blob_auto_row_id: + self._blob_paths = () + return + self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys()) + self._inner.with_row_id() + async def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool: if blob_mode != "bytes" or self._table is None: return False @@ -4220,6 +4240,18 @@ class AsyncQueryBase(object): reader = await self._inner.execute_to_reader(None, timeout) return pa.Table.from_batches(reader, schema=reader.schema) + def _execute_eager_sync( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + """Execute with the synchronous native eager collector.""" + self._ensure_fragment_constraints_supported("to_arrow()") + if not self._blob_row_id_prepared: + self._maybe_add_blob_row_id_sync() + reader = self._inner.execute_to_reader_sync(None, timeout) + return pa.Table.from_batches(reader, schema=reader.schema) + async def _execute_batches( self, *, @@ -5118,6 +5150,22 @@ class AsyncFTSQuery(AsyncStandardQuery): results = _merge_query_snapshot(results, source) return results + def _execute_eager_sync( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + try: + results = super()._execute_eager_sync(timeout=timeout) + except Exception as error: + _add_fts_position_error_note(error) + raise + if self._reranker: + source = results + results = self._reranker.rerank_fts(self.get_query(), results) + results = _merge_query_snapshot(results, source) + return results + async def _execute_batches( self, *, @@ -5480,6 +5528,18 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): results = _merge_query_snapshot(results, source) return results + def _execute_eager_sync( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + results = super()._execute_eager_sync(timeout=timeout) + if self._reranker: + source = results + results = self._reranker.rerank_vector(self._query_string, results) + results = _merge_query_snapshot(results, source) + return results + async def _execute_batches( self, *, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 52ae6b9fd..fdcea6aa8 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -4533,7 +4533,10 @@ class LanceTable(Table): ------- pa.Schema A PyArrow schema object.""" - return LOOP.run(self._table.schema()) + schema_sync = getattr(self._table, "_schema_sync", None) + if schema_sync is None: + return LOOP.run(self._table.schema()) + return schema_sync() def list_versions(self) -> List[Dict[str, Any]]: """List all versions of the table""" @@ -6060,6 +6063,13 @@ class LanceTable(Table): async_query = self._table._sync_query_to_async(query) async_query._blob_row_id_prepared = query._blob_row_id_prepared + if ( + self._table._inner._is_native() + and self._namespace_client is None + and not self._route_pushdown_to_rust + and isinstance(async_query, (AsyncQuery, AsyncVectorQuery, AsyncFTSQuery)) + ): + return async_query._execute_eager_sync(timeout=timeout) return LOOP.run(async_query._execute_eager(timeout=timeout)) def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: @@ -7430,6 +7440,9 @@ class AsyncTable: """ return _restore_blob_extensions(await self._inner.schema()) + def _schema_sync(self) -> pa.Schema: + return _restore_blob_extensions(self._inner.schema_sync()) + async def embedding_functions(self) -> Dict[str, EmbeddingFunctionConfig]: """ Get the embedding functions for the table diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index ec747bd40..c01b3f9dc 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -2676,14 +2676,14 @@ def test_sync_query_prepares_schema_once_per_execution(tmp_path, monkeypatch): ) calls = 0 - original = AsyncTable.schema + original = AsyncTable._schema_sync - async def counted(self): + def counted(self): nonlocal calls calls += 1 - return await original(self) + return original(self) - monkeypatch.setattr(AsyncTable, "schema", counted) + monkeypatch.setattr(AsyncTable, "_schema_sync", counted) table.search().where("id = 1").select(["id"]).to_arrow() assert calls <= 1 diff --git a/python/python/tests/test_sync_query_direct.py b/python/python/tests/test_sync_query_direct.py new file mode 100644 index 000000000..9863f66c4 --- /dev/null +++ b/python/python/tests/test_sync_query_direct.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import signal +import os +import subprocess +import sys +import threading +from datetime import timedelta + +import pyarrow as pa +import pytest + +import lancedb +from lancedb import background_loop +from lancedb.index import BTree, FTS, IvfFlat + + +def _direct_query_table(tmp_path): + table = lancedb.connect(tmp_path).create_table( + "direct", + pa.table( + { + "id": pa.array([1, 2, 3, 4], pa.int64()), + "text": ["alpha beta", "alpha gamma", "beta gamma", "delta epsilon"], + "vector": pa.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + pa.list_(pa.float32(), 4), + ), + } + ), + ) + table.create_index("id", config=BTree()) + table.create_index("vector", config=IvfFlat(distance_type="l2", num_partitions=1)) + table.create_index("text", config=FTS(with_position=True)) + return table + + +def test_direct_sync_queries_do_not_use_background_loop(tmp_path, monkeypatch): + table = _direct_query_table(tmp_path) + expected_empty_schema = table.search().where("id < 0").output_schema() + + def fail(*_args, **_kwargs): + raise AssertionError("LOOP.run must not be used by direct sync queries") + + monkeypatch.setattr(background_loop.LOOP, "run", fail) + + point = table.search().where("id = 1").select(["id", "text"]).to_arrow() + assert point.to_pylist() == [{"id": 1, "text": "alpha beta"}] + + with_row_id = ( + table.search().where("id = 1").select(["id"]).with_row_id(True).to_arrow() + ) + assert with_row_id["_rowid"].to_pylist() == [0] + + # The vector column is inferred from the sync schema binding. + vector = table.search([0.9, 0.1, 0.0, 0.0]).limit(2).to_arrow() + assert vector["id"].to_pylist() == [1, 2] + assert "_distance" in vector.column_names + + fts = table.search("alpha", query_type="fts").select(["id"]).to_arrow() + assert sorted(fts["id"].to_pylist()) == [1, 2] + assert "_score" in fts.column_names + + phrase = table.search('"alpha beta"', query_type="fts").select(["id"]).to_arrow() + assert phrase["id"].to_pylist() == [1] + + empty = table.search().where("id < 0").to_arrow() + assert empty.num_rows == 0 + assert empty.schema == expected_empty_schema + + with pytest.raises(Exception, match="Query timeout"): + table.search([1.0, 0.0, 0.0, 0.0]).to_arrow(timeout=timedelta(0)) + + +@pytest.mark.skipif(sys.platform != "linux", reason="needs sched_setaffinity") +def test_direct_sync_query_from_single_worker_progress_callback(tmp_path): + script = r""" +import os +import sys + +try: + cpus = sorted(os.sched_getaffinity(0)) + if not cpus: + print("SKIP") + sys.exit(0) + os.sched_setaffinity(0, {cpus[0]}) +except OSError: + print("SKIP") + sys.exit(0) + +import lancedb + +db = lancedb.connect("memory:///") +target = db.create_table( + "target", + [{"id": 1, "value": "one"}, {"id": 2, "value": "two"}], +) +source = db.create_table("source", [{"id": 1}]) +seen = [] + +def progress(_update): + if not seen: + seen.append( + target.search() + .where("id = 1") + .select(["value"]) + .to_arrow() + .to_pylist() + ) + +source.add([{"id": 2}], progress=progress) +assert seen == [[{"value": "one"}]], seen +print("OK") +""" + result = subprocess.run( + [sys.executable, "-c", script], + cwd=tmp_path, + capture_output=True, + text=True, + timeout=30, + ) + if "SKIP" in result.stdout: + pytest.skip("sched_setaffinity did not leave a usable CPU") + assert result.returncode == 0, result.stdout + result.stderr + assert "OK" in result.stdout + + +@pytest.mark.slow +def test_direct_sync_query_sigint_aborts_and_reuses_runtime(tmp_path): + rows = 500_000 + table = lancedb.connect(tmp_path).create_table( + "sigint", + pa.table( + { + "id": pa.array(range(rows), pa.int64()), + "text": pa.array([f"row-{row}" for row in range(rows)]), + } + ), + ) + # Warm the runtime and page cache so the timed call is long enough to observe. + table.search().select(["id"]).to_arrow() + + timer = threading.Timer(0.001, os.kill, args=(os.getpid(), signal.SIGINT)) + timer.start() + try: + with pytest.raises(KeyboardInterrupt): + table.search().select(["id", "text"]).to_arrow() + finally: + timer.cancel() + timer.join() + + # The shared runtime and its generation counter remain usable. + after = table.search().where("id = 1").select(["id", "text"]).to_arrow() + assert after.to_pylist() == [{"id": 1, "text": "row-1"}] diff --git a/python/src/arrow.rs b/python/src/arrow.rs index 0384f2b2a..a4de3a911 100644 --- a/python/src/arrow.rs +++ b/python/src/arrow.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use std::time::Duration; use crate::error::PythonErrorExt; -use crate::runtime::future_into_py; +use crate::runtime::{block_on_interruptible, future_into_py}; use arrow::{ datatypes::SchemaRef, pyarrow::{IntoPyArrow, ToPyArrow}, @@ -89,18 +89,45 @@ where Q: ExecutableQuery + Send + 'static, { future_into_py(py, async move { - let mut options = QueryExecutionOptions::default(); - // `None` means the caller wants one eager result, not the core's - // default batch size. An explicit value is still honored. - options.max_batch_length = max_batch_length.unwrap_or(0); - options.timeout = timeout; - let stream = query.execute_with_options(options).await.infer_error()?; - let schema = stream.schema(); - let batches = stream.try_collect::>().await.infer_error()?; - let reader: Box = Box::new(RecordBatchIterator::new( - batches.into_iter().map(Ok), - schema, - )); + let reader = collect_to_reader(query, max_batch_length, timeout).await?; Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) }) } + +/// Synchronous counterpart of [`execute_to_reader`]. +/// +/// The returned reader owns the collected batches; the caller converts it to +/// Python after reattaching to the interpreter. The wait releases the GIL and +/// keeps Python signal handlers on the calling thread. +pub fn execute_to_reader_sync( + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + block_on_interruptible(collect_to_reader(query, max_batch_length, timeout)) +} + +async fn collect_to_reader( + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + let mut options = QueryExecutionOptions::default(); + // `None` means the caller wants one eager result, not the core's + // default batch size. An explicit value is still honored. + options.max_batch_length = max_batch_length.unwrap_or(0); + options.timeout = timeout; + let stream = query.execute_with_options(options).await.infer_error()?; + let schema = stream.schema(); + let batches = stream.try_collect::>().await.infer_error()?; + Ok(Box::new(RecordBatchIterator::new( + batches.into_iter().map(Ok), + schema, + ))) +} diff --git a/python/src/query.rs b/python/src/query.rs index 2c1a606eb..7a7e34416 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -33,6 +33,7 @@ use lancedb::query::{HasQuery, QueryBase}; use lancedb::table::AnyQuery; use pyo3::Bound; use pyo3::IntoPyObject; +use pyo3::Py; use pyo3::PyAny; use pyo3::PyRef; use pyo3::PyResult; @@ -65,6 +66,20 @@ fn analyze_plan_options(distributed_metrics: Option<&str>) -> PyResult( + py: Python<'_>, + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + let reader = + py.detach(move || crate::arrow::execute_to_reader_sync(query, max_batch_length, timeout))?; + Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) +} + impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { type Error = PyErr; @@ -713,6 +728,15 @@ impl Query { crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) } + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader_sync( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -966,6 +990,23 @@ impl FTSQuery { ) } + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader_sync( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + execute_to_reader_sync( + self_.py(), + self_ + .inner + .clone() + .full_text_search(self_.fts_query.clone()), + max_batch_length, + timeout, + ) + } + pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult> { let mut inner = self_ .inner @@ -1219,6 +1260,15 @@ impl VectorQuery { crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) } + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader_sync( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { diff --git a/python/src/runtime.rs b/python/src/runtime.rs index 85d536939..436b0d40b 100644 --- a/python/src/runtime.rs +++ b/python/src/runtime.rs @@ -93,15 +93,19 @@ //! `Arc` clone from becoming the final owner that drops it. use std::future::Future; +use std::panic::{AssertUnwindSafe, catch_unwind}; use std::pin::Pin; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::mpsc::{self, RecvTimeoutError}; use std::time::{Duration, Instant}; use arc_swap::ArcSwapOption; -use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject}; +use futures::FutureExt; +use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject, exceptions::PyRuntimeError}; use pyo3_async_runtimes::{ TaskLocals, + err::RustPanic, generic::{ContextExt, JoinError, Runtime}, }; use tokio::{runtime, task}; @@ -282,6 +286,111 @@ pub fn block_on(fut: F) -> F::Output { get_runtime().block_on(fut) } +/// How often an interruptible wait returns to the Python caller for signal checks. +const SIGNAL_CHECK_INTERVAL: Duration = Duration::from_millis(25); + +/// Block on `fut` while keeping the Python caller responsive to signals. +/// +/// The query task lives on the shared runtime and carries an [`OutstandingGuard`]. +/// The caller waits on the result channel without holding the GIL and periodically +/// reacquires it to run CPython's signal handlers on the same thread. A signal +/// exception aborts the task and drops the result receiver. +/// +/// A synchronous callback already running on a multi-threaded Tokio worker uses +/// [`tokio::task::block_in_place`] so the core can be handed off while the callback +/// waits. Current-thread runtimes and contexts that reject blocking are returned as +/// Python errors instead of falling back to the Python event loop. +pub fn block_on_interruptible(fut: F) -> PyResult +where + F: Future> + Send + 'static, + T: Send + 'static, +{ + block_on_interruptible_with(fut, || Python::attach(|py| py.check_signals())) +} + +fn block_on_interruptible_with(fut: F, check: C) -> PyResult +where + F: Future> + Send + 'static, + T: Send + 'static, + C: FnMut() -> PyResult<()>, +{ + match runtime::Handle::try_current() { + Ok(handle) => match handle.runtime_flavor() { + runtime::RuntimeFlavor::MultiThread => { + let result = catch_unwind(AssertUnwindSafe(|| { + task::block_in_place(|| block_on_interruptible_inner(fut, check)) + })); + match result { + Ok(result) => result, + Err(payload) => Err(PyRuntimeError::new_err(format!( + "synchronous query cannot block in this Tokio context: {}", + panic_message(payload.as_ref()) + ))), + } + } + _ => Err(PyRuntimeError::new_err( + "synchronous query execution cannot block on a current-thread Tokio runtime; use the async API", + )), + }, + Err(_) => block_on_interruptible_inner(fut, check), + } +} + +fn block_on_interruptible_inner(fut: F, mut check: C) -> PyResult +where + F: Future> + Send + 'static, + T: Send + 'static, + C: FnMut() -> PyResult<()>, +{ + let guard = OutstandingGuard::new(); + let (tx, rx) = mpsc::sync_channel(1); + let task = async move { + let _guard = guard; + let result = AssertUnwindSafe(fut).catch_unwind().await; + // Dropping a completed result is enough when the caller has already + // returned on an interrupt; the task's guard is dropped with it. + let _ = tx.send(result); + }; + let handle = get_runtime().spawn(task); + + loop { + match rx.recv_timeout(SIGNAL_CHECK_INTERVAL) { + Ok(Ok(result)) => { + check()?; + return result; + } + Ok(Err(payload)) => { + check()?; + return Err(RustPanic::new_err(format!( + "rust future panicked: {}", + panic_message(payload.as_ref()) + ))); + } + Err(RecvTimeoutError::Timeout) => { + if let Err(error) = check() { + handle.abort(); + return Err(error); + } + } + Err(RecvTimeoutError::Disconnected) => { + return Err(PyRuntimeError::new_err( + "query task stopped before producing a result", + )); + } + } + } +} + +fn panic_message(payload: &(dyn std::any::Any + Send)) -> &str { + if let Some(message) = payload.downcast_ref::<&str>() { + message + } else if let Some(message) = payload.downcast_ref::() { + message.as_str() + } else { + "unknown error" + } +} + /// Run a detached task, including when the caller is already on a runtime worker. /// Keep it visible to [`shutdown`] until it finishes. pub fn spawn_background(fut: F) @@ -571,6 +680,95 @@ mod tests { shutdown(Duration::from_secs(5)); } + #[test] + fn test_block_on_interruptible_aborts_and_drops_future() { + use std::sync::mpsc; + + Python::initialize(); + let _lock = lock_runtime_state_for_test(); + let (started_tx, started_rx) = mpsc::channel(); + let (dropped_tx, dropped_rx) = mpsc::channel(); + + struct DropNotify(Option>); + impl Drop for DropNotify { + fn drop(&mut self) { + if let Some(tx) = self.0.take() { + let _ = tx.send(()); + } + } + } + + let fut = async move { + started_tx.send(()).unwrap(); + let _notify = DropNotify(Some(dropped_tx)); + std::future::pending::<()>().await; + #[allow(unreachable_code)] + Ok::<(), pyo3::PyErr>(()) + }; + let result = block_on_interruptible_with(fut, || { + Err(pyo3::exceptions::PyRuntimeError::new_err("interrupted")) + }); + + assert!(result.is_err()); + started_rx + .recv_timeout(Duration::from_secs(2)) + .expect("query task never started"); + dropped_rx + .recv_timeout(Duration::from_secs(2)) + .expect("interrupted query future was not dropped"); + shutdown(Duration::from_secs(5)); + } + + #[test] + fn test_block_on_interruptible_maps_panic() { + Python::initialize(); + let result = block_on_interruptible(async { + panic!("boom"); + #[allow(unreachable_code)] + Ok::<(), pyo3::PyErr>(()) + }); + assert!( + result + .expect_err("panic must become a Python exception") + .to_string() + .contains("rust future panicked: boom") + ); + } + + #[test] + fn test_block_on_interruptible_rejects_current_thread_runtime() { + Python::initialize(); + let runtime = runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("current-thread runtime"); + let error = runtime + .block_on(async { block_on_interruptible(async { Ok::<_, pyo3::PyErr>(1) }) }) + .expect_err("current-thread runtime must be rejected"); + assert!(error.to_string().contains("current-thread")); + } + + #[cfg(target_os = "linux")] + #[test] + fn test_block_on_interruptible_from_single_worker_runtime() { + Python::initialize(); + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(1); + shutdown(Duration::from_secs(5)); + + let (done_tx, done_rx) = mpsc::channel(); + drop(get_runtime().spawn(async move { + let result = block_on_interruptible(async { Ok::<_, pyo3::PyErr>(42) }); + let _ = done_tx.send(result.map_err(|error| error.to_string())); + })); + + let result = done_rx + .recv_timeout(Duration::from_secs(10)) + .expect("single-worker runtime made no progress"); + assert_eq!(result.expect("single-worker query failed"), 42); + shutdown(Duration::from_secs(5)); + } + // Adapted from the concurrent reproducer that found the original bug: // many threads hammering the runtime while shutdown races them, not // just the sequential rebuild path above. Before every reader held its diff --git a/python/src/table.rs b/python/src/table.rs index a4611d80c..f9c81d5a3 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -9,7 +9,7 @@ use std::{ }, }; -use crate::runtime::{block_on, future_into_py, spawn_background}; +use crate::runtime::{block_on, block_on_interruptible, future_into_py, spawn_background}; use crate::{ connection::Connection, error::PythonErrorExt, @@ -1619,6 +1619,14 @@ impl Table { }) } + pub fn schema_sync(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let schema = self_.py().detach(move || { + block_on_interruptible(async move { inner.schema().await.infer_error() }) + })?; + Python::attach(|py| schema.to_pyarrow(py).map(|obj| obj.unbind())) + } + #[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false, retries=None))] pub fn add<'a>( self_: PyRef<'a, Self>, From 74239973c70e76d58f399c24e22951087dd786cd Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Fri, 20 Nov 2026 12:47:31 -0800 Subject: [PATCH 53/78] docs: describe current Function refresh defaults (#5134) Several Function pages still said a refresh defaults to `error_policy = 'fail'` and that `skip` writes null outputs. The server now defaults new refreshes to skip with a 5% failed-row ceiling, and skip keeps a row's existing output, leaving only never-filled rows empty. This updates those pages to match. --- docs/web/feature-engineering/index.mdx | 8 ++++--- .../feature-engineering/refresh-column.mdx | 5 ++-- docs/web/management/function-failures.mdx | 23 +++++++++---------- docs/web/management/function.mdx | 12 ++++++---- docs/web/sql/dml/refresh-column.mdx | 2 +- 5 files changed, 27 insertions(+), 23 deletions(-) diff --git a/docs/web/feature-engineering/index.mdx b/docs/web/feature-engineering/index.mdx index 405f4e852..94c5d6f70 100644 --- a/docs/web/feature-engineering/index.mdx +++ b/docs/web/feature-engineering/index.mdx @@ -121,9 +121,11 @@ That is also why a function must declare the environment it needs. ## Recovering from a failure {#failures} -A function that raises fails the job. There is no per-row retry or skip policy -in the function definition, so a function calling a flaky external service -should handle that itself, inside the function body. +By default, a refresh skips rows where the function raises and records their +errors, up to a 5% failed-row ceiling; see +[Handle Function failures](/management/function-failures). A function can also +declare a retry policy for transient errors with `@function(retry_policy=...)` +where the SDK, server and Function image support it. When a refresh fails, fix the cause and run the refresh again. The new refresh fills what is still empty or stale. How much of the diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index f893118fc..de0b56888 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -536,8 +536,9 @@ refresh value overrides that default for this execution only. `batch_size` caps rows in one Function call; LanceDB adapts actual call and work sizes. For Function columns, the refresh defaults to -`error_policy = 'fail'`. Set `error_policy = 'skip'` to write null outputs for -failing rows and record them in the error store, subject to failure limits. +`error_policy = 'skip'` with a 5% failed-row ceiling: failing rows keep any +existing output, unassigned outputs stay unassigned, and their errors are +recorded in the error store. Set `error_policy = 'fail'` to stop on a row error. See the [SQL refresh options](/sql/dml/refresh-column#options). {/* diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx index 226d8b573..76fbc0371 100644 --- a/docs/web/management/function-failures.mdx +++ b/docs/web/management/function-failures.mdx @@ -11,18 +11,16 @@ availability: A Function refresh can encounter a bad row, fail to initialize a model, lose a worker, or fail while publishing results. These need different remedies. -The native workflow below is draft guidance for an unreleased SDK and a -matching Enterprise server. The recipes that follow it remain available for -older deployments. +The native workflow below needs a recent SDK and a matching Enterprise server. +The recipes that follow it remain available for older deployments. -## Draft native workflow: server contract version 1 {#native} +## Native workflow: server contract version 1 {#native} -This section requires the SDK changes in [PR #5048](https://github.com/lancedb/lancedb/pull/5048) -and an Enterprise deployment advertising `workflow_version >= 1` in its -Function error response. No released SDK or Enterprise version is implied by -this draft. The SDK checks this capability before submitting native retry, -upgrade, quarantine, history or provenance requests, and rejects unsupported -servers before changing the column. +This section requires Python SDK 0.42.0b19 or later and an Enterprise +deployment advertising `workflow_version >= 1` in its Function error response. +The SDK checks this capability before submitting native retry, upgrade, +quarantine, history or provenance requests, and rejects unsupported servers +before changing the column. New Function refreshes default to `error_policy="skip"` with a 5% failed-row ceiling. Successful outputs are published before a threshold failure is @@ -145,8 +143,9 @@ remain unchanged. ## Choose a row-error policy {#policy} -The default `fail` stops the job on a row error. `skip` writes null outputs for -failed rows and records errors, subject to the refresh's failure limits: +On these deployments, the default `fail` stops the job on a row error. `skip` +retains a failed row's existing output, leaves an unassigned output unassigned +and records errors, subject to the refresh's failure limits: ```python job = table.refresh_column_async( diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index bc237d79e..4de54e78a 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -696,23 +696,25 @@ full worked example. For the full skip, inspect, grouped-error, stable-row-ID retry and quarantine workflow, see [Handle Function failures](/management/function-failures). -By default, a Function that raises fails the refresh job. Choose how the -refresh handles row errors with its error policy: +By default, a refresh skips rows where the Function raises, up to a 5% +failed-row ceiling. Choose how the refresh handles row errors with its error +policy: ```sql SQL icon="database" -REFRESH COLUMN embedding ON documents WITH (error_policy = 'skip') +REFRESH COLUMN embedding ON documents WITH (error_policy = 'fail') ``` -`skip` writes null outputs for failing rows and records their errors. Inspect +`skip` retains a failing row's existing output, leaves an unassigned output +unassigned and records the error. Inspect them with `SHOW ERRORS` or `table.function_errors()`. Failure limits still apply, and initialization or infrastructure failures can still fail the job. See the [SQL refresh options](/sql/dml/refresh-column#options). A Function that calls a transiently failing external service can handle bounded retries inside its body. -Letting the job fail is the other option: fix the cause and refresh again. The +`fail` is the opt-in alternative: fix the cause and refresh again. The next unfiltered refresh [skips rows that are filled and current](/feature-engineering/refresh-column#idempotent), but how much of the failed job's work was kept is not guaranteed, so do not count on the retry costing only the rows that did not complete. A refresh with diff --git a/docs/web/sql/dml/refresh-column.mdx b/docs/web/sql/dml/refresh-column.mdx index fcb78bd35..e680823ef 100644 --- a/docs/web/sql/dml/refresh-column.mdx +++ b/docs/web/sql/dml/refresh-column.mdx @@ -59,7 +59,7 @@ to let LanceDB track which outputs need updating. | `batch_size` | maximum rows passed to one Function call; actual calls can be smaller. Function columns only | | `max_executor_processes_per_worker` | cap on executor processes per worker. Function columns only | | `row_timeout_seconds` | deadline for one Function call. Function columns only | -| `error_policy` | `'fail'` (default) stops on a row error; `'skip'` writes null outputs and records row errors, subject to failure limits. Function columns only | +| `error_policy` | `'skip'` (default, with a 5% failed-row ceiling) retains a failing row's existing output, leaves unassigned outputs unassigned and records row errors, subject to failure limits; `'fail'` stops on a row error. Function columns only | | `max_failed_fraction` | fail the job once more than this share of rows has failed. Function columns only | | `max_failed_rows` | fail the job once more than this many rows has failed. Function columns only | From 668fb1e2569f8206f418fbc12adad8cef8dea70a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 04:59:34 +0800 Subject: [PATCH 54/78] feat(python): add tag-based branch creation and default tag versions (#5136) Python `tags.create()` now defaults `version` to the handle's currently visible version, including checked-out handles. Existing `from_ref` / `from_version` branch selection and explicit tag versions keep their current behavior. `branches.create()` gains keyword-only `from_tag`, so a branch can fork from a tag through the existing `Ref::Tag` path. This preserves the tag's actual branch snapshot; resolving only its numeric version could fork from `main` when both branches share a version number. `from_tag` conflicts with `from_ref` / `from_version` are rejected before `from_ref="main"` normalization. When `from_ref` names a tag instead of a branch, the native missing-branch failure keeps its classification and receives a static `from_tag=` hint without another lookup. A missing version and an ambiguous Enterprise 404 keep their original errors. The Python sync and async APIs, PyO3 binding, stubs and docstrings are updated together, with native Rust coverage for a tag on a branch that shares main's numeric version. Node.js `fromTag` and optional `version` will follow in a separate PR after this one. --- docs/web-tests/py/test_tables.py | 16 ++- docs/web-tests/rs/tables.rs | 20 +++- docs/web/management/table.mdx | 5 + docs/web/snippets/tables.mdx | 6 +- docs/web/tables/branching.mdx | 8 +- python/python/lancedb/_lancedb.pyi | 4 +- python/python/lancedb/table.py | 55 ++++++++-- python/python/tests/test_table.py | 167 +++++++++++++++++++++++++++++ python/src/table.rs | 70 ++++++++++-- rust/lancedb/src/table.rs | 54 ++++++++++ 10 files changed, 382 insertions(+), 23 deletions(-) diff --git a/docs/web-tests/py/test_tables.py b/docs/web-tests/py/test_tables.py index 93c3729f7..465e6de47 100644 --- a/docs/web-tests/py/test_tables.py +++ b/docs/web-tests/py/test_tables.py @@ -1328,7 +1328,8 @@ def test_versioning_tags(tmp_db): # --8<-- [start:versioning_tags] # Create a tag pointing at a specific version table.tags.create("baseline", 1) - table.tags.create("with-edits", table.version) + # Omit version to tag the version this handle currently shows. + table.tags.create("with-edits") # List all tags on this table print(table.tags.list()) @@ -1343,6 +1344,9 @@ def test_versioning_tags(tmp_db): table.checkout("baseline") print(table.version) + # A checked-out handle tags the older version it shows, not the latest. + table.tags.create("baseline-checkout") + # Delete a tag (does not delete the underlying version) table.tags.delete("with-edits") @@ -1350,6 +1354,7 @@ def test_versioning_tags(tmp_db): table.checkout_latest() # --8<-- [end:versioning_tags] assert table.version == 3 + assert table.tags.get_version("baseline-checkout") == 2 assert "baseline" in table.tags.list() assert "with-edits" not in table.tags.list() @@ -1387,8 +1392,15 @@ def test_branches(tmp_db): # Fork an isolated, writable branch from main's latest version. # `create` returns a table handle scoped to the new branch. branch = table.branches.create("exp") + + # Fork from a tag. `from_tag` is keyword-only and cannot be combined with + # `from_ref` or `from_version`. + table.tags.create("baseline", 1) + tag_branch = table.branches.create("exp-from-tag", from_tag="baseline") # --8<-- [end:branch_create] + assert tag_branch.count_rows() == 3 + # --8<-- [start:branch_write] # Writes land on the branch handle only; main is left untouched. branch.add([{"id": 4, "author": "Lancelot", "quote": "For the realm!"}]) @@ -1414,6 +1426,8 @@ def test_branches(tmp_db): assert table.count_rows() == 3 assert "exp" not in table.branches.list() + assert "exp-from-tag" in table.branches.list() + table.branches.delete("exp-from-tag") # Setup: a branch with row results that we want to apply to main. candidate = table.branches.create("candidate") diff --git a/docs/web-tests/rs/tables.rs b/docs/web-tests/rs/tables.rs index 0d568530d..e5a8295df 100644 --- a/docs/web-tests/rs/tables.rs +++ b/docs/web-tests/rs/tables.rs @@ -1379,17 +1379,27 @@ async fn main() { .await .unwrap(); + // --8<-- [start:branch_create] use lancedb::table::Ref; - // --8<-- [start:branch_create] // Fork an isolated, writable branch from main's latest version. // `create_branch` returns a table handle scoped to the new branch. let branch = branches_table .create_branch("exp", Ref::Version(None, None)) .await .unwrap(); + + // Fork from a tag. A tag keeps its branch and version. + let mut tags = branches_table.tags().await.unwrap(); + tags.create("baseline", 1).await.unwrap(); + let tag_branch = branches_table + .create_branch("exp-from-tag", Ref::Tag("baseline".to_string())) + .await + .unwrap(); // --8<-- [end:branch_create] + assert_eq!(tag_branch.count_rows(None).await.unwrap(), 3); + // --8<-- [start:branch_write] // Writes land on the branch handle only; main is left untouched. branch @@ -1428,6 +1438,14 @@ async fn main() { assert_eq!(branches_table.count_rows(None).await.unwrap(), 3); assert!(!branches_table.list_branches().await.unwrap().contains_key("exp")); + assert!( + branches_table + .list_branches() + .await + .unwrap() + .contains_key("exp-from-tag") + ); + branches_table.delete_branch("exp-from-tag").await.unwrap(); // Setup: a branch with row results that we want to apply to main. let candidate = branches_table diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index c5dc4f8cd..14c1a9fc2 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -1742,6 +1742,11 @@ page). The tags API supports the standard CRUD operations (create, list, update, delete), plus checking out by tag name. +In Python, `tags.create()` accepts an optional `version`. If you omit it, the +tag uses the version the table handle currently shows. That includes a handle +checked out to an older version, so pass `version` explicitly when the tag must +not depend on the handle's checkout state. + {VersioningTags} diff --git a/docs/web/snippets/tables.mdx b/docs/web/snippets/tables.mdx index f4b0a1af8..ecbdc71c9 100644 --- a/docs/web/snippets/tables.mdx +++ b/docs/web/snippets/tables.mdx @@ -30,7 +30,7 @@ export const PyAlterVectorColumn = "data = [\n {\n \"id\": 1,\n export const PyBatchDataInsertion = "import pyarrow as pa\n\ndef make_batches():\n for i in range(5): # Create 5 batches\n yield pa.RecordBatch.from_arrays(\n [\n pa.array([[3.1, 4.1], [5.9, 26.5]], pa.list_(pa.float32(), 2)),\n pa.array([f\"item{i * 2 + 1}\", f\"item{i * 2 + 2}\"]),\n pa.array([float((i * 2 + 1) * 10), float((i * 2 + 2) * 10)]),\n ],\n [\"vector\", \"item\", \"price\"],\n )\n\nschema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float32(), 2)),\n pa.field(\"item\", pa.utf8()),\n pa.field(\"price\", pa.float32()),\n ]\n)\n# Create table with batches\ntable_name = \"batch_ingestion_example\"\ntable = db.create_table(table_name, make_batches(), schema=schema, mode=\"overwrite\")\n"; -export const PyBranchCreate = "# Fork an isolated, writable branch from main's latest version.\n# `create` returns a table handle scoped to the new branch.\nbranch = table.branches.create(\"exp\")\n"; +export const PyBranchCreate = "# Fork an isolated, writable branch from main's latest version.\n# `create` returns a table handle scoped to the new branch.\nbranch = table.branches.create(\"exp\")\n\n# Fork from a tag. `from_tag` is keyword-only and cannot be combined with\n# `from_ref` or `from_version`.\ntable.tags.create(\"baseline\", 1)\ntag_branch = table.branches.create(\"exp-from-tag\", from_tag=\"baseline\")\n"; export const PyBranchDelete = "# Delete the branch and its branch-local history. Data on main is safe.\ntable.branches.delete(\"exp\")\n"; @@ -136,7 +136,7 @@ export const PyVersioningListAllVersions = "versions = table.list_versions()\nfo export const PyVersioningRollback = "table.restore(version_after_mod)\nversions = table.list_versions()\nversion_count_after_rollback = len(versions)\nprint(f\"Total number of versions after rollback: {version_count_after_rollback}\")\n"; -export const PyVersioningTags = "# Create a tag pointing at a specific version\ntable.tags.create(\"baseline\", 1)\ntable.tags.create(\"with-edits\", table.version)\n\n# List all tags on this table\nprint(table.tags.list())\n\n# Look up the version a tag points at\nprint(table.tags.get_version(\"baseline\"))\n\n# Move an existing tag to a different version\ntable.tags.update(\"baseline\", 2)\n\n# Check out a version by tag name\ntable.checkout(\"baseline\")\nprint(table.version)\n\n# Delete a tag (does not delete the underlying version)\ntable.tags.delete(\"with-edits\")\n\n# Return to the latest version\ntable.checkout_latest()\n"; +export const PyVersioningTags = "# Create a tag pointing at a specific version\ntable.tags.create(\"baseline\", 1)\n# Omit version to tag the version this handle currently shows.\ntable.tags.create(\"with-edits\")\n\n# List all tags on this table\nprint(table.tags.list())\n\n# Look up the version a tag points at\nprint(table.tags.get_version(\"baseline\"))\n\n# Move an existing tag to a different version\ntable.tags.update(\"baseline\", 2)\n\n# Check out a version by tag name\ntable.checkout(\"baseline\")\nprint(table.version)\n\n# A checked-out handle tags the older version it shows, not the latest.\ntable.tags.create(\"baseline-checkout\")\n\n# Delete a tag (does not delete the underlying version)\ntable.tags.delete(\"with-edits\")\n\n# Return to the latest version\ntable.checkout_latest()\n"; export const PyVersioningUpdateData = "table.update(where=\"author='Richard'\", values={\"author\": \"Richard Daniel Sanchez\"})\nrows_after_update = table.count_rows(\"author = 'Richard Daniel Sanchez'\")\nprint(f\"Rows updated to Richard Daniel Sanchez: {rows_after_update}\")\n"; @@ -274,7 +274,7 @@ export const RsAlterColumnsWithExpression = "// For custom transforms, create a export const RsAlterVectorColumn = "let old_dim = 384;\nlet new_dim = 1024;\nlet vector_schema = Arc::new(Schema::new(vec![\n Field::new(\"id\", DataType::Int64, false),\n Field::new(\n \"embedding\",\n DataType::FixedSizeList(\n Arc::new(Field::new(\"item\", DataType::Float32, true)),\n old_dim,\n ),\n true,\n ),\n]));\nlet vector_batch = RecordBatch::try_new(\n vector_schema.clone(),\n vec![\n Arc::new(Int64Array::from(vec![1])),\n Arc::new(\n FixedSizeListArray::from_iter_primitive::(\n vec![Some(vec![Some(0.1_f32); old_dim as usize])],\n old_dim,\n ),\n ),\n ],\n)\n.unwrap();\nlet vector_reader: Box =\n Box::new(RecordBatchIterator::new(vec![Ok(vector_batch)].into_iter(), vector_schema.clone()));\nlet vector_table = db\n .create_table(\"vector_alter_example\", vector_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n\n// Changing FixedSizeList dimensions (384 -> 1024) is not supported via alter_columns.\n// Use add_columns + drop_columns + alter_columns(rename) to replace the column.\nvector_table\n .add_columns(\n NewColumnTransform::SqlExpressions(vec![(\n \"embedding_v2\".to_string(),\n format!(\"arrow_cast(NULL, 'FixedSizeList({}, Float32)')\", new_dim),\n )]),\n None,\n )\n .await\n .unwrap();\nvector_table.drop_columns(&[\"embedding\"]).await.unwrap();\nvector_table\n .alter_columns(&[ColumnAlteration::new(\"embedding_v2\".to_string())\n .rename(\"embedding\".to_string())])\n .await\n .unwrap();\n"; -export const RsBranchCreate = "// Fork an isolated, writable branch from main's latest version.\n// `create_branch` returns a table handle scoped to the new branch.\nlet branch = branches_table\n .create_branch(\"exp\", Ref::Version(None, None))\n .await\n .unwrap();\n"; +export const RsBranchCreate = "use lancedb::table::Ref;\n\n// Fork an isolated, writable branch from main's latest version.\n// `create_branch` returns a table handle scoped to the new branch.\nlet branch = branches_table\n .create_branch(\"exp\", Ref::Version(None, None))\n .await\n .unwrap();\n\n// Fork from a tag. A tag keeps its branch and version.\nlet mut tags = branches_table.tags().await.unwrap();\ntags.create(\"baseline\", 1).await.unwrap();\nlet tag_branch = branches_table\n .create_branch(\"exp-from-tag\", Ref::Tag(\"baseline\".to_string()))\n .await\n .unwrap();\n"; export const RsBranchDelete = "// Delete the branch and its branch-local history. Data on main is safe.\nbranches_table.delete_branch(\"exp\").await.unwrap();\n"; diff --git a/docs/web/tables/branching.mdx b/docs/web/tables/branching.mdx index baf46b265..9edd7c669 100644 --- a/docs/web/tables/branching.mdx +++ b/docs/web/tables/branching.mdx @@ -127,8 +127,12 @@ small `quotes` table with three rows on `main`. ### Create a branch {#create-a-branch} Forking from `main` returns a table handle scoped to the new branch. `main` is -the reserved default source, so `create` needs only a name; to fork from -somewhere else, pass a branch name, a specific version, or both. +the reserved default source, so `create` needs only a name. To fork from another +branch, pass `from_ref`, optionally with `from_version`. In Python, use +keyword-only `from_tag` to fork from a tag; it cannot be combined with +`from_ref` or `from_version`. In Rust, pass `Ref::Tag` to `create_branch`. A +tag carries its own branch and version, so the tag source forks from that exact +snapshot. diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index eb8536f3e..a3a9610c9 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -879,7 +879,7 @@ class Table: class Tags: async def list(self) -> Dict[str, Tag]: ... async def get_version(self, tag: str) -> int: ... - async def create(self, tag: str, version: int): ... + async def create(self, tag: str, version: Optional[int] = None): ... async def delete(self, tag: str): ... async def update(self, tag: str, version: int): ... @@ -890,6 +890,8 @@ class Branches: name: str, from_ref: Optional[str] = None, from_version: Optional[int] = None, + *, + from_tag: Optional[str] = None, ) -> Table: ... async def checkout(self, name: str, version: Optional[int] = None) -> Table: ... async def delete(self, name: str) -> None: ... diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index fdcea6aa8..a6ba1692e 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -10250,6 +10250,26 @@ class FragmentSummaryStats: p99: int +def _validate_branch_source( + from_ref: Optional[str], + from_version: Optional[int], + from_tag: Optional[str], +) -> None: + if from_tag is None: + return + conflicts = [ + name + for name, value in (("from_ref", from_ref), ("from_version", from_version)) + if value is not None + ] + if conflicts: + raise ValueError( + "from_tag cannot be combined with " + + " or ".join(conflicts) + + "; pass only one source" + ) + + class Tags: """ Table tag manager. @@ -10280,7 +10300,7 @@ class Tags: """ return LOOP.run(self._table.tags.get_version(tag)) - def create(self, tag: str, version: int) -> None: + def create(self, tag: str, version: Optional[int] = None) -> None: """ Create a tag for a given table version. @@ -10289,8 +10309,9 @@ class Tags: tag: str, The name of the tag to create. This name must be unique among all tag names for the table. - version: int, - The table version to tag. + version: int, optional + The table version to tag. Defaults to the version visible to this + handle, including a checked-out version. """ LOOP.run(self._table.tags.create(tag, version)) @@ -10337,6 +10358,8 @@ class Branches: name: str, from_ref: Optional[str] = None, from_version: Optional[int] = None, + *, + from_tag: Optional[str] = None, ) -> "Table": """Create a branch and return a handle scoped to it. @@ -10348,9 +10371,13 @@ class Branches: Source branch to fork from. Defaults to ``main``. from_version: int, optional A specific version on ``from_ref`` to fork from. Defaults to latest. + from_tag: str, optional + Source tag to fork from. Cannot be combined with ``from_ref`` or + ``from_version``. """ + _validate_branch_source(from_ref, from_version, from_tag) async_table = LOOP.run( - self._table.branches.create(name, from_ref, from_version) + self._table.branches.create(name, from_ref, from_version, from_tag=from_tag) ) return self._wrap(async_table) @@ -10432,7 +10459,7 @@ class AsyncTags: """ return await self._table.tags.get_version(tag) - async def create(self, tag: str, version: int) -> None: + async def create(self, tag: str, version: Optional[int] = None) -> None: """ Create a tag for a given table version. @@ -10441,8 +10468,9 @@ class AsyncTags: tag: str, The name of the tag to create. This name must be unique among all tag names for the table. - version: int, - The table version to tag. + version: int, optional + The table version to tag. Defaults to the version visible to this + handle, including a checked-out version. """ await self._table.tags.create(tag, version) @@ -10486,6 +10514,8 @@ class AsyncBranches: name: str, from_ref: Optional[str] = None, from_version: Optional[int] = None, + *, + from_tag: Optional[str] = None, ) -> "AsyncTable": """Create a branch and return a handle scoped to it. @@ -10497,12 +10527,19 @@ class AsyncBranches: Source branch to fork from. Defaults to ``main``. from_version: int, optional A specific version on ``from_ref`` to fork from. Defaults to latest. + from_tag: str, optional + Source tag to fork from. Cannot be combined with ``from_ref`` or + ``from_version``. """ + _validate_branch_source(from_ref, from_version, from_tag) # "main" and None are two spellings of the root branch in lance; normalize - # so from_ref="main" behaves identically to the default. + # so from_ref="main" behaves identically to the default. This must happen + # after validating from_tag conflicts so an explicit from_ref is not lost. if from_ref == "main": from_ref = None - inner = await self._table.branches.create(name, from_ref, from_version) + inner = await self._table.branches.create( + name, from_ref, from_version, from_tag=from_tag + ) return AsyncTable(inner) async def checkout(self, name: str, version: Optional[int] = None) -> "AsyncTable": diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index e999390a1..c9a587950 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1426,6 +1426,31 @@ def test_tags(mem_db: DBConnection): ) +def test_tags_create_defaults_to_visible_version(mem_db: DBConnection): + table = mem_db.create_table("test", data=[{"id": 1}]) + table.add(data=[{"id": 2}]) + + table.tags.create("live") + assert table.tags.get_version("live") == 2 + + table.checkout(1) + table.tags.create("pinned") + assert table.tags.get_version("pinned") == 1 + + # An explicit version is independent of the version this handle shows. + table.tags.create("explicit", 2) + assert table.tags.get_version("explicit") == 2 + + # A tag checkout is still a visible version, not "latest". + table.checkout_latest() + table.add(data=[{"id": 3}]) + assert table.version == 3 + table.checkout("live") + assert table.version == 2 + table.tags.create("tag-checkout") + assert table.tags.get_version("tag-checkout") == 2 + + @pytest.mark.asyncio async def test_async_tags(mem_db_async: AsyncConnection): table = await mem_db_async.create_table( @@ -1480,6 +1505,34 @@ async def test_async_tags(mem_db_async: AsyncConnection): ) +@pytest.mark.asyncio +async def test_async_tags_create_defaults_to_visible_version( + mem_db_async: AsyncConnection, +): + table = await mem_db_async.create_table("test", data=[{"id": 1}]) + await table.add(data=[{"id": 2}]) + + await table.tags.create("live") + assert await table.tags.get_version("live") == 2 + + await table.checkout(1) + await table.tags.create("pinned") + assert await table.tags.get_version("pinned") == 1 + + # An explicit version is independent of the version this handle shows. + await table.tags.create("explicit", 2) + assert await table.tags.get_version("explicit") == 2 + + # A tag checkout is still a visible version, not "latest". + await table.checkout_latest() + await table.add(data=[{"id": 3}]) + assert await table.version() == 3 + await table.checkout("live") + assert await table.version() == 2 + await table.tags.create("tag-checkout") + assert await table.tags.get_version("tag-checkout") == 2 + + def test_branches(tmp_path): db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0)) table = db.create_table( @@ -1519,6 +1572,62 @@ def test_branches(tmp_path): assert "exp" not in table.branches.list() +def test_branches_create_from_tag(tmp_path): + db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0)) + table = db.create_table("test", data=[{"i": 0}]) + + exp = table.branches.create("exp") + exp.add([{"i": 10}]) + exp_version = exp.version + exp.tags.create("exp-v2", exp_version) + + # main reaches the same numeric version with different rows. + table.add([{"i": 100}]) + assert table.version == exp_version + + forked = table.branches.create("from-tag", from_tag="exp-v2") + assert forked.current_branch() == "from-tag" + assert forked.count_rows("i = 10") == 1 + assert forked.count_rows("i = 100") == 0 + + +def test_branches_create_from_tag_rejects_other_sources(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("test", data=[{"i": 0}]) + table.tags.create("baseline") + + # from_ref="main" must be rejected before it is normalized to the default. + with pytest.raises(ValueError, match="from_tag cannot be combined"): + table.branches.create("exp", from_ref="main", from_tag="baseline") + with pytest.raises(ValueError, match="from_tag cannot be combined"): + table.branches.create("exp", from_version=1, from_tag="baseline") + + +def test_branches_create_from_missing_ref_hint_applies_only_to_branches(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("test", data=[{"i": 0}]) + base = table.branches.create("base") + base.add([{"i": 1}]) + table.tags.create("baseline") + + # A tag passed through from_ref is not a branch. Keep the original failure + # classification and add guidance without probing the ref a second time. + with pytest.raises(RuntimeError) as exc_info: + table.branches.create("exp", from_ref="baseline") + + detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ()))) + assert "from_tag='baseline'" in detail + + # An existing branch with an absent version is a version failure, not an + # unresolved branch, so it must not suggest from_tag. + with pytest.raises(RuntimeError) as exc_info: + table.branches.create("exp", from_ref="base", from_version=9999) + + detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ()))) + assert "9999" in detail + assert "from_tag=" not in detail + + def test_branch_handle_tracks_concurrent_writes(tmp_path): db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0)) table = db.create_table("t", [{"id": 1}]) @@ -1814,6 +1923,64 @@ async def test_async_branches(tmp_path): assert "exp" not in await table.branches.list() +@pytest.mark.asyncio +async def test_async_branches_create_from_tag(tmp_path): + db = await lancedb.connect_async(tmp_path, read_consistency_interval=timedelta(0)) + table = await db.create_table("test", data=[{"i": 0}]) + + exp = await table.branches.create("exp") + await exp.add([{"i": 10}]) + exp_version = await exp.version() + await exp.tags.create("exp-v2", exp_version) + + # main reaches the same numeric version with different rows. + await table.add([{"i": 100}]) + assert await table.version() == exp_version + + forked = await table.branches.create("from-tag", from_tag="exp-v2") + assert forked.current_branch() == "from-tag" + assert await forked.count_rows("i = 10") == 1 + assert await forked.count_rows("i = 100") == 0 + + +@pytest.mark.asyncio +async def test_async_branches_create_from_tag_rejects_other_sources(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("test", data=[{"i": 0}]) + await table.tags.create("baseline") + + with pytest.raises(ValueError, match="from_tag cannot be combined"): + await table.branches.create("exp", from_ref="main", from_tag="baseline") + with pytest.raises(ValueError, match="from_tag cannot be combined"): + await table.branches.create("exp", from_version=1, from_tag="baseline") + + +@pytest.mark.asyncio +async def test_async_branches_create_from_missing_ref_hint_applies_only_to_branches( + tmp_path, +): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("test", data=[{"i": 0}]) + base = await table.branches.create("base") + await base.add([{"i": 1}]) + await table.tags.create("baseline") + + with pytest.raises(RuntimeError) as exc_info: + await table.branches.create("exp", from_ref="baseline") + + detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ()))) + assert "from_tag='baseline'" in detail + + # An existing branch with an absent version is a version failure, not an + # unresolved branch, so it must not suggest from_tag. + with pytest.raises(RuntimeError) as exc_info: + await table.branches.create("exp", from_ref="base", from_version=9999) + + detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ()))) + assert "9999" in detail + assert "from_tag=" not in detail + + @pytest.mark.asyncio async def test_async_open_table_with_branch_version(tmp_path): db = await lancedb.connect_async(tmp_path, read_consistency_interval=timedelta(0)) diff --git a/python/src/table.rs b/python/src/table.rs index f9c81d5a3..227247307 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -36,7 +36,7 @@ use lancedb::table::{ }; use lancedb::tokenize as lancedb_tokenize; use pyo3::{ - Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python, + Bound, FromPyObject, Py, PyAny, PyErr, PyRef, PyResult, Python, exceptions::{PyRuntimeError, PyValueError}, pyclass, pyfunction, pymethods, types::{ @@ -3261,9 +3261,14 @@ impl Tags { }) } - pub fn create(self_: PyRef, tag: String, version: u64) -> PyResult> { + #[pyo3(signature = (tag, version=None))] + pub fn create(self_: PyRef, tag: String, version: Option) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { + let version = match version { + Some(version) => version, + None => inner.version().await.infer_error()?, + }; let mut tags = inner.tags().await.infer_error()?; tags.create(tag.as_str(), version).await.infer_error()?; Ok(()) @@ -3300,6 +3305,35 @@ impl Branches { } } +/// Add the from_tag hint to a native branch lookup failure. +/// +/// The caller only invokes this for a native `NotFound`, which identifies an +/// unresolved branch path. A missing version is `VersionNotFound`, and a REST +/// 404 is an ambiguous `TableNotFound`, so neither gets the hint. The original +/// exception class and message are preserved apart from the added note. +fn add_from_tag_hint(error: PyErr, branch: &str) -> PyErr { + let hint = format!("If '{branch}' is a tag, pass from_tag='{branch}' instead of from_ref."); + Python::attach(|py| { + let value = error.value(py); + if value.hasattr("add_note").unwrap_or(false) + && value.call_method1("add_note", (hint.clone(),)).is_ok() + { + return error; + } + // Python 3.10 has no BaseException.add_note. Native branch lookup + // failures are runtime errors with one string argument, so append the + // hint to that message without changing the exception class. + let Ok(args) = value.getattr("args") else { + return error; + }; + let Ok(original) = args.get_item(0).and_then(|arg| arg.extract::()) else { + return error; + }; + let _ = value.setattr("args", (format!("{original}\n{hint}"),)); + error + }) +} + #[pymethods] impl Branches { pub fn list(self_: PyRef<'_, Self>) -> PyResult> { @@ -3320,18 +3354,42 @@ impl Branches { }) } - #[pyo3(signature = (name, from_ref=None, from_version=None))] + #[pyo3(signature = (name, from_ref=None, from_version=None, *, from_tag=None))] pub fn create( self_: PyRef<'_, Self>, name: String, from_ref: Option, from_version: Option, + from_tag: Option, ) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { - let from = Ref::Version(from_ref, from_version); - let table = inner.create_branch(&name, from).await.infer_error()?; - Ok(Table::new(table)) + let from_branch = if from_tag.is_none() { + from_ref.clone() + } else { + None + }; + let from = match from_tag { + Some(tag) => Ref::Tag(tag), + None => Ref::Version(from_ref, from_version), + }; + match inner.create_branch(&name, from).await { + Ok(table) => Ok(Table::new(table)), + Err(error) => { + // A missing branch is a native NotFound. A missing version + // is VersionNotFound, and a remote 404 is an ambiguous + // TableNotFound, so only the native branch case hints. + let missing_branch = matches!( + &error, + lancedb::Error::Lance { source } if source.is_not_found() + ); + let error = Err::<(), _>(error).infer_error().unwrap_err(); + match from_branch { + Some(branch) if missing_branch => Err(add_from_tag_hint(error, &branch)), + _ => Err(error), + } + } + } }) } diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index fd7358e9a..b168ff6ff 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -5813,6 +5813,60 @@ mod tests { assert_eq!(at2.count_rows(Some("i = 10".to_string())).await.unwrap(), 0); } + #[tokio::test] + async fn test_create_branch_from_tag_on_branch_with_same_version_as_main() { + let tmp_dir = tempdir().unwrap(); + let uri = tmp_dir.path().to_str().unwrap(); + let conn = ConnectBuilder::new(uri) + .read_consistency_interval(Duration::from_secs(0)) + .execute() + .await + .unwrap(); + + let table = conn + .create_table("my_table", sample_rows(vec![0])) + .execute() + .await + .unwrap(); + let fork_point = table.version().await.unwrap(); + + // Advance exp and main to the same version number with different rows. + let exp = table.create_branch("exp", fork_point).await.unwrap(); + exp.add(sample_rows(vec![10])).execute().await.unwrap(); + let exp_version = exp.version().await.unwrap(); + table.add(sample_rows(vec![100])).execute().await.unwrap(); + assert_eq!(exp_version, table.version().await.unwrap()); + + // Tag exp at that shared version number. The tag must keep exp's branch + // identity, so forking from it sees exp's snapshot rather than main's + // version with the same number. + let mut tags = exp.tags().await.unwrap(); + tags.create("exp-v2", exp_version).await.unwrap(); + + let from_tag = table + .create_branch( + "from-tag", + lance::dataset::refs::Ref::Tag("exp-v2".to_string()), + ) + .await + .unwrap(); + assert_eq!(from_tag.current_branch().as_deref(), Some("from-tag")); + assert_eq!( + from_tag + .count_rows(Some("i = 10".to_string())) + .await + .unwrap(), + 1 + ); + assert_eq!( + from_tag + .count_rows(Some("i = 100".to_string())) + .await + .unwrap(), + 0 + ); + } + #[tokio::test] async fn test_branch_name_validation() { let tmp_dir = tempdir().unwrap(); From 0d2655edbae904bbc351fb98df5b35ee24c65d23 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 05:04:30 +0800 Subject: [PATCH 55/78] test(python): isolate the background-loop fork scenario (#5142) ## Summary Follow-up to #5111. `test_forked_child_starts_background_loop_lazily` forked the shared pytest process. On CI that process may already own native Tokio/parking_lot state from earlier tests such as `test_authz.py`, so the forked child can crash in a non-Python native thread during `table_names()` for reasons unrelated to this scenario. Run the entire fork scenario in a fresh `python -c` subprocess. The parent still starts `LOOP` via `parent-before`, forks while holding `LOOP._start_lock` (released in `finally`), and the child still verifies that it sees no inherited loop, thread, or background threads before using the real native sync API (`connect("memory://")` / `table_names()`). The child must then gain exactly one live daemon thread, while the parent's original thread stays alive and serves `parent-after`. This is test isolation, not a production fix or a root-cause claim. The original assertions and cleanup are preserved, with a 40s outer timeout for `join(20)`, `terminate()` + `join(5)`, `queue.get(5)`, and diagnostics. ## CI evidence The failure was observed on a docs-only main run (`b4459f35`), so it is not caused by a product change in that run: - [Minimum dependencies job 136441279987](https://github.com/lancedb/lancedb/actions/runs/44780367013/job/136441279987): timed out at ~20s. - [Linux Python 3.13 job 136441280394](https://github.com/lancedb/lancedb/actions/runs/44780367013/job/136441280394): native SIGSEGV in a non-Python native thread during `table_names()` after `connect`, following `test_authz.py` in the same stage. ## Validation - `python/tests/test_background_loop.py`: 4 passed. - Same pytest process, `test_authz.py` followed by `test_background_loop.py`: 83 passed. - `uv run make check`: cargo fmt, ruff format, cargo clippy, and ruff check passed. No production code changes. --- python/python/tests/test_background_loop.py | 171 +++++++++++--------- 1 file changed, 91 insertions(+), 80 deletions(-) diff --git a/python/python/tests/test_background_loop.py b/python/python/tests/test_background_loop.py index 52b8b1f73..8a3a2c247 100644 --- a/python/python/tests/test_background_loop.py +++ b/python/python/tests/test_background_loop.py @@ -1,12 +1,10 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -import multiprocessing as mp import os import subprocess import sys import textwrap -import traceback import pytest @@ -14,7 +12,7 @@ import pytest BACKGROUND_THREAD_NAME = "LanceDBBackgroundEventLoop" -def _run_in_subprocess(code: str) -> subprocess.CompletedProcess: +def _run_in_subprocess(code: str, timeout: int = 30) -> subprocess.CompletedProcess: env = os.environ.copy() env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path) return subprocess.run( @@ -23,7 +21,7 @@ def _run_in_subprocess(code: str) -> subprocess.CompletedProcess: capture_output=True, text=True, env=env, - timeout=30, + timeout=timeout, ) @@ -142,45 +140,6 @@ def test_concurrent_first_use_initializes_one_background_thread(): _assert_subprocess_ok(result) -def _fork_child_starts_lazily(queue): - def background_threads(): - import threading - - return [ - thread - for thread in threading.enumerate() - if thread.name == BACKGROUND_THREAD_NAME - ] - - try: - from lancedb.background_loop import LOOP - - inherited_thread_is_none = LOOP.thread is None - inherited_loop_is_none = LOOP.loop is None - background_threads_before = [thread.name for thread in background_threads()] - - import lancedb - - db = lancedb.connect("memory://") - tables = db.table_names() - - worker = LOOP.thread - queue.put( - { - "error": None, - "inherited_thread_is_none": inherited_thread_is_none, - "inherited_loop_is_none": inherited_loop_is_none, - "background_threads_before": background_threads_before, - "tables": tables, - "thread_alive": False if worker is None else worker.is_alive(), - "thread_daemon": False if worker is None else worker.daemon, - "background_thread_count": len(background_threads()), - } - ) - except BaseException: - queue.put({"error": traceback.format_exc()}) - - @pytest.mark.skipif( sys.platform != "linux", reason=( @@ -189,48 +148,100 @@ def _fork_child_starts_lazily(queue): ), ) def test_forked_child_starts_background_loop_lazily(): - import asyncio + # Fork from a fresh interpreter: earlier tests in a shared pytest process + # may have left native runtime state that is not part of this scenario. + result = _run_in_subprocess( + f""" + import asyncio + import multiprocessing as mp + import threading + import traceback - from lancedb.background_loop import LOOP + from lancedb.background_loop import LOOP - assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before" - parent_thread = LOOP.thread - assert parent_thread is not None + BACKGROUND_THREAD_NAME = {BACKGROUND_THREAD_NAME!r} - ctx = mp.get_context("fork") - queue = ctx.Queue() + def background_threads(): + return [ + thread + for thread in threading.enumerate() + if thread.name == BACKGROUND_THREAD_NAME + ] - # Simulate forking while another thread held the initialization lock. The - # child must replace the inherited lock instead of trying to acquire it. - LOOP._start_lock.acquire() - try: - proc = ctx.Process(target=_fork_child_starts_lazily, args=(queue,)) - proc.start() - finally: - LOOP._start_lock.release() + def fork_child(queue): + try: + from lancedb.background_loop import LOOP - proc.join(timeout=20) - if proc.is_alive(): - proc.terminate() - proc.join(timeout=5) + inherited_thread_is_none = LOOP.thread is None + inherited_loop_is_none = LOOP.loop is None + background_threads_before = [ + thread.name for thread in background_threads() + ] + + import lancedb + + db = lancedb.connect("memory://") + tables = db.table_names() + + worker = LOOP.thread + queue.put( + dict( + error=None, + inherited_thread_is_none=inherited_thread_is_none, + inherited_loop_is_none=inherited_loop_is_none, + background_threads_before=background_threads_before, + tables=tables, + thread_alive=False if worker is None else worker.is_alive(), + thread_daemon=False if worker is None else worker.daemon, + background_thread_count=len(background_threads()), + ) + ) + except BaseException: + queue.put(dict(error=traceback.format_exc())) + + assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before" + parent_thread = LOOP.thread + assert parent_thread is not None + + ctx = mp.get_context("fork") + queue = ctx.Queue() + + # Simulate forking while another thread held the initialization lock. The + # child must replace the inherited lock instead of trying to acquire it. + LOOP._start_lock.acquire() + try: + proc = ctx.Process(target=fork_child, args=(queue,)) + proc.start() + finally: + LOOP._start_lock.release() + + proc.join(timeout=20) if proc.is_alive(): - proc.kill() - proc.join() - pytest.fail("Forked child hung starting the background loop") + proc.terminate() + proc.join(timeout=5) + if proc.is_alive(): + proc.kill() + proc.join() + raise AssertionError("Forked child hung starting the background loop") - assert proc.exitcode == 0, f"child exited with code {proc.exitcode}" - payload = queue.get(timeout=5) - queue.close() - assert payload["error"] is None, payload["error"] - assert payload["inherited_thread_is_none"] is True - assert payload["inherited_loop_is_none"] is True - assert payload["background_threads_before"] == [] - assert payload["tables"] == [] - assert payload["thread_alive"] is True - assert payload["thread_daemon"] is True - assert payload["background_thread_count"] == 1 + assert proc.exitcode == 0, "child exited with code %s" % proc.exitcode + payload = queue.get(timeout=5) + queue.close() + assert payload["error"] is None, payload["error"] + assert payload["inherited_thread_is_none"] is True + assert payload["inherited_loop_is_none"] is True + assert payload["background_threads_before"] == [] + assert payload["tables"] == [] + assert payload["thread_alive"] is True + assert payload["thread_daemon"] is True + assert payload["background_thread_count"] == 1 - # The child's reset must not disturb the parent's loop. - assert LOOP.thread is parent_thread - assert parent_thread.is_alive() - assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after" + # The child's reset must not disturb the parent's loop. + assert LOOP.thread is parent_thread + assert parent_thread.is_alive() + assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after" + """, + # join(20) + terminate join(5) + queue get(5), plus startup and traceback. + timeout=40, + ) + _assert_subprocess_ok(result) From c55b7c0390e2b75b7640c0466bbd1d193612bc2c Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 05:20:16 +0800 Subject: [PATCH 56/78] feat!: add explicit scan order contract for local queries (#5138) BREAKING CHANGE: `QueryRequest` now has a public `scan_in_order: Option` field. Existing code that constructs `QueryRequest` with an exhaustive struct literal must add `scan_in_order: None` to retain the previous backend default, or use `..Default::default()` where appropriate. Python defaults are unchanged: leaving `scan_in_order()` uncalled keeps `None`. ## Problem Plain Embedded LanceDB scans already use Lance's ordered scan on a fixed snapshot, but the storage-order contract was undocumented and callers had no way to require it. Explicit `order_by` sorts the whole result. Ranked, Enterprise, RTE/LSM, legacy scalar-index and namespace-pushdown paths cannot always preserve base manifest order. ## Behavior - `scan_in_order(true)` requires manifest order without adding a sort: fragments in manifest order, then rows in fragment order. - `true` disables scalar-index filter planning. Legacy scalar-index plans can materialize index rows in a different sequence, so filters are evaluated over the manifest-ordered scan instead. Filter semantics are unchanged, but the scan can read more data. Default filtered scans can still use those plans and may not preserve manifest order. - `scan_in_order(false)` permits the backend to scan unordered. It does **not** guarantee a different order; an explicit nonempty `order_by` still sorts. - Leaving the option unset preserves the backend default. The documented manifest-order default applies to an unfiltered base-only scan of a pinned Embedded table version. RTE tables scan the LSM by default and need `use_rte(false)` for the base-only guarantee. Enterprise and namespace-pushed scans have no order guarantee. - `true` conflicts with nonempty `order_by`, take queries, vector/full-text/hybrid/reranked queries, RTE/LSM reads, and Enterprise tables. These fail explicitly instead of silently dropping the requirement. Take conflict validation happens at the shared take-preparation boundary before offset or row-id selectors are stripped. - `with_fragments()` is rejected with `scan_in_order(true)` because fragment objects cannot be validated against the pinned dataset version. Use `fragment_ids()`, which resolves fragment ids from the manifest and preserves manifest order. Both sync and async pandas scanner paths share this rule. - Namespace `QueryTable` pushdown executes `true` against Embedded storage instead of dropping the order. The existing path preserves projection, filtering, limits, version/branch selection, and RTE routing; if Embedded storage cannot be read, the query fails. Supported entry points are plain Rust `Table::query()`, Python sync `table.search()` and async `table.query()`. The Python pandas scanner fast path forwards the option and disables scalar-index planning for explicit order. Existing takes and `with_fragments()` calls with `None` or `false` are unchanged. ## Validation - Rust: 6 `scan_in_order` tests, 32 take tests, 25 query-route tests. - Python: `test_query.py` and `test_namespace.py` 352 passed, 1 skipped against a matching extension. - Scoped `pytest --doctest-modules python/lancedb/query.py -k scan_in_order`: 2 passed. The Rust/Python examples create their own tables and are executable. - Regressions cover legacy 0.1 and stable BTREE tables with update and a filter admitting every row, across pinned versions before and after update; reversed `fragment_ids`; explicit `with_fragments()` rejection; and fixed-version multi-fragment reads with deletions, one-row batches, and limit/offset. No `SortExec` is added. - `cargo clippy --features remote --tests --examples`; `cargo fmt --check`; Ruff format/check; `git diff --check`. - Local checks ran on this branch. CI on this PR evaluates the merge with current `main`; no combined local binary validation is claimed here. Refs OSS-3109. --- python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/namespace.py | 16 +- python/python/lancedb/query.py | 120 ++++++++- python/python/lancedb/table.py | 5 + python/python/tests/test_namespace.py | 48 ++++ python/python/tests/test_query.py | 195 ++++++++++++++ python/src/query.rs | 7 + rust/lancedb/src/query.rs | 161 ++++++++++- rust/lancedb/src/remote/table.rs | 28 ++ rust/lancedb/src/table.rs | 15 +- rust/lancedb/src/table/query.rs | 372 +++++++++++++++++++++++++- rust/lancedb/src/table/query/lsm.rs | 5 + 12 files changed, 956 insertions(+), 18 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a3a9610c9..f40fbc30c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -972,6 +972,7 @@ class Query: def nearest_to(self, query_vec: pa.Array) -> VectorQuery: ... def nearest_to_text(self, query: dict) -> FTSQuery: ... def order_by(self, ordering: Optional[List[ColumnOrdering]]): ... + def scan_in_order(self, ordered: bool): ... async def output_schema(self) -> pa.Schema: ... async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] @@ -1129,6 +1130,7 @@ class PyQueryRequest: postfilter: Optional[bool] norm: Optional[str] order_by: Optional[List[ColumnOrdering]] + scan_in_order: Optional[bool] class CompactionStats: fragments_removed: int diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 3940e7b7e..4c8ec1a62 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -510,8 +510,8 @@ class LanceNamespaceDBConnection(DBConnection): - "QueryTable": Execute queries on the namespace server via namespace.query_table() instead of locally. Queries with a - nonempty ``order_by`` execute locally and require the client to - access the table storage. + nonempty ``order_by`` or an explicit ``scan_in_order(True)`` + execute on the client and require access to the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1215,8 +1215,8 @@ class AsyncLanceNamespaceDBConnection: - "QueryTable": Execute queries on the namespace server via namespace.query_table() instead of locally. Queries with a - nonempty ``order_by`` execute locally and require the client to - access the table storage. + nonempty ``order_by`` or an explicit ``scan_in_order(True)`` + execute on the client and require access to the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1824,8 +1824,8 @@ def connect_namespace( - "QueryTable": Execute queries on the namespace server via namespace.query_table() instead of locally. Queries with a nonempty - ``order_by`` execute locally and require the client to access the - table storage. + ``order_by`` or an explicit ``scan_in_order(True)`` execute on the + client and require access to the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1917,8 +1917,8 @@ def connect_namespace_async( - "QueryTable": Execute queries on the namespace server via namespace.query_table() instead of locally. Queries with a nonempty - ``order_by`` execute locally and require the client to access the - table storage. + ``order_by`` or an explicit ``scan_in_order(True)`` execute on the + client and require access to the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 19e9051f7..68598dd68 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -371,6 +371,10 @@ def _scanner_kwargs_for_query( "with_row_id": with_row_id if with_row_id is not None else query.with_row_id, "with_row_address": query.with_row_address, "fast_search": query.fast_search, + "scan_in_order": query.scan_in_order, + # Legacy scalar-index plans can reorder rows. Explicit storage order + # evaluates filters over the manifest-ordered scan instead. + "use_scalar_index": False if query.scan_in_order is True else None, "blob_handling": BLOB_MODE_TO_HANDLING[blob_mode], "fragments": fragments, } @@ -381,6 +385,12 @@ def _scanner_fragments_for_query(query: Query, dataset: Optional[Any]) -> Option if query.fragments is not None and query.fragment_ids is not None: raise ValueError("fragments and fragment_ids cannot both be set") if query.fragments is not None: + if query.scan_in_order is True: + raise ValueError( + "scan_in_order(True) cannot validate with_fragments() against " + "the scanned dataset version; use fragment_ids() to select " + "fragments by manifest id" + ) return query.fragments if query.fragment_ids is None: return None @@ -1208,6 +1218,10 @@ class Query(pydantic.BaseModel): order_by: Optional[List[ColumnOrdering]] = None + # Tri-state storage-order requirement: None preserves the backend default, + # True requires manifest order, False allows an unordered scan. + scan_in_order: Optional[bool] = None + @classmethod def from_inner(cls, req: PyQueryRequest) -> Self: query = cls() @@ -1241,6 +1255,7 @@ class Query(pydantic.BaseModel): query.postfilter = req.postfilter if req.order_by is not None: query.order_by = [ColumnOrdering(**o) for o in req.order_by] + query.scan_in_order = req.scan_in_order if req.full_text_search is not None: query.full_text_query = FullTextSearchQuery( columns=None, @@ -1415,6 +1430,7 @@ class LanceQueryBuilder(ABC): self._approx_mode = None self._bypass_vector_index = None self._order_by = None + self._scan_in_order = None @deprecation.deprecated( deprecated_in="0.3.1", @@ -2023,7 +2039,9 @@ class LanceQueryBuilder(ABC): ---------- fragments : list[lance.Fragment] Fragments from ``table.to_lance().get_fragments()``. Pass fragments - from the same dataset snapshot. + from the same dataset snapshot. Use ``fragment_ids()`` instead when + ``scan_in_order(True)`` is set; fragment objects cannot be validated + against the pinned dataset version. Returns ------- @@ -3082,6 +3100,52 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): schema=schema, ) + def scan_in_order(self, ordered: bool = True) -> Self: + """Control whether an ordinary scan must preserve storage order. + + Parameters + ---------- + ordered: bool, default True + ``True`` requires manifest order: fragments in manifest order, then + rows in fragment order. ``False`` allows the backend to scan + unordered. Leave the method uncalled to preserve the backend + default. + + An unfiltered plain base-only scan of an Embedded table, pinned to one + dataset version, returns manifest order by default. RTE tables scan the + LSM by default and do not provide this guarantee unless + ``use_rte(False)`` selects the base table. Explicit ``True`` also + disables scalar-index filter planning, because legacy scalar-index plans + can return a different sequence; default filtered scans can still use + those plans and may not preserve manifest order. Filters still apply, + but the scan can read more data. ``with_fragments()`` is not supported + with ``True`` because fragment objects cannot be validated against the + pinned dataset version; use ``fragment_ids()`` instead, which resolves + ids from the manifest and remains ordered. Compaction, updates, or + opening a newer version can change that order, so pin the table version + when positions must remain stable across executions. An explicit + ``order_by()`` replaces manifest order with a global sort, and vector, + full-text, hybrid, or reranked queries return ranked results; combining + those with ``scan_in_order(True)`` raises ``ValueError``. Enterprise + tables and RTE/LSM reads raise ``NotImplementedError`` because they + cannot uphold the order; set ``use_rte(False)`` to read the RTE base + table in storage order. When ``QueryTable`` pushdown is enabled, the + backend default may not preserve order; requesting ``True`` executes + against Embedded storage instead, because the namespace request has no + order field. + + Examples + -------- + >>> import lancedb + >>> db = lancedb.connect("memory://") + >>> table = db.create_table("scan_in_order", [{"id": 1}]) + >>> query = table.search().scan_in_order(True).select(["id"]) + >>> query.to_arrow()["id"].to_pylist() + [1] + """ + self._scan_in_order = ordered + return self + def to_query_object(self) -> Query: return Query( columns=self._columns, @@ -3094,6 +3158,7 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): use_rte=self._use_rte, offset=self._offset, order_by=self._order_by, + scan_in_order=self._scan_in_order, ) def output_schema(self) -> pa.Schema: @@ -4142,7 +4207,9 @@ class AsyncQueryBase(object): query types. Other terminals and remote tables raise ``NotImplementedError`` before scanning instead of silently scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep their - existing validation errors. + existing validation errors. Use ``fragment_ids()`` instead when + ``scan_in_order(True)`` is set; fragment objects cannot be validated + against the pinned dataset version. """ self._fragments = fragments return self @@ -4866,6 +4933,55 @@ class AsyncQuery(AsyncStandardQuery): super().__init__(inner, table) self._inner = inner + def scan_in_order(self, ordered: bool = True) -> Self: + """Control whether an ordinary scan must preserve storage order. + + Parameters + ---------- + ordered: bool, default True + ``True`` requires manifest order: fragments in manifest order, then + rows in fragment order. ``False`` allows the backend to scan + unordered. Leave the method uncalled to preserve the backend + default. + + An unfiltered plain base-only scan of an Embedded table, pinned to one + dataset version, returns manifest order by default. RTE tables scan the + LSM by default and do not provide this guarantee unless + ``use_rte(False)`` selects the base table. Explicit ``True`` also + disables scalar-index filter planning, because legacy scalar-index plans + can return a different sequence; default filtered scans can still use + those plans and may not preserve manifest order. Filters still apply, + but the scan can read more data. ``with_fragments()`` is not supported + with ``True`` because fragment objects cannot be validated against the + pinned dataset version; use ``fragment_ids()`` instead, which resolves + ids from the manifest and remains ordered. Compaction, updates, or + opening a newer version can change that order, so pin the table version + when positions must remain stable across executions. An explicit + ``order_by()`` replaces manifest order with a global sort, and vector, + full-text, hybrid, or reranked queries return ranked results; combining + those with ``scan_in_order(True)`` raises ``ValueError``. Enterprise + tables and RTE/LSM reads raise ``NotImplementedError`` because they + cannot uphold the order; set ``use_rte(False)`` to read the RTE base + table in storage order. When ``QueryTable`` pushdown is enabled, the + backend default may not preserve order; requesting ``True`` executes + against Embedded storage instead, because the namespace request has no + order field. + + Examples + -------- + >>> import asyncio + >>> import lancedb + >>> async def example(): + ... db = await lancedb.connect_async("memory://") + ... table = await db.create_table("scan_in_order_async", [{"id": 1}]) + ... query = table.query().scan_in_order(True).select(["id"]) + ... return (await query.to_arrow())["id"].to_pylist() + >>> asyncio.run(example()) + [1] + """ + self._inner.scan_in_order(ordered) + return self + @classmethod def _query_vec_to_array(self, vec: Union[VEC, Tuple]): if isinstance(vec, list): diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index a6ba1692e..529375f6e 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -149,6 +149,9 @@ def _requires_local_namespace_execution(query: Query) -> bool: # The namespace QueryTable request has no order_by field. Pushing a # nonempty ordering down would drop it and return the wrong top-K rows. or bool(query.order_by) + # An ordered scan is a local manifest-order guarantee. The request has + # no scan-order field, so run it locally where storage is available. + or query.scan_in_order is True or ( query.full_text_query is not None and query.fast_search is True @@ -8529,6 +8532,8 @@ class AsyncTable: async_query = async_query.with_row_id() if query.order_by: async_query = async_query.order_by(query.order_by) + if query.scan_in_order is not None: + async_query = async_query.scan_in_order(query.scan_in_order) if query.vector: async_query = async_query.nearest_to(query.vector).distance_range( diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 937572cc0..2c999d1b0 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -1789,6 +1789,31 @@ class TestPushdownOperations: assert result.column("id").to_pylist() == [1] assert namespace_client.requests == [] + def test_lance_table_scan_in_order_is_not_pushed_down(self, tmp_path): + namespace_client = _NamespaceClient() + db = lancedb.connect(str(tmp_path / "db")) + table = db.create_table("hist", data=[{"id": 3}, {"id": 1}]) + table.add([{"id": 2}]) + table._namespace_path = ["geneva"] + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = table._execute_query( + Query( + limit=2, + filter="id >= 1", + columns=["id"], + scan_in_order=True, + ) + ).read_all() + + # The namespace request has no scan-order field. Local execution keeps + # membership order, projection and limit; a dropped order or a sort + # would return [1, 3] or [1, 2]. + assert result.column("id").to_pylist() == [3, 1] + assert namespace_client.requests == [] + @pytest.mark.asyncio class TestAsyncPushdownOperations: @@ -1869,6 +1894,29 @@ class TestAsyncPushdownOperations: assert pa.Table.from_batches(batches).column("id").to_pylist() == [1] assert namespace_client.requests == [] + async def test_async_table_scan_in_order_is_not_pushed_down(self, tmp_path): + namespace_client = _NamespaceClient() + db = await lancedb.connect_async(str(tmp_path / "db")) + table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}]) + await table.add([{"id": 2}]) + table._namespace_path = ["geneva"] + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = await table._execute_query( + Query( + limit=2, + filter="id >= 1", + columns=["id"], + scan_in_order=True, + ) + ) + + batches = await result.read_all() + assert pa.Table.from_batches(batches).column("id").to_pylist() == [3, 1] + assert namespace_client.requests == [] + @pytest.mark.parametrize( "query_kwargs", [ diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index c01b3f9dc..ed8e0d24f 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1102,6 +1102,201 @@ def test_order_by_clears_with_none_and_empty_list(mem_db): assert query.order_by([]).to_query_object().order_by is None +def test_scan_in_order_plain_query(tmp_db): + table = tmp_db.create_table("scan_in_order", pa.table({"id": [0, 1]})) + table.add(pa.table({"id": [2, 3]})) + table.add(pa.table({"id": [4, 5]})) + + fragments = table.to_lance().get_fragments() + assert len(fragments) == 3, "the test needs real multi-fragment data" + + version = table.version + table.checkout(version) + + default = table.search().select(["id"]).to_arrow()["id"].to_pylist() + assert default == [0, 1, 2, 3, 4, 5] + assert table.search().to_query_object().scan_in_order is None + + ordered = table.search().scan_in_order().select(["id"]).to_arrow() + assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5] + repeated = table.search().scan_in_order(True).select(["id"]).to_arrow() + assert repeated.equals(ordered) + + unordered = ( + table.search().scan_in_order(False).select(["id"]).to_arrow()["id"].to_pylist() + ) + assert sorted(unordered) == [0, 1, 2, 3, 4, 5] + + sorted_desc = ( + table.search() + .scan_in_order(False) + .order_by(("id", "desc")) + .select(["id"]) + .to_arrow()["id"] + .to_pylist() + ) + assert sorted_desc == [5, 4, 3, 2, 1, 0] + + with pytest.raises(ValueError, match="nonempty order_by"): + table.search().scan_in_order().order_by("id").to_arrow() + + +@pytest.mark.asyncio +async def test_scan_in_order_async_query(tmp_db_async: AsyncConnection): + table = await tmp_db_async.create_table( + "scan_in_order_async", pa.table({"id": [0, 1]}) + ) + await table.add(pa.table({"id": [2, 3]})) + await table.add(pa.table({"id": [4, 5]})) + + assert len((await table.to_lance()).get_fragments()) == 3 + version = await table.version() + await table.checkout(version) + + ordered = await table.query().scan_in_order().select(["id"]).to_arrow() + assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5] + assert table.query().to_query_object().scan_in_order is None + + unordered = (await table.query().scan_in_order(False).select(["id"]).to_arrow())[ + "id" + ].to_pylist() + assert sorted(unordered) == [0, 1, 2, 3, 4, 5] + + with pytest.raises(ValueError, match="nonempty order_by"): + await table.query().scan_in_order().order_by("id").to_arrow() + with pytest.raises(ValueError, match="ranked results"): + await table.query().scan_in_order().nearest_to([0.0, 0.0]).to_arrow() + + +@pytest.mark.parametrize("ordered", [False, True]) +def test_scan_in_order_pandas_scanner_path(tmp_db, monkeypatch, ordered): + pytest.importorskip("lance") + data = _blob_query_data() + table = tmp_db.create_table( + f"scan_in_order_scanner_{ordered}", + data.slice(0, 2), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + table.add(data.slice(2, 2)) + + query = table.search().select(["id", "blob"]).scan_in_order(ordered) + + def fail_to_arrow(*args, **kwargs): + raise AssertionError("scanner-backed pandas must not collect through to_arrow") + + monkeypatch.setattr(query, "to_arrow", fail_to_arrow) + + dataset = table.to_lance() + dataset_cls = type(dataset) + real_scanner = dataset_cls.scanner + captured = {} + + def capture_scanner(self, **kwargs): + captured.update(kwargs) + return real_scanner(self, **kwargs) + + monkeypatch.setattr(dataset_cls, "scanner", capture_scanner) + + df = query.to_pandas(blob_mode="descriptions", flatten=True) + + assert captured["scan_in_order"] is ordered + assert captured.get("use_scalar_index") is (False if ordered else None) + assert sorted(df["id"].tolist()) == [1, 2, 3, 4] + + +@pytest.mark.parametrize("storage_version", ["legacy", "stable"]) +def test_scan_in_order_indexed_filter_preserves_manifest_order( + tmp_path, storage_version +): + lance = pytest.importorskip("lance") + data = pa.table({"id": list(range(20)), "value": list(range(20))}) + dataset = lance.write_dataset( + data, + tmp_path / "t.lance", + data_storage_version=storage_version, + max_rows_per_file=10, + ) + dataset.create_scalar_index("value", "BTREE") + version_before_update = dataset.version + dataset.update({"value": "100"}, where="id = 0") + + table = lancedb.connect(str(tmp_path)).open_table("t") + for version in (version_before_update, dataset.version): + table.checkout(version) + base = table.search().scan_in_order(True).select(["id"]).limit(100) + expected = base.to_arrow()["id"].to_pylist() + actual = base.where("value < 1000").to_arrow()["id"].to_pylist() + assert actual == expected + + +def test_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(tmp_db): + pytest.importorskip("lance") + data = _blob_query_data() + table = tmp_db.create_table( + "scan_in_order_fragments", + data.slice(0, 2), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + table.add(data.slice(2, 2)) + table.checkout(table.version) + + fragments = table.to_lance().get_fragments() + reversed_fragments = fragments[::-1] + with pytest.raises(ValueError, match="use fragment_ids"): + ( + table.search() + .scan_in_order() + .select(["id", "blob"]) + .with_fragments(reversed_fragments) + .to_pandas(blob_mode="descriptions", flatten=True) + ) + + # fragment_ids is already resolved from the manifest and stays ordered. + df_by_id = ( + table.search() + .scan_in_order() + .select(["id", "blob"]) + .fragment_ids([fragment.fragment_id for fragment in reversed_fragments]) + .to_pandas(blob_mode="descriptions", flatten=True) + ) + assert df_by_id["id"].tolist() == [1, 2, 3, 4] + + +@pytest.mark.asyncio +async def test_async_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids( + tmp_db_async, +): + pytest.importorskip("lance") + data = _blob_query_data() + table = await tmp_db_async.create_table( + "scan_in_order_fragments_async", + data.slice(0, 2), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + await table.add(data.slice(2, 2)) + await table.checkout(await table.version()) + + fragments = (await table.to_lance()).get_fragments() + reversed_fragments = fragments[::-1] + with pytest.raises(ValueError, match="use fragment_ids"): + await ( + table.query() + .scan_in_order() + .with_fragments(fragments[::-1]) + .select(["id", "blob"]) + .to_pandas(blob_mode="descriptions", flatten=True) + ) + + df_by_id = await ( + table.query() + .scan_in_order() + .fragment_ids([fragment.fragment_id for fragment in reversed_fragments]) + .select(["id", "blob"]) + .to_pandas(blob_mode="descriptions", flatten=True) + ) + assert df_by_id["id"].tolist() == [1, 2, 3, 4] + + def test_order_by_rejects_invalid_input_early(mem_db): table = mem_db.create_table("test_order_by_invalid", [{"name": "a"}]) diff --git a/python/src/query.rs b/python/src/query.rs index 7a7e34416..d8cfedfdb 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -396,6 +396,7 @@ pub struct PyQueryRequest { pub postfilter: Option, pub norm: Option, pub order_by: Option>, + pub scan_in_order: Option, } impl From for PyQueryRequest { @@ -434,6 +435,7 @@ impl From for PyQueryRequest { order_by: query_request .order_by .map(|order_by| order_by.into_iter().map(PyColumnOrdering::from).collect()), + scan_in_order: query_request.scan_in_order, }, AnyQuery::VectorQuery(vector_query) => Self { limit: vector_query.base.limit, @@ -467,6 +469,7 @@ impl From for PyQueryRequest { .base .order_by .map(|order_by| order_by.into_iter().map(PyColumnOrdering::from).collect()), + scan_in_order: vector_query.base.scan_in_order, }, } } @@ -685,6 +688,10 @@ impl Query { Ok(()) } + pub fn scan_in_order(&mut self, ordered: bool) { + self.inner = self.inner.clone().scan_in_order(ordered); + } + #[pyo3(signature = ())] pub fn output_schema(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 57af7f28d..bc460dc35 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -742,8 +742,14 @@ pub trait ExecutableQuery { /// an Stream of Arrow [`arrow_array::RecordBatch`] (and you can also independently /// access the [`arrow_schema::Schema`] without polling the stream). /// - /// Note: The size of the returned batches and the order of individual rows is - /// not deterministic. + /// Note: The size of the returned batches is not deterministic. Row order + /// depends on the query shape: an ordinary unfiltered base-only scan of a + /// fixed table version in Embedded returns manifest order unless + /// [`Query::scan_in_order`] is set to `false` or a nonempty + /// [`QueryBase::order_by`] adds a sort. RTE + /// tables scan the LSM by default; use `use_rte(false)` for the base-only + /// guarantee. Ranked searches return rank order, while Enterprise and + /// namespace-pushed scans have no order guarantee. /// /// LanceDb will use many threads to calculate results and, when /// the result set is large, multiple batches will be processed at one time. @@ -922,6 +928,11 @@ pub struct QueryRequest { /// This allows ordering query results by one or more columns in either ascending or descending order. pub order_by: Option>, + /// Require (`Some(true)`), allow (`Some(false)`), or leave unchanged (`None`) + /// the scan order. See [`Query::scan_in_order`] for the contract and its + /// boundaries. + pub scan_in_order: Option, + /// Controls RTE read routing. When unset (the default), a query against a /// table that carries an RTE write spec (see /// [`crate::Table::enable_rte`]) is routed through the LSM scanner so @@ -956,6 +967,7 @@ impl Default for QueryRequest { norm: None, disable_scoring_autoprojection: false, order_by: None, + scan_in_order: None, use_rte: None, } } @@ -1044,6 +1056,64 @@ impl Query { VectorQuery::new(self) } + /// Require the results to follow storage order instead of allowing an + /// unordered scan. + /// + /// An unfiltered plain base-only scan of an Embedded table, pinned to one + /// dataset version, returns rows in that version's manifest order: + /// fragments in manifest order, then rows in fragment order. Ordinary + /// unfiltered base-only scans already use Lance's ordered scan by default, + /// so leaving this unset preserves that behavior. RTE tables scan the LSM + /// by default and do not provide this guarantee unless `use_rte(false)` + /// selects the base table. Use `true` when a caller assigns meaning to row + /// positions and must fail instead of silently receiving a different order. + /// + /// Explicit `true` also disables scalar-index filter planning. Legacy + /// scalar-index plans can materialize index rows in a different sequence, + /// so filters are evaluated over the manifest-ordered scan instead. Default + /// filtered scans can still use those plans and may not preserve manifest + /// order. The filter result is unchanged, but the scan can read more data. + /// + /// Leaving this unset preserves the backend default. In particular, a + /// namespace-backed native table configured for `QueryTable` pushdown may + /// not preserve order because the request has no order field; request + /// `true` to execute against Embedded storage. + /// + /// The order is fixed only for the dataset version being scanned. + /// Compaction, updates, or opening a newer version can change it, so pin a + /// version when positions must remain stable across executions. A latest + /// handle can also observe a different version between two executions. + /// + /// - `true` requires manifest order without adding a sort. A nonempty + /// [`QueryBase::order_by`], take query, vector, full-text, hybrid, or + /// reranked query conflicts with storage order and fails with + /// [`Error::InvalidInput`]. + /// Enterprise tables and RTE/LSM reads fail with [`Error::NotSupported`] + /// because they cannot uphold the requirement; set `use_rte(false)` to + /// read the RTE base table in storage order. Namespace-backed native + /// tables execute against Embedded storage instead of using `QueryTable` + /// pushdown, which has no order field, and fail if that storage cannot be + /// read. + /// + /// # Examples + /// + /// ```no_run + /// # use lancedb::query::ExecutableQuery; + /// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> { + /// let rows = table.query().scan_in_order(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + /// - `false` allows the backend to scan without preserving order. An + /// explicit nonempty `order_by` still applies its sort. + /// + /// A nonempty `order_by` replaces manifest order with a global sort. Vector + /// and full-text searches return ranked results regardless of this option. + pub fn scan_in_order(mut self, ordered: bool) -> Self { + self.request.scan_in_order = Some(ordered); + self + } + /// Find the nearest vectors to the given query vector. /// /// This converts the query from a plain query to a vector query. @@ -2086,6 +2156,20 @@ struct TakeLookup { output_projection: Option>, } +/// Take queries restore rows in the requested offset or row-id order, so an +/// explicit storage-order requirement cannot be honored. Check this before the +/// lookup strips the take selectors and hands the inner request to a scan. +pub(crate) fn validate_take_scan_in_order(request: &QueryRequest) -> Result<()> { + if request.scan_in_order == Some(true) { + return Err(Error::InvalidInput { + message: "scan_in_order(true) conflicts with take by row id or offset, which \ + defines its own result order" + .to_string(), + }); + } + Ok(()) +} + impl TakeQuery { /// Create a new `TakeQuery` that will return rows at the given offsets. /// @@ -2200,6 +2284,7 @@ impl TakeQuery { request: &QueryRequest, preserve_order: bool, ) -> Result { + validate_take_scan_in_order(request)?; let (indices, by_row_id) = match (&request.take_offsets, &request.take_row_ids) { (Some(indices), None) => (indices.clone(), false), (None, Some(indices)) => (indices.clone(), true), @@ -4564,6 +4649,78 @@ mod tests { assert!(!analyzed.contains("CoalescePartitionsExec")); } + #[tokio::test] + async fn test_take_scan_in_order_is_rejected_before_lookup() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + + let mut offsets = table + .take_offsets(vec![5, 1, 17]) + .select(Select::Columns(vec!["id".to_string()])) + .limit(2) + .offset(1); + offsets.mut_query().scan_in_order = Some(true); + + let plan_err = offsets + .create_plan(QueryExecutionOptions::default()) + .await + .expect_err("take planning must reject scan_in_order(true)"); + assert!( + matches!(&plan_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {plan_err}" + ); + + let execution_err = offsets + .execute() + .await + .err() + .expect("take execution must reject scan_in_order(true)"); + assert!( + matches!(&execution_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {execution_err}" + ); + + let explain_err = offsets + .explain_plan(false) + .await + .expect_err("take explain must reject scan_in_order(true)"); + assert!( + matches!(&explain_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {explain_err}" + ); + + let mut row_ids = table.take_row_ids(vec![5, 1]); + row_ids.mut_query().scan_in_order = Some(true); + let row_id_err = row_ids + .execute() + .await + .err() + .expect("take by row id must reject scan_in_order(true)"); + assert!( + matches!(&row_id_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {row_id_err}" + ); + + // Allowing unordered scans leaves an ordinary take unchanged. + let mut allowed = table.take_offsets(vec![5, 1]); + allowed.mut_query().scan_in_order = Some(false); + let batches = allowed + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + batches.iter().map(|batch| batch.num_rows()).sum::(), + 2 + ); + } + #[rstest::rstest] #[case::unsorted(vec![5, 1, 17], vec![5, 1, 17])] #[case::duplicate_and_missing(vec![17, 5, 17, u64::MAX, 1], vec![17, 5, 17, 1])] diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 760ab83fe..fc888e32b 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1326,6 +1326,13 @@ impl RemoteTable { params: &QueryRequest, ) -> Result<()> { params.check_filter()?; + if params.scan_in_order == Some(true) { + return Err(Error::NotSupported { + message: "scan_in_order(true) requires an ordered scan of Embedded storage; \ + LanceDB Enterprise tables do not support storage-order scans yet" + .to_string(), + }); + } body["prefilter"] = params.prefilter.into(); // Only forward use_rte when explicitly set; a server that predates it // ignores the field and routes as it would by default. @@ -6718,6 +6725,27 @@ mod tests { assert_eq!(result.version, if old_server { 0 } else { 43 }); } + #[tokio::test] + async fn test_query_scan_in_order_true_is_not_supported() { + let table = Table::new_with_handler::<&str>("my_table", |_| { + panic!("scan_in_order(true) must fail before sending a request") + }); + + let err = table + .query() + .scan_in_order(true) + .execute() + .await + .err() + .expect("remote scans cannot guarantee manifest order"); + assert!( + matches!(&err, Error::NotSupported { message } + if message.contains("scan_in_order(true)") + && message.contains("Enterprise tables")), + "unexpected error: {err}" + ); + } + #[tokio::test] async fn test_query_plain() { let expected_data = RecordBatch::try_new( diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index b168ff6ff..b79beca55 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1897,10 +1897,17 @@ impl Table { /// Create a [`Query`] Builder. /// /// Queries allow you to search your existing data. By default the query will - /// return all the data in the table in no particular order. The builder + /// return all the data in the table. The builder /// returned by this method can be used to control the query using filtering, /// vector similarity, sorting, and more. /// + /// An ordinary unfiltered base-only scan of a fixed table version in + /// Embedded returns manifest order: fragments in manifest order, then rows + /// in fragment order. RTE tables scan the LSM by default; use + /// `use_rte(false)` for the base table guarantee. Compaction, updates, and + /// newer versions can change that order. Use [`Query::scan_in_order`] to + /// require it explicitly and fail on paths that cannot uphold it. + /// /// Note: By default, all columns are returned. For best performance, you should /// only fetch the columns you need. See [`Query::select_with_projection`] for /// more details. @@ -1967,8 +1974,10 @@ impl Table { /// /// ## Full scan /// - /// This query will return everything in the table in no particular - /// order. + /// This query returns everything in the table. On an Embedded table, an + /// ordinary unfiltered base-only scan of a fixed version returns manifest + /// order. RTE tables scan the LSM by default and need `use_rte(false)` for + /// base manifest order. /// /// ```no_run /// # use arrow_array::RecordBatch; diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index b69b85cb3..4dd8df294 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -121,11 +121,13 @@ async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> R fn requires_local_namespace_execution(query: &AnyQuery) -> bool { // The namespace QueryTable request cannot represent approx_mode, search_effort, - // use_rte or order_by. For use_rte that is worse than a tuning miss: RTE read - // routing lives only in `create_plan`, so a pushed-down query would return - // stale base-only data. A dropped order_by would return the wrong top-K rows. + // use_rte, order_by or scan_in_order. For use_rte that is worse than a tuning miss: + // RTE read routing lives only in `create_plan`, so a pushed-down query would return + // stale base-only data. A dropped order_by would return the wrong top-K rows, and a + // dropped ordered scan would silently stop guaranteeing manifest order. if query.base().use_rte.is_some() || query.base().has_take() + || query.base().scan_in_order == Some(true) || query .base() .order_by @@ -154,6 +156,47 @@ pub async fn analyze_query_plan( Ok(lance_analyze_plan(plan, Default::default()).await?) } +/// Reject requests that ask for storage order in a query shape that cannot +/// preserve it, or that also define a different result order. +fn validate_scan_in_order(query: &AnyQuery) -> Result<()> { + if query.base().scan_in_order != Some(true) { + return Ok(()); + } + + let ranked = match query { + AnyQuery::VectorQuery(_) => true, + AnyQuery::Query(query) => { + query.full_text_search.is_some() || query.reranker.is_some() || query.norm.is_some() + } + }; + if ranked { + return Err(Error::InvalidInput { + message: "scan_in_order(true) is only supported for ordinary scans; vector, \ + full-text, hybrid, and reranked queries return ranked results" + .to_string(), + }); + } + + if query + .base() + .order_by + .as_ref() + .is_some_and(|order_by| !order_by.is_empty()) + { + return Err(Error::InvalidInput { + message: "scan_in_order(true) conflicts with a nonempty order_by; remove the \ + ordering to keep manifest order, or remove scan_in_order(true) to sort" + .to_string(), + }); + } + + if query.base().has_take() { + return crate::query::validate_take_scan_in_order(query.base()); + } + + Ok(()) +} + /// Local Execution Path (DataFusion) async fn execute_generic_query( table: &NativeTable, @@ -177,6 +220,7 @@ pub async fn create_plan( options: QueryExecutionOptions, ) -> Result> { let query = query.canonicalized()?; + validate_scan_in_order(&query)?; if let AnyQuery::Query(request) = &query && request.has_take() { @@ -435,6 +479,17 @@ pub async fn create_plan( scanner.order_by(Some(order_by.clone()))?; } + if let Some(scan_in_order) = query.base.scan_in_order { + scanner.scan_in_order(scan_in_order); + if scan_in_order { + // Legacy scalar-index plans can union materialized index rows with + // unindexed fragments and emit a different sequence. Explicit + // storage order must come from the manifest scan, so filters fall + // back to evaluating over the ordered fragments. + scanner.use_scalar_index(false); + } + } + let mut plan = scanner .create_plan() .await @@ -1191,6 +1246,21 @@ mod tests { FixedSizeListArray::try_new_from_values(Float32Array::from(values), dimension).unwrap() } + fn collect_i32(batches: &[RecordBatch]) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect() + } + #[tokio::test] async fn test_parse_arrow_ipc_response_handles_file_and_stream() { use arrow_array::{Int32Array, RecordBatch}; @@ -2462,4 +2532,300 @@ mod tests { Some(ApproxMode::Accurate) ); } + + #[tokio::test] + async fn test_scan_in_order_local_multi_fragment_contract() { + use crate::connect; + use crate::query::ColumnOrdering; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = |ids: Vec| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(ids))]).unwrap() + }; + + let table = conn + .create_table("scan_in_order_contract", batch(vec![0, 1])) + .execute() + .await + .unwrap(); + table.add(batch(vec![2, 3])).execute().await.unwrap(); + table.add(batch(vec![4, 5])).execute().await.unwrap(); + + let fragments = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .get_fragments() + .len(); + assert_eq!(fragments, 3, "the test needs real multi-fragment data"); + + // An ordered scan must not introduce a global sort. + let plan = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(true) + .explain_plan(false) + .await + .unwrap(); + assert!( + !plan.contains("SortExec"), + "scan_in_order(true) must not add a sort, got:\n{plan}" + ); + + // Pin one version so repeated executions describe the same manifest. + let version = table.version().await.unwrap(); + table.checkout(version).await.unwrap(); + for _ in 0..2 { + let batches = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(true) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![0, 1, 2, 3, 4, 5]); + } + + // The default keeps the ordered local behavior. + let batches = table + .query() + .select(Select::columns(&["id"])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![0, 1, 2, 3, 4, 5]); + + // Allowing unordered scans changes no membership. + let mut unordered = collect_i32( + &table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(false) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(), + ); + unordered.sort(); + assert_eq!(unordered, vec![0, 1, 2, 3, 4, 5]); + + // An explicit sort still wins when storage order is not required. + let batches = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(false) + .order_by(Some(vec![ColumnOrdering::desc_nulls_last( + "id".to_string(), + )])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![5, 4, 3, 2, 1, 0]); + + // Deletions keep manifest order, and small output batches plus + // limit/offset must not disturb it. + table.checkout_latest().await.unwrap(); + table.delete("id = 3").await.unwrap(); + let version = table.version().await.unwrap(); + table.checkout(version).await.unwrap(); + let batches = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(true) + .offset(1) + .limit(2) + .execute_with_options(QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert!( + batches.iter().all(|batch| batch.num_rows() <= 1), + "max_batch_length must stay bounded" + ); + assert_eq!(collect_i32(&batches), vec![1, 2]); + } + + #[tokio::test] + async fn test_scan_in_order_rejects_ranked_and_sorted_queries() { + use crate::connect; + use crate::query::ColumnOrdering; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let vector = fixed_size_list_array(vec![0.0, 0.0, 1.0, 0.0, 2.0, 0.0], 2); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("vector", vector.data_type().clone(), false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![Arc::new(Int32Array::from(vec![0, 1, 2])), Arc::new(vector)], + ) + .unwrap(); + let table = conn + .create_table("scan_in_order_conflicts", batch) + .execute() + .await + .unwrap(); + + let err = table + .query() + .scan_in_order(true) + .order_by(Some(vec![ColumnOrdering::asc_nulls_last("id".to_string())])) + .execute() + .await + .err() + .expect("ranked and sorted scans must be rejected"); + assert!( + matches!(&err, Error::InvalidInput { message } + if message.contains("nonempty order_by")), + "unexpected error: {err}" + ); + + let err = table + .query() + .scan_in_order(true) + .nearest_to(vec![0.0f32, 0.0]) + .unwrap() + .execute() + .await + .err() + .expect("ranked scans must be rejected"); + assert!( + matches!(&err, Error::InvalidInput { message } + if message.contains("ranked results")), + "unexpected error: {err}" + ); + } + + #[tokio::test] + async fn test_scan_in_order_with_namespace_pushdown_runs_locally() { + use crate::connect; + use crate::query::ColumnOrdering; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = |ids: Vec| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(ids))]).unwrap() + }; + // Insertion order differs from sorted order so a dropped scan order or + // an accidental sort changes the result. + let table = conn + .create_table("scan_in_order_namespace", batch(vec![3, 1])) + .execute() + .await + .unwrap(); + table.add(batch(vec![2])).execute().await.unwrap(); + + let namespace_client = Arc::new(CountingNamespaceClient::default()); + let mut native_table = table.as_native().unwrap().clone(); + native_table.namespace_client = Some(namespace_client.clone()); + native_table + .pushdown_operations + .insert(NamespaceClientPushdownOperation::QueryTable); + + let query = AnyQuery::Query(QueryRequest { + filter: Some(QueryFilter::Sql("id >= 1".to_string())), + select: Select::columns(&["id"]), + limit: Some(2), + scan_in_order: Some(true), + ..Default::default() + }); + assert!(requires_local_namespace_execution(&query)); + + let batches = execute_query(&native_table, &query, QueryExecutionOptions::default()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![3, 1]); + assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); + + // Allowing unordered scans does not require local execution. + let allow_unordered = AnyQuery::Query(QueryRequest { + scan_in_order: Some(false), + ..Default::default() + }); + assert!(!requires_local_namespace_execution(&allow_unordered)); + + // An explicit sort is already local because the namespace request has + // no order_by field. + let sorted = AnyQuery::Query(QueryRequest { + order_by: Some(vec![ColumnOrdering::asc_nulls_last("id".to_string())]), + ..Default::default() + }); + assert!(requires_local_namespace_execution(&sorted)); + } + + #[tokio::test] + async fn test_scan_in_order_true_rejected_on_rte() { + use crate::connect; + use crate::table::RTEWriteSpec; + use arrow_schema::{DataType, Field, Schema}; + + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![0, 1]))]).unwrap(); + let table = conn + .create_table("scan_in_order_rte", batch) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["id"]).await.unwrap(); + table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap(); + + let err = table + .query() + .scan_in_order(true) + .execute() + .await + .err() + .expect("RTE scans cannot guarantee manifest order"); + assert!( + matches!(&err, Error::NotSupported { message } + if message.contains("scan_in_order(true)") && message.contains("use_rte(false)")), + "unexpected error: {err}" + ); + + // The base table can still be read in storage order explicitly. + let batches = table + .query() + .scan_in_order(true) + .use_rte(false) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![0, 1]); + } } diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index 400df6c82..eddb4d0c0 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -183,6 +183,11 @@ fn reject_unsupported(query: &VectorQueryRequest) -> Result<()> { if query.base.order_by.is_some() { return unsupported("order_by"); } + if query.base.scan_in_order == Some(true) { + return unsupported( + "scan_in_order(true) (the LSM scanner does not preserve base manifest order)", + ); + } // Vector-only knobs the LSM scanner cannot honor. Both change results rather // than just recall, so error instead of silently ignoring them: distance_range // would return rows outside the bound, and use_index(false) asks for a From 87262842e07f600b289019db921527f1ef8997b5 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 05:37:28 +0800 Subject: [PATCH 57/78] docs(function): document GPU row deadline guidance (#5144) Enterprise GPU Functions on 1.13.0 through 1.14.1 and on 1.15.0 builds before the shared 300-second default was restored reject a refresh without an explicit positive `row_timeout_seconds`. The GPU authoring example and the `@function`/`@udf` docstrings now carry the requirement, the definition/request precedence, and sizing guidance. The 600-second value is a working example from the reported workload, not a recommendation. --- docs/web/curation/create-function.mdx | 10 ++++++++++ python/python/lancedb/functions.py | 12 ++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 109846bea..1e26f778f 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -209,6 +209,7 @@ gpu_class = next( @function( gpu=True, gpu_class=gpu_class, + row_timeout_seconds=600, pip=["torch==2.12.0", "sentence-transformers==5.7.0"], input_schema=pa.schema([pa.field("text", pa.string(), nullable=True)]), output_schema=pa.list_(pa.float32(), 384), @@ -231,6 +232,15 @@ table.add_columns({"embedding": version(text=col("caption"))}) ``` +`row_timeout_seconds` sets the per-call deadline, not the `__init__` budget. +Current Enterprise builds default to 300 seconds for both CPU and GPU +Functions. Enterprise 1.13.0 through 1.14.1, and 1.15.0 builds before the +shared default was restored, reject a GPU refresh unless the Function +definition or the refresh request sets a positive value; registration still +succeeds. A refresh value overrides the definition. Size the deadline from the +longest observed call. The 600 seconds above is one working GPU example, not a +universal recommendation. + Older servers that do not implement `GET /v1/gpu/classes` raise `NotImplementedError`. Without `gpu_class`, the deployment's default GPU class is used. The class is immutable with the Function version; set a diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 43226fdf3..18403c75d 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -3724,7 +3724,11 @@ def function( Positive, finite deadline in seconds for each Python call: one row for scalar Functions and one batch for vectorized Functions. This does not govern class initialization. When omitted, the service applies its - default per-call budget. + default per-call budget, currently 300 seconds on Enterprise builds. + Set it for a GPU Function whose longest call can exceed that budget. + Enterprise builds that require an explicit GPU deadline reject a + refresh when neither the definition nor the refresh request sets one; + a refresh value overrides the definition. retry_policy : FunctionRetryPolicy, optional Retry selected failed calls inside the Function, with bounded attempts and backoff. A refresh may override this default. Retrying a partial @@ -3918,7 +3922,11 @@ __all__ = [ def udf(*args: Any, **kwargs: Any) -> Any: - """Deprecated alias of :func:`function`.""" + """Deprecated alias of :func:`function`. + + Accepts the same options, including ``row_timeout_seconds``. See + :func:`function` for GPU deadline guidance. + """ warnings.warn( "lancedb.udf is deprecated; use lancedb.function", DeprecationWarning, From 8b8778938fe0ae214dbc67eb73350078d9cc88ce Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 06:25:05 +0800 Subject: [PATCH 58/78] perf(python): stream plain sync batches on demand (#5143) ## Problem Synchronous local `table.search().to_batches()` creates one Python future per batch through the background event loop. At the default 1024-row cap, a large scan pays that Python round trip thousands of times even though the Rust stream can produce the next batch immediately. ## Change Use a pull-driven synchronous reader for native, non-namespace, ordinary lazy plain scans. The query is executed once with the same `QueryExecutionOptions` as the async path: `None` keeps the 1024-row cap, `0` leaves sizing to the engine, and a positive value caps each returned batch. Each `__next__` releases the GIL, waits for exactly one batch from the same Rust stream through the reviewed `block_on_interruptible`, and stores the stream back on success. - No background producer and no Python `LOOP.run` per batch. - A read error, interrupt, EOF, or the last owner drops the stream. A normal early `break` can resume the same reader. - The public `pa.RecordBatchReader` still comes from `from_batches`, so the schema, Arrow capsule, and exception types stay unchanged. Existing PyArrow `close()` behavior is unchanged; the known PyArrow close issue is separately scoped. - Routing is limited to native, non-namespace, lazy plain scans. Vector, take, FTS/hybrid, remote, namespace, `to_arrow` direct eager routes, and Blob `bytes`/`descriptions` keep their existing paths. Take ordering from #5140 remains on the take path. - Forward explicit `scan_in_order` through the pull launch; base-only ordered `to_batches` results and the incompatible `order_by`/fragment behavior are included in the scan-order suite. - Adds a public RTE `to_batches` regression: the default LSM route sees pending memtable writes, while `use_rte(False)` remains base-only. ## Validation - `test_sync_pull_reader.py`, `test_merge_insert_lsm.py`, and `test_sync_query_direct.py`: 53 passed. - `test_query.py`, `test_blob.py`, and `test_blob_query_without_pylance.py`: 539 passed, 1 skipped. - `test_table.py`: 552 passed, 17 skipped. - `test_remote_db.py -k "to_batches or take"`: 16 passed. - `test_background_loop.py`: 4 passed. - Rust `cargo test --manifest-path python/Cargo.toml --lib sync_stream`: 5 passed. - `cargo check -j 1 --manifest-path python/Cargo.toml --lib --tests` passed; no full Rust doctests were run. A matched same-base release-with-debug streaming comparison is a follow-up and is not claimed here. Tracking: [OSS-2865](https://linear.app/lancedb/issue/OSS-2865) --- python/python/lancedb/_lancedb.pyi | 9 + python/python/lancedb/query.py | 36 ++- python/python/lancedb/table.py | 31 ++ python/python/tests/test_merge_insert_lsm.py | 19 ++ python/python/tests/test_sync_pull_reader.py | 195 ++++++++++++ python/src/lib.rs | 2 + python/src/query.rs | 46 ++- python/src/sync_stream.rs | 298 +++++++++++++++++++ 8 files changed, 628 insertions(+), 8 deletions(-) create mode 100644 python/python/tests/test_sync_pull_reader.py create mode 100644 python/src/sync_stream.rs diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index f40fbc30c..129304f0a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -952,6 +952,12 @@ class RecordBatchStream: def __aiter__(self) -> "RecordBatchStream": ... async def __anext__(self) -> pa.RecordBatch: ... +class SyncRecordBatchStream: + @property + def schema(self) -> pa.Schema: ... + def __iter__(self) -> "SyncRecordBatchStream": ... + def __next__(self) -> pa.RecordBatch: ... + class ColumnOrdering(TypedDict): column_name: str ascending: bool @@ -977,6 +983,9 @@ class Query: async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> RecordBatchStream: ... + def execute_sync( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> SyncRecordBatchStream: ... async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 68598dd68..93f84aeca 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -1850,7 +1850,14 @@ class LanceQueryBuilder(ABC): ) -> pa.RecordBatchReader: query = self._query_for_scan(blob_sources, schema) reader = self._execute_query_prepared( - query, batch_size=batch_size, timeout=timeout + query, + batch_size=batch_size, + timeout=timeout, + pull_reader=( + blob_mode == "lazy" + and _query_is_plain_scan(query) + and not _query_needs_lance_scanner(self) + ), ) return self._batches_in_mode(reader, blob_mode, blob_sources, schema) @@ -1860,9 +1867,19 @@ class LanceQueryBuilder(ABC): *, batch_size: Optional[int] = None, timeout: Optional[timedelta] = None, + pull_reader: bool = False, ) -> pa.RecordBatchReader: if not _is_remote_query_table(self._table): query._blob_row_id_prepared = True + if ( + pull_reader + and not _is_remote_query_table(self._table) + and not self._table.namespace + and getattr(self._table, "_namespace_client", None) is None + ): + return self._table._execute_pull_query( + query, batch_size=batch_size, timeout=timeout + ) return self._table._execute_query(query, batch_size=batch_size, timeout=timeout) def _execute_arrow_prepared( @@ -4933,6 +4950,23 @@ class AsyncQuery(AsyncStandardQuery): super().__init__(inner, table) self._inner = inner + def _execute_batches_sync( + self, + *, + max_batch_length: Optional[int] = None, + timeout: Optional[timedelta] = None, + ) -> pa.RecordBatchReader: + """Execute a plain local scan with one Rust fetch per batch. + + The query starts once; each iteration asks the same Rust stream for a + single batch instead of submitting one Python future per batch to the + background event loop. The public reader type and schema come from the + same stream, so Arrow export and exception behavior stay unchanged. + """ + self._ensure_fragment_constraints_supported("to_batches()") + stream = self._inner.execute_sync(max_batch_length, timeout) + return pa.RecordBatchReader.from_batches(stream.schema, stream) + def scan_in_order(self, ordered: bool = True) -> Self: """Control whether an ordinary scan must preserve storage order. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 529375f6e..c241ab725 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2961,6 +2961,16 @@ class Table(ABC): timeout: Optional[timedelta] = None, ) -> pa.RecordBatchReader: ... + def _execute_pull_query( + self, + query: Query, + *, + batch_size: Optional[int] = None, + timeout: Optional[timedelta] = None, + ) -> pa.RecordBatchReader: + """Execute a pull-driven batch query, falling back to the normal path.""" + return self._execute_query(query, batch_size=batch_size, timeout=timeout) + def _execute_arrow( self, query: Query, @@ -6047,6 +6057,27 @@ class LanceTable(Table): return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync()) + def _execute_pull_query( + self, + query: Query, + *, + batch_size: Optional[int] = None, + timeout: Optional[timedelta] = None, + ) -> pa.RecordBatchReader: + """Execute a plain local scan with one Rust fetch per batch. + + The caller has already checked that this is an embedded, non-namespace + plain lazy scan. A query shape that does not map to ``AsyncQuery`` + keeps the existing reader path instead of guessing at its semantics. + """ + async_query = self._table._sync_query_to_async(query) + async_query._blob_row_id_prepared = query._blob_row_id_prepared + if isinstance(async_query, AsyncQuery): + return async_query._execute_batches_sync( + max_batch_length=batch_size, timeout=timeout + ) + return self._execute_query(query, batch_size=batch_size, timeout=timeout) + def _execute_arrow( self, query: Query, diff --git a/python/python/tests/test_merge_insert_lsm.py b/python/python/tests/test_merge_insert_lsm.py index f5280383c..5b4114112 100644 --- a/python/python/tests/test_merge_insert_lsm.py +++ b/python/python/tests/test_merge_insert_lsm.py @@ -241,6 +241,25 @@ def test_lsm_read_sees_active_memtable(tmp_path): assert sorted(base_only["id"].to_pylist()) == [1, 2, 3] +def test_lsm_read_to_batches_sees_active_memtable(tmp_path): + db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0)) + table = db.create_table("t", _reader([1, 2, 3])) # base ids 1,2,3 + table.set_unenforced_primary_key("id") + table.enable_rte(RTEWriteSpec.unsharded()) + + _lsm_upsert(table, [4, 5]) # active memtable only, not committed to base + + # The sync batch reader keeps the default LSM route and its pending writes. + lsm = pa.Table.from_batches(list(table.search().to_batches(batch_size=2))) + assert sorted(lsm["id"].to_pylist()) == [1, 2, 3, 4, 5] + + # use_rte(False) still takes the base-only escape hatch through to_batches. + base_only = pa.Table.from_batches( + list(table.search().use_rte(False).to_batches(batch_size=2)) + ) + assert sorted(base_only["id"].to_pylist()) == [1, 2, 3] + + def test_lsm_read_dedup_newest_wins(tmp_path): db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0)) table = db.create_table("t", _reader([1, 2, 3])) # id 2 -> value 1 diff --git a/python/python/tests/test_sync_pull_reader.py b/python/python/tests/test_sync_pull_reader.py new file mode 100644 index 000000000..3994b11d2 --- /dev/null +++ b/python/python/tests/test_sync_pull_reader.py @@ -0,0 +1,195 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import gc +import time +from datetime import timedelta + +import pyarrow as pa +import pytest + +import lancedb +import lancedb.table as table_module +from lancedb.query import AsyncQuery + + +def _table(db, name="sync_pull_reader"): + return db.create_table( + name, + data=[{"id": i, "vector": [float(i), float(i)]} for i in range(10)], + ) + + +def _spy_on_pull_reader(monkeypatch): + calls = [] + real = AsyncQuery._execute_batches_sync + + def spy(self, *, max_batch_length=None, timeout=None): + calls.append((max_batch_length, timeout)) + return real(self, max_batch_length=max_batch_length, timeout=timeout) + + monkeypatch.setattr(AsyncQuery, "_execute_batches_sync", spy) + return calls + + +@pytest.mark.parametrize( + "batch_size,row_limit", + [ + (None, 1024), + (0, None), + (4, 4), + ], +) +def test_plain_sync_batches_use_pull_reader(mem_db, monkeypatch, batch_size, row_limit): + table = _table(mem_db) + calls = _spy_on_pull_reader(monkeypatch) + + reader = table.search().select(["id"]).to_batches(batch_size=batch_size) + + assert isinstance(reader, pa.RecordBatchReader) + assert calls == [(batch_size, None)] + batches = list(reader) + assert sum(batch.num_rows for batch in batches) == 10 + assert pa.Table.from_batches(batches).column("id").to_pylist() == list(range(10)) + if row_limit is not None: + assert all(batch.num_rows <= row_limit for batch in batches) + + +def test_scan_in_order_routes_through_pull_reader(tmp_db, monkeypatch): + table = tmp_db.create_table("ordered_pull_reader", pa.table({"id": [0, 1]})) + table.add(pa.table({"id": [2, 3]})) + table.add(pa.table({"id": [4, 5]})) + table.checkout(table.version) + calls = _spy_on_pull_reader(monkeypatch) + + reader = table.search().scan_in_order(True).select(["id"]).to_batches(batch_size=2) + + assert calls == [(2, None)] + assert [value for batch in reader for value in batch["id"].to_pylist()] == [ + 0, + 1, + 2, + 3, + 4, + 5, + ] + with pytest.raises(ValueError, match="nonempty order_by"): + table.search().scan_in_order(True).order_by("id").to_batches() + + +def test_plain_sync_batches_do_not_enter_background_loop(mem_db, monkeypatch): + table = _table(mem_db) + + def fail(*args, **kwargs): + raise AssertionError("plain sync batches entered the background event loop") + + monkeypatch.setattr(table_module.LOOP, "run", fail) + + reader = table.search().select(["id"]).to_batches(batch_size=4) + + assert sum(batch.num_rows for batch in reader) == 10 + + +@pytest.mark.parametrize( + "execute", + [ + lambda table: table.search().select(["id"]).to_arrow(), + lambda table: table.search([0.0, 0.0]).to_batches(), + lambda table: table.take_offsets([0]).to_batches(), + lambda table: table.search().select(["id"]).order_by(["id"]).to_batches(), + lambda table: ( + table.search().select(["id"]).to_batches(blob_mode="descriptions") + ), + ], +) +def test_other_sync_routes_keep_the_existing_reader(mem_db, monkeypatch, execute): + table = _table(mem_db) + calls = _spy_on_pull_reader(monkeypatch) + + execute(table) + + assert calls == [] + + +@pytest.mark.asyncio +async def test_async_batches_keep_the_existing_reader(monkeypatch): + db = await lancedb.connect_async("memory://") + table = await db.create_table( + "async_sync_pull_reader", data=[{"id": i} for i in range(4)] + ) + calls = _spy_on_pull_reader(monkeypatch) + + reader = await table.query().to_batches() + + total_rows = 0 + async for batch in reader: + total_rows += batch.num_rows + assert total_rows == 4 + assert calls == [] + + +def test_timeout_starts_on_first_read_and_spans_reads(tmp_path): + table = lancedb.connect(tmp_path).create_table( + "timeout_pull_reader", data=[{"id": i} for i in range(8)] + ) + reader = ( + table.search() + .select(["id"]) + .to_batches(batch_size=2, timeout=timedelta(milliseconds=200)) + ) + + # A slow consumer before the first poll must not count against the query: + # the timeout starts when the first batch is requested. + time.sleep(0.25) + first = reader.read_next_batch() + assert first.num_rows == 2 + + # The deadline spans reads, so a pause between batches expires it. + time.sleep(0.25) + with pytest.raises(RuntimeError, match="Query timeout"): + reader.read_next_batch() + + +def test_early_break_can_resume_the_same_reader(mem_db): + table = _table(mem_db) + reader = table.search().select(["id"]).to_batches(batch_size=2) + + first = next(iter(reader)) + rest = list(reader) + + assert pa.Table.from_batches([first, *rest]).column("id").to_pylist() == list( + range(10) + ) + + reader = table.search().select(["id"]).to_batches(batch_size=2) + for first in reader: + break + rest = list(reader) + assert pa.Table.from_batches([first, *rest]).column("id").to_pylist() == list( + range(10) + ) + + +def test_arrow_export_shares_cursor_with_the_last_owner(mem_db): + table = _table(mem_db) + reader = table.search().select(["id"]).to_batches(batch_size=2) + first = reader.read_next_batch() + + capsule = reader.__arrow_c_stream__() + del reader + gc.collect() + + imported = pa.RecordBatchReader._import_from_c_capsule(capsule) + rest = imported.read_all() + combined = pa.concat_tables([pa.Table.from_batches([first]), rest]) + assert combined.column("id").to_pylist() == list(range(10)) + + +def test_empty_result_preserves_the_query_schema(mem_db): + table = _table(mem_db) + query = table.search().select(["id"]).where("id < 0") + + reader = query.to_batches(batch_size=4) + + assert reader.schema == query.output_schema() + assert reader.read_all().num_rows == 0 diff --git a/python/src/lib.rs b/python/src/lib.rs index b0698d5e0..a8217d2b1 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -40,6 +40,7 @@ pub mod query; pub mod runtime; pub mod session; pub mod sql; +mod sync_stream; pub mod table; pub mod util; @@ -113,6 +114,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/python/src/query.rs b/python/src/query.rs index d8cfedfdb..f14276d74 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -7,6 +7,7 @@ use std::time::Duration; use crate::expr::PyExpr; use crate::runtime::future_into_py; +use crate::sync_stream::SyncRecordBatchStream; use crate::util::parse_distance_type; use crate::{arrow::RecordBatchStream, util::PyLanceDB}; use crate::{error::PythonErrorExt, index::class_name}; @@ -80,6 +81,20 @@ where Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) } +fn query_execution_options( + max_batch_length: Option, + timeout: Option, +) -> QueryExecutionOptions { + let mut options = QueryExecutionOptions::default(); + if let Some(max_batch_length) = max_batch_length { + options.max_batch_length = max_batch_length; + } + if let Some(timeout) = timeout { + options.timeout = Some(timeout); + } + options +} + impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { type Error = PyErr; @@ -709,18 +724,35 @@ impl Query { ) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { - let mut opts = QueryExecutionOptions::default(); - if let Some(max_batch_length) = max_batch_length { - opts.max_batch_length = max_batch_length; - } - if let Some(timeout) = timeout { - opts.timeout = Some(timeout); - } + let opts = query_execution_options(max_batch_length, timeout); let inner_stream = inner.execute_with_options(opts).await.infer_error()?; Ok(RecordBatchStream::new(inner_stream)) }) } + /// Execute this local query and return a pull-driven synchronous iterator. + /// + /// The query is started once. Each `__next__` fetches exactly one batch + /// from the caller's thread while the GIL is released. `None` keeps the + /// core's default 1024-row output cap, `0` lets the engine choose, and a + /// positive value caps each returned batch. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_sync( + self_: PyRef<'_, Self>, + py: Python<'_>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult { + let inner = self_.inner.clone(); + let opts = query_execution_options(max_batch_length, timeout); + let stream = py.detach(move || { + crate::runtime::block_on_interruptible(async move { + inner.execute_with_options(opts).await.infer_error() + }) + })?; + Ok(SyncRecordBatchStream::new(stream)) + } + /// Execute this query eagerly and return an Arrow C Stream reader. /// /// The returned reader exposes batches already collected in Rust, so diff --git a/python/src/sync_stream.rs b/python/src/sync_stream.rs new file mode 100644 index 000000000..5180f7a73 --- /dev/null +++ b/python/src/sync_stream.rs @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! A pull-driven synchronous reader over a query's record batch stream. +//! +//! The synchronous Python API used to drive one future per batch through the +//! shared background event loop. This reader keeps the stream in Rust and +//! fetches exactly one batch from the caller's thread for each `__next__`, +//! while the caller's GIL is released. +//! +//! The stream is stored only while the reader is idle. Taking it out for a +//! poll means an error, EOF, interrupt, or a dropped last owner releases the +//! execution plan immediately instead of leaving a reader task behind. A +//! successful batch puts the stream back so an early `break` can resume +//! reading from the same cursor. + +use std::sync::Mutex; + +use arrow::datatypes::SchemaRef; +use arrow::pyarrow::{IntoPyArrow, ToPyArrow}; +use arrow::record_batch::RecordBatch; +use futures::StreamExt; +use lancedb::arrow::SendableRecordBatchStream; +use pyo3::{Py, PyAny, PyRef, PyResult, Python, pyclass, pymethods}; + +use crate::error::PythonErrorExt; +use crate::runtime::block_on_interruptible; + +/// Synchronous iterator over the batches of one query execution. +/// +/// Python wraps this in [`pyarrow.RecordBatchReader.from_batches`] so the +/// public return type, schema capsule, and exception types stay the same as +/// the existing sync reader. Creating the iterator does not poll the stream; +/// the first `__next__` starts any configured query timeout. +#[pyclass] +pub struct SyncRecordBatchStream { + schema: SchemaRef, + stream: Mutex>, +} + +impl SyncRecordBatchStream { + pub fn new(stream: SendableRecordBatchStream) -> Self { + let schema = stream.schema(); + Self { + schema, + stream: Mutex::new(Some(stream)), + } + } + + /// Take the stream and hand it to one owned, one-shot read future. + /// + /// The future owns the stream so an interrupt aborts it and drops the + /// execution plan with the future. A successful batch returns the stream + /// to the slot, which keeps an early `break` resumable. EOF and read + /// errors drop the stream before returning. The lock is held only while + /// taking or storing the stream, never while waiting, so another Python + /// thread cannot deadlock against a read that needs the GIL. + fn pull(&mut self) -> PyResult> { + match self.pull_with(|mut stream| { + block_on_interruptible(async move { + let next = stream.next().await; + Ok::<_, pyo3::PyErr>((stream, next)) + }) + })? { + Some(Ok(batch)) => Ok(Some(batch)), + Some(Err(error)) => Err(into_py_error(error)), + None => Ok(None), + } + } + + /// Shared state machine for one pull, with the wait injected for tests. + fn pull_with( + &mut self, + fetch: F, + ) -> Result>, pyo3::PyErr> + where + F: FnOnce( + SendableRecordBatchStream, + ) -> PyResult<( + SendableRecordBatchStream, + Option>, + )>, + { + let Some(stream) = self + .stream + .lock() + .expect("sync reader mutex poisoned") + .take() + else { + return Ok(None); + }; + let (stream, next) = fetch(stream)?; + match next { + Some(Ok(batch)) => { + *self.stream.lock().expect("sync reader mutex poisoned") = Some(stream); + Ok(Some(Ok(batch))) + } + Some(Err(error)) => { + drop(stream); + Ok(Some(Err(error))) + } + None => { + drop(stream); + Ok(None) + } + } + } + + fn release(&self) { + *self.stream.lock().expect("sync reader mutex poisoned") = None; + } +} + +#[pymethods] +impl SyncRecordBatchStream { + #[getter] + pub fn schema(&self, py: Python<'_>) -> PyResult> { + (*self.schema) + .clone() + .into_pyarrow(py) + .map(|obj| obj.unbind()) + } + + fn __iter__(self_: PyRef<'_, Self>) -> PyRef<'_, Self> { + self_ + } + + fn __next__(&mut self, py: Python<'_>) -> PyResult>> { + let batch = py.detach(|| self.pull())?; + let Some(batch) = batch else { + return Ok(None); + }; + let batch = match batch.to_pyarrow(py) { + Ok(batch) => batch, + Err(error) => { + self.release(); + return Err(error); + } + }; + // A signal arriving after the fetch still terminates the reader, so + // no execution plan outlives the KeyboardInterrupt. + if let Err(error) = py.check_signals() { + self.release(); + return Err(error); + } + Ok(Some(batch.unbind())) + } +} + +fn into_py_error(error: lancedb::Error) -> pyo3::PyErr { + match Err::<(), _>(error).infer_error() { + Ok(()) => unreachable!("infer_error returned Ok for an Err value"), + Err(error) => error, + } +} + +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::pin::Pin; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::task::{Context, Poll}; + + use arrow::array::Int32Array; + use arrow::datatypes::{DataType, Field, Schema}; + use futures::Stream; + use lancedb::arrow::RecordBatchStream as LanceRecordBatchStream; + + use super::*; + + struct TestStream { + schema: SchemaRef, + batches: VecDeque>, + polls: Arc, + dropped: Arc, + } + + impl TestStream { + fn new(batches: Vec>) -> Self { + let schema = test_schema(); + Self { + schema, + batches: batches.into(), + polls: Arc::new(AtomicUsize::new(0)), + dropped: Arc::new(AtomicBool::new(false)), + } + } + } + + impl Stream for TestStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + self.polls.fetch_add(1, Ordering::SeqCst); + Poll::Ready(self.batches.pop_front()) + } + } + + impl LanceRecordBatchStream for TestStream { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } + } + + impl Drop for TestStream { + fn drop(&mut self) { + self.dropped.store(true, Ordering::SeqCst); + } + } + + fn test_schema() -> SchemaRef { + Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])) + } + + fn test_batch(value: i32) -> RecordBatch { + RecordBatch::try_new(test_schema(), vec![Arc::new(Int32Array::from(vec![value]))]).unwrap() + } + + fn boxed(stream: TestStream) -> SendableRecordBatchStream { + Box::pin(stream) + } + + fn pull_fake( + reader: &mut SyncRecordBatchStream, + ) -> Result>, pyo3::PyErr> { + reader.pull_with(|mut stream| { + let next = futures::executor::block_on(stream.next()); + Ok((stream, next)) + }) + } + + #[test] + fn creation_does_not_poll() { + let stream = TestStream::new(vec![Ok(test_batch(1))]); + let polls = Arc::clone(&stream.polls); + let _reader = SyncRecordBatchStream::new(boxed(stream)); + assert_eq!(polls.load(Ordering::SeqCst), 0); + } + + #[test] + fn one_pull_reads_one_batch_and_keeps_the_stream_resumable() { + let stream = TestStream::new(vec![ + Ok(test_batch(1)), + Ok(test_batch(2)), + Ok(test_batch(3)), + ]); + let polls = Arc::clone(&stream.polls); + let dropped = Arc::clone(&stream.dropped); + let mut reader = SyncRecordBatchStream::new(boxed(stream)); + + assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok()); + assert_eq!(polls.load(Ordering::SeqCst), 1); + assert!(!dropped.load(Ordering::SeqCst)); + + assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok()); + assert_eq!(polls.load(Ordering::SeqCst), 2); + assert!(!dropped.load(Ordering::SeqCst)); + } + + #[test] + fn eof_drops_the_stream_before_returning() { + let stream = TestStream::new(vec![Ok(test_batch(1))]); + let dropped = Arc::clone(&stream.dropped); + let mut reader = SyncRecordBatchStream::new(boxed(stream)); + + assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok()); + assert!(!dropped.load(Ordering::SeqCst)); + assert!(pull_fake(&mut reader).unwrap().is_none()); + assert!(dropped.load(Ordering::SeqCst)); + assert!(pull_fake(&mut reader).unwrap().is_none()); + } + + #[test] + fn error_drops_the_stream_before_returning() { + let stream = TestStream::new(vec![Err(lancedb::Error::Runtime { + message: "read failed".to_string(), + })]); + let dropped = Arc::clone(&stream.dropped); + let mut reader = SyncRecordBatchStream::new(boxed(stream)); + + assert!(pull_fake(&mut reader).unwrap().unwrap().is_err()); + assert!(dropped.load(Ordering::SeqCst)); + assert!(pull_fake(&mut reader).unwrap().is_none()); + } + + #[test] + fn dropping_an_unread_reader_drops_the_stream_without_polling() { + let stream = TestStream::new(vec![Ok(test_batch(1))]); + let polls = Arc::clone(&stream.polls); + let dropped = Arc::clone(&stream.dropped); + let reader = SyncRecordBatchStream::new(boxed(stream)); + + drop(reader); + assert_eq!(polls.load(Ordering::SeqCst), 0); + assert!(dropped.load(Ordering::SeqCst)); + } +} From 8fd1c716d9af7cada88503750b4d911f34b775e2 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 06:27:27 +0800 Subject: [PATCH 59/78] feat(python): persist permutation plans and reopen pinned snapshots (#5137) ## Summary Add `permutation_builder(base).persist(db, table_name, *, namespace_path=None, mode="create").execute()` for embedded local and object-store destinations. The native create request carries the namespace and create/overwrite mode, with no drop-before-create. The returned table keeps the destination connection context so it can be pickled and reopened directly, including namespaced and manifest-enabled connections. Persisted plans pickle by reference to their own branch and version, so a later overwrite or cross-branch checkout does not change what an existing pickle reads. In-memory plans, old serialized state, and shallow copies keep their existing behavior. `Permutation.base_version` and `base_branch` expose the recorded base snapshot from loaded metadata. Enterprise destinations remain rejected in v1 because reproducible remote plan ordering is follow-up work. ## Verification - `test_permutation.py`: 93 passed. - `test_torch.py`: 23 passed in a compatible torch 2.15 / NumPy 2.2 / PyArrow 26 environment using the abi3 extension. - S3 direct-result persistence/pickle test passed against a disposable loopback Moto server using the existing fixture's fake keys and explicit storage options. - Earlier targeted checks predate the live snapshot pin repair: Rust builder tests 12 passed; Rust check/clippy and Node type-check passed. - The live snapshot pin repair added private PyO3 glue and was verified with a rebuilt extension: `test_permutation.py` 93 passed, `test_torch.py` 23 passed, and one loopback S3 direct-result test passed. - `ruff format --check`, `ruff check`, `pyright`, `git diff --check`: passed. --- docs/web/training/permutation.mdx | 36 +++ python/python/lancedb/_lancedb.pyi | 9 + python/python/lancedb/permutation.py | 266 ++++++++++++++-- python/python/lancedb/table.py | 48 ++- python/python/tests/test_permutation.py | 290 +++++++++++++++++- python/python/tests/test_s3.py | 31 ++ python/src/permutation.rs | 38 ++- python/src/table.rs | 9 + .../src/dataloader/permutation/builder.rs | 164 +++++++++- 9 files changed, 844 insertions(+), 47 deletions(-) diff --git a/docs/web/training/permutation.mdx b/docs/web/training/permutation.mdx index 0da10f947..952341ea9 100644 --- a/docs/web/training/permutation.mdx +++ b/docs/web/training/permutation.mdx @@ -29,6 +29,42 @@ In specific use cases, you may need the flexibility to shuffle, split, and selec functionality `StreamingDataset` is built on. A `Permutation` defines a customizable row ordering, and supports map-style access through `__getitem__()` and batched access through `__getitems__()`. +## Persisting a permutation {#persisting} + +By default a permutation table is stored in memory. Call `persist` before `execute` to write it to an embedded +LanceDB connection backed by local files or object storage. The plan becomes an ordinary table, so another process +with access to the same storage can open it and use `Permutation.from_tables` to read the same split. + + +```py Python icon=Python +from lancedb.permutation import Permutation, permutation_builder + +db = lancedb.connect("file://some/db/path") +table = db.open_table("some_table") +plan = ( + permutation_builder(table) + .split_random(ratios=[0.8, 0.2], seed=42, split_names=["train", "validation"]) + .persist(db, "splits_v1") + .execute() +) +train = Permutation.from_tables(table, db.open_table("splits_v1"), split="train") +print(train.base_version, train.base_branch) +``` + + +The table returned by `execute` keeps the destination connection and namespace context, so it can be pickled and +reopened directly in a worker process. + +`mode="create"` is the default and fails when the destination table already exists. Pass `mode="overwrite"` to +replace it explicitly. Overwriting writes a new table version; readers that already opened the previous version keep +reading that snapshot. Use `namespace_path` to create the plan in a namespace. Persisting to LanceDB Enterprise +connections is not supported yet, because reproducible Enterprise plan ordering requires deterministic remote row +ordering. + +The plan records the base table version and branch in its schema metadata. `Permutation.base_version` and +`Permutation.base_branch` read those values without querying the base table; both are `None` for older plans that did +not record them. + ## Version Pinning {#version-pinning} A `Permutation` is pinned to the version of its base table at the time it was constructed, and every read (including future reads diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 129304f0a..82b2a3513 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -651,6 +651,7 @@ class Table: async def version(self) -> int: ... async def checkout(self, version: Union[int, str]): ... async def checkout_latest(self): ... + async def _checkout_current(self) -> Table: ... async def restore(self, version: Optional[Union[int, str]] = None): ... async def prewarm_index(self, index_name: str) -> None: ... async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: ... @@ -1356,6 +1357,14 @@ class AsyncPermutationBuilder: self, seed: Optional[int], clump_size: Optional[int] ) -> "AsyncPermutationBuilder": ... def filter(self, filter: str) -> "AsyncPermutationBuilder": ... + def persist( + self, + db: Connection, + table_name: str, + *, + namespace_path: Optional[List[str]] = None, + mode: str = "create", + ) -> "AsyncPermutationBuilder": ... async def execute(self) -> Table: ... def async_permutation_builder( diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index 2a45f4cc4..0369ccec5 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -8,6 +8,7 @@ import os from deprecation import deprecated import pyarrow as pa +from ._lancedb import Connection as NativeConnection from ._lancedb import async_permutation_builder, PermutationReader from .table import LanceTable, Table from .background_loop import LOOP @@ -16,11 +17,26 @@ from .util import ( batch_to_tensor_columns, batch_to_tensor_dict, batch_to_tensor_rows, + get_uri_scheme, ) from typing import Any, Callable, Iterator, Literal, Optional, TYPE_CHECKING, Union if TYPE_CHECKING: from lancedb.dependencies import pandas as pd, numpy as np, polars as pl + from .db import DBConnection + + +def _native_connection(db: Any) -> Any: + """Return the native connection wrapped by a sync or async connection.""" + async_connection = getattr(db, "_conn", None) + if async_connection is not None: + return _native_connection(async_connection) + inner = getattr(db, "_inner", None) + if inner is not None: + return _native_connection(inner) + if isinstance(db, NativeConnection): + return db + raise TypeError("db must be a LanceDB connection") class PermutationBuilder: @@ -43,7 +59,9 @@ class PermutationBuilder: be referenced by name in the future. If names are not provided then they can only be referenced by their ordinal index. There is no requirement to name every split. - The permutation is stored in memory and will be lost when the program exits. + The permutation is stored in memory and will be lost when the program exits, + unless [persist][lancedb.permutation.PermutationBuilder.persist] is called before + [execute][lancedb.permutation.PermutationBuilder.execute]. """ def __init__(self, table: Table): @@ -56,6 +74,9 @@ class PermutationBuilder: Tables with an RTE write spec are rejected: unflushed rows have no row id. """ self._async = async_permutation_builder(table) + self._persist_connection: Optional[Any] = None + self._persist_table_name: Optional[str] = None + self._persist_namespace_path: list[str] = [] def split_random( self, @@ -262,6 +283,76 @@ class PermutationBuilder: self._async.filter(filter) return self + def persist( + self, + db: "DBConnection", + table_name: str, + *, + namespace_path: Optional[list[str]] = None, + mode: Literal["create", "overwrite"] = "create", + ) -> "PermutationBuilder": + """ + Store the permutation table in an embedded database. + + Persisting a plan makes the same split available to another process or + another machine with access to the destination storage. The plan is an + ordinary LanceDB table containing row ids and split ids; it can be + opened with [open_table][lancedb.db.DBConnection.open_table] and passed to + [Permutation.from_tables][lancedb.permutation.Permutation.from_tables]. + The table returned by ``execute`` keeps the destination connection and + namespace context, so it can be pickled and reopened directly. + + Parameters + ---------- + db: DBConnection + An embedded LanceDB connection. Local files and object storage are + supported; LanceDB Enterprise connections are not supported yet. + table_name: str + The name of the permutation table to create. + namespace_path: list[str], optional + The namespace to create the table in. The default is the root + namespace. + mode: {"create", "overwrite"}, default "create" + ``create`` fails if the destination table already exists. + ``overwrite`` writes a new version of the table. Readers that already + opened the previous version keep reading that snapshot. + + Returns + ------- + PermutationBuilder + This builder, so ``persist`` can be chained with the split, filter, + and execute methods. + """ + if mode not in ("create", "overwrite"): + raise ValueError(f"Invalid mode {mode!r}; expected 'create' or 'overwrite'") + + uri = getattr(db, "uri", None) + if uri is None: + raise TypeError("db must be a LanceDB connection") + if get_uri_scheme(str(uri)) == "db": + raise NotImplementedError( + "Permutation persistence is not supported for LanceDB Enterprise " + "connections yet; reproducible Enterprise plan ordering requires " + "deterministic remote row ordering." + ) + + if namespace_path is None: + namespace_path = [] + elif not isinstance(namespace_path, (list, tuple)): + raise TypeError("namespace_path must be a list of strings or None") + + namespace_path = list(namespace_path) + self._async.persist( + _native_connection(db), + table_name, + namespace_path=namespace_path, + mode=mode, + ) + self._persist_connection = db + self._persist_table_name = table_name + self._persist_namespace_path = namespace_path + return self + def execute(self) -> LanceTable: """ Execute the configuration and create the permutation table. @@ -269,7 +360,14 @@ class PermutationBuilder: async def do_execute(): inner_tbl = await self._async.execute() - return await LanceTable.from_inner(inner_tbl) + if self._persist_connection is None: + return await LanceTable.from_inner(inner_tbl) + return await LanceTable.from_inner( + inner_tbl, + connection=self._persist_connection, + name=self._persist_table_name, + namespace_path=self._persist_namespace_path, + ) return LOOP.run(do_execute()) @@ -411,6 +509,11 @@ class Transforms: DEFAULT_BATCH_SIZE = 100 +def _is_persisted_plan(table: Table) -> bool: + """Whether a permutation table lives in reopenable storage rather than memory.""" + return isinstance(table, LanceTable) and not table._conn.uri.startswith("memory://") + + def _table_to_pickle_state(table: Table) -> dict[str, Any]: from .remote.table import RemoteTable @@ -497,6 +600,9 @@ class Permutation: limit: Optional[int] = None, connection_factory: Optional[Callable[[str], Table]] = None, _reader: Optional[PermutationReader] = None, + _plan_metadata: Optional[dict[bytes, bytes]] = None, + _plan_version: Optional[int] = None, + _plan_branch: Optional[str] = None, ): """ Internal constructor. Use @@ -513,6 +619,9 @@ class Permutation: self.offset = offset self.limit = limit self.connection_factory = connection_factory + self._plan_metadata = _plan_metadata + self._plan_version = _plan_version + self._plan_branch = _plan_branch if _reader is None: _reader = LOOP.run(self._build_reader()) self.reader: PermutationReader = _reader @@ -652,6 +761,17 @@ class Permutation: then the first split will be used. """ assert base_table is not None, "base_table is required" + persisted_plan = permutation_table is not None and _is_persisted_plan( + permutation_table + ) + if persisted_plan: + # Pin before reading metadata or constructing the reader. The caller's + # handle may keep tracking latest, but the live reader and pickle must + # share one immutable plan snapshot. + permutation_table = permutation_table._pin_current_snapshot() + plan_metadata = None if permutation_table is not None else {} + if permutation_table is not None and (isinstance(split, str) or persisted_plan): + plan_metadata = dict(permutation_table.schema.metadata or {}) if split is not None: if permutation_table is None: raise ValueError( @@ -659,12 +779,7 @@ class Permutation: " because no permutation table is provided" ) if isinstance(split, str): - if permutation_table.schema.metadata is None: - raise ValueError( - f"Cannot create a permutation on split `{split}`" - " because no split names are defined in the permutation table" - ) - raw = permutation_table.schema.metadata.get(b"split_names") + raw = (plan_metadata or {}).get(b"split_names") split_names = raw.decode("utf-8") if raw is not None else None if split_names is None: raise ValueError( @@ -687,6 +802,14 @@ class Permutation: else: split = 0 + plan_version = None + plan_branch = None + if persisted_plan: + # Pin the pickled plan to the snapshot this object was created from, + # not what the destination name points at after an overwrite. + plan_version = permutation_table.version + plan_branch = permutation_table.current_branch() + async def do_from_tables(): reader = await PermutationReader.from_tables( base_table, permutation_table, split @@ -701,6 +824,9 @@ class Permutation: DEFAULT_BATCH_SIZE, Transforms.arrow2python, _reader=reader, + _plan_metadata=plan_metadata, + _plan_version=plan_version, + _plan_branch=plan_branch, ) return LOOP.run(do_from_tables()) @@ -710,18 +836,43 @@ class Permutation: The base table is captured either via a user-supplied ``connection_factory`` (see [with_connection_factory]) or, as a - fallback, by the table's own picklable reopen state. The permutation - table is captured as a pyarrow Table (which pickles via Arrow IPC - natively). The reader is dropped from the wire format and rebuilt - lazily on first use. + fallback, by the table's own picklable reopen state. A permutation + table in memory is captured as a pyarrow Table (which pickles via Arrow + IPC natively). A persisted plan is reopened by reference and pinned to + the plan snapshot this object was built from. The reader is dropped + from the wire format and rebuilt lazily on first use. """ + base_table_state = ( + None + if self.connection_factory is not None + else _table_to_pickle_state(self.base_table) + ) + base_is_memory = ( + base_table_state is not None and base_table_state["kind"] == "memory" + ) + permutation_data: Optional[pa.Table] = None - if self.permutation_table is not None: + permutation_table_state: Optional[dict[str, Any]] = None + if ( + self.permutation_table is not None + and _is_persisted_plan(self.permutation_table) + and not base_is_memory + ): + plan_state = _table_to_pickle_state(self.permutation_table) + # Keep the plan's own branch/version coordinate. A later overwrite + # of the destination must not change what this pickle reads. + table_state = plan_state["state"] + if self._plan_version is not None: + table_state["checkout_version"] = self._plan_version + # None is the main branch. Restore it explicitly because the + # live handle may have moved to another branch since capture. + table_state["branch"] = self._plan_branch + permutation_table_state = plan_state + elif self.permutation_table is not None: permutation_data = self.permutation_table.to_arrow() common = { "base_table_name": self.base_table.name, - "permutation_data": permutation_data, "split": self.split, "selection": self.selection, "batch_size": self.batch_size, @@ -730,17 +881,13 @@ class Permutation: "limit": self.limit, "connection_factory": self.connection_factory, } - - if self.connection_factory is not None: - # The factory carries enough state to recover the base table on - # its own; we don't need to capture the URI / storage options / - # namespace from the existing connection. - return common - - return { - **common, - "base_table_state": _table_to_pickle_state(self.base_table), - } + if permutation_table_state is not None: + common["permutation_table_state"] = permutation_table_state + else: + common["permutation_data"] = permutation_data + if base_table_state is not None: + common["base_table_state"] = base_table_state + return common def __setstate__(self, state: dict[str, Any]) -> None: from . import connect @@ -772,17 +919,32 @@ class Permutation: ) permutation_table: Optional[Table] = None - permutation_data = state["permutation_data"] - if permutation_data is not None: - if rebuilt_base: - # The base table was materialized from Arrow, so it is a fresh - # single-version dataset and the recorded pin cannot resolve on it. - permutation_data = _drop_base_version(permutation_data) - mem_db = connect("memory://") - permutation_table = mem_db.create_table("permutation", permutation_data) + plan_metadata: dict[bytes, bytes] = {} + plan_version = None + plan_branch = None + if "permutation_table_state" in state: + plan_state = state["permutation_table_state"] + permutation_table = _table_from_pickle_state(plan_state) + nested_state = plan_state.get("state", {}) + plan_version = nested_state.get("checkout_version") + plan_branch = nested_state.get("branch") + plan_metadata = dict(permutation_table.schema.metadata or {}) + else: + permutation_data = state.get("permutation_data") + if permutation_data is not None: + if rebuilt_base: + # The base table was materialized from Arrow, so it is a fresh + # single-version dataset and the recorded pin cannot resolve on it. + permutation_data = _drop_base_version(permutation_data) + mem_db = connect("memory://") + permutation_table = mem_db.create_table("permutation", permutation_data) + plan_metadata = dict(permutation_table.schema.metadata or {}) self.base_table = base_table self.permutation_table = permutation_table + self._plan_metadata = plan_metadata + self._plan_version = plan_version + self._plan_branch = plan_branch self.split = state["split"] self.selection = state["selection"] self.batch_size = state["batch_size"] @@ -807,6 +969,44 @@ class Permutation: new.__dict__ = self.__dict__.copy() return new + def _loaded_plan_metadata(self) -> dict[bytes, bytes]: + if self._plan_metadata is None: + self._plan_metadata = ( + dict(self.permutation_table.schema.metadata or {}) + if self.permutation_table is not None + else {} + ) + return self._plan_metadata + + @property + def base_version(self) -> Optional[int]: + """The base table version recorded in the plan, or ``None`` for legacy plans. + + This value comes from the plan's schema metadata, so reading it does not + query the base table. Version numbers are per-branch; see + [base_branch][lancedb.permutation.Permutation.base_branch]. + """ + raw = self._loaded_plan_metadata().get(b"base_version") + if raw is None: + return None + try: + return int(raw) + except ValueError as error: + raise ValueError( + f"Permutation table has an unreadable base_version of {raw!r}" + ) from error + + @property + def base_branch(self) -> Optional[str]: + """The base table branch recorded in the plan, or ``None`` for main. + + Legacy plans recorded no branch and therefore also return ``None``. + """ + raw = self._loaded_plan_metadata().get(b"base_branch") + if raw is None: + return None + return raw.decode("utf-8") + def _ensure_open(self) -> None: pid = os.getpid() if self.reader is not None and getattr(self, "_pid", None) == pid: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index c241ab725..57588948f 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -4437,10 +4437,40 @@ class LanceTable(Table): return self._namespace_path @classmethod - async def from_inner(cls, tbl: LanceDBTable): + async def from_inner( + cls, + tbl: LanceDBTable, + *, + connection: Optional["DBConnection"] = None, + name: Optional[str] = None, + namespace_path: Optional[List[str]] = None, + location: Optional[str] = None, + ): + async_tbl = AsyncTable(tbl) + if connection is not None: + # A table created through a Python connection keeps that + # connection's explicit options. Reconstructing a bare connection + # from the native handle loses namespace, storage, manifest and + # Session state needed by pickle. + return cls( + connection, + name or async_tbl.name, + namespace_path=namespace_path, + storage_options=getattr(connection, "storage_options", None), + location=location, + namespace_client=getattr(connection, "_namespace_client", None), + managed_versioning=getattr(connection, "_managed_versioning", None), + pushdown_operations=getattr( + connection, "_namespace_client_pushdown_operations", None + ), + route_pushdown_to_rust=getattr( + connection, "_route_pushdown_to_rust", False + ), + _async=async_tbl, + ) + from .db import AsyncConnection, LanceDBConnection - async_tbl = AsyncTable(tbl) inner_conn = tbl.database() read_consistency_interval = await AsyncConnection( inner_conn @@ -4670,6 +4700,16 @@ class LanceTable(Table): """The branch this table handle is scoped to, or ``None`` for ``main``.""" return self._table.current_branch() + def _pin_current_snapshot(self) -> "LanceTable": + """Return an independent handle pinned to this table's current snapshot.""" + + async def do_pin(): + pinned = await self._table._checkout_current() + return pinned, await pinned.version() + + pinned, version = LOOP.run(do_pin()) + return self._wrap_branch_handle(pinned, version) + def _wrap_branch_handle( self, async_table: "AsyncTable", version: Optional[int] = None ) -> "LanceTable": @@ -9664,6 +9704,10 @@ class AsyncTable: """ return await self._inner.version() + async def _checkout_current(self) -> "AsyncTable": + """Return an independent handle pinned to the currently selected snapshot.""" + return AsyncTable(await self._inner._checkout_current()) + async def list_versions(self): """ List all versions of the table diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 4a4c54a56..22df4570c 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -5,7 +5,7 @@ import pyarrow as pa import math import pytest -from lancedb import DBConnection, Table, connect +from lancedb import DBConnection, Session, Table, connect, connect_namespace from lancedb.background_loop import LOOP from lancedb.permutation import ( DEFAULT_BATCH_SIZE, @@ -21,6 +21,18 @@ from utils import ( ) +def _read_permutation_in_spawned_process(payload: bytes, output) -> None: + import pickle + + permutation = pickle.loads(payload) + output.put( + [ + row["id"] + for row in permutation.__getitems__(list(range(permutation.num_rows))) + ] + ) + + def test_split_random_ratios(mem_db): """Test random splitting with ratios.""" tbl = mem_db.create_table( @@ -87,6 +99,282 @@ def test_pickled_permutation_reads_pinned_version(tmp_path): assert sorted(row["idx"] for row in rows) == list(range(20)) +def test_persist_plan_create_overwrite_namespace_and_metadata(tmp_path): + import pickle + + db = connect(tmp_path) + tbl = db.create_table("base", pa.table({"id": range(20)})) + db.create_namespace(["plans"]) + namespace_path = ["plans"] + + plan = ( + permutation_builder(tbl) + .split_sequential(fixed=2, split_names=["train", "test"]) + .persist(db, "splits", namespace_path=namespace_path) + .execute() + ) + assert plan.count_rows() == 20 + assert plan.namespace == namespace_path + assert pickle.loads(pickle.dumps(plan)).namespace == namespace_path + + permutation = Permutation.from_tables(tbl, plan, split="train") + assert permutation.base_version == tbl.version + assert permutation.base_branch is None + assert permutation.num_rows == 10 + + with pytest.raises((ValueError, RuntimeError), match="already exists"): + ( + permutation_builder(tbl) + .split_sequential(fixed=2) + .persist(db, "splits", namespace_path=namespace_path) + .execute() + ) + + with pytest.raises(ValueError, match="Invalid mode"): + permutation_builder(tbl).persist(db, "other", mode="replace") + + class RemoteLike: + uri = "db://example" + + with pytest.raises(NotImplementedError, match="Enterprise"): + permutation_builder(tbl).persist(RemoteLike(), "remote_splits") + + tbl.add(pa.table({"id": range(20, 40)})) + plan = ( + permutation_builder(tbl) + .split_sequential(fixed=2) + .persist(db, "splits", namespace_path=namespace_path, mode="overwrite") + .execute() + ) + assert plan.count_rows() == 40 + assert db.open_table("splits", namespace_path=namespace_path).count_rows() == 40 + # The earlier permutation still reads the plan and base snapshot it was built from. + assert permutation.num_rows == 10 + assert [row["id"] for row in permutation.__getitems__([0, 1])] == [0, 1] + + +def test_persist_namespace_connection_direct_result_pickle(tmp_path): + import pickle + + db = connect_namespace("dir", {"root": str(tmp_path)}) + db.create_namespace(["plans"]) + tbl = db.create_table("base", pa.table({"id": range(20)})) + + plan = ( + permutation_builder(tbl) + .split_sequential(fixed=2, split_names=["train", "test"]) + .persist(db, "splits", namespace_path=["plans"]) + .execute() + ) + assert plan.namespace == ["plans"] + assert plan._conn is db + + restored_plan = pickle.loads(pickle.dumps(plan)) + assert restored_plan.namespace == ["plans"] + assert restored_plan.count_rows() == 20 + + permutation = Permutation.from_tables(tbl, plan, split="train") + restored = pickle.loads(pickle.dumps(permutation)) + assert restored.num_rows == 10 + assert sorted( + row["id"] for row in restored.__getitems__(list(range(restored.num_rows))) + ) == list(range(10)) + + +def test_persist_direct_result_keeps_session_pickle_error(tmp_path): + import pickle + + db = connect(tmp_path, session=Session()) + tbl = db.create_table("base", pa.table({"id": range(5)})) + plan = permutation_builder(tbl).persist(db, "splits").execute() + + with pytest.raises(TypeError, match="Session"): + pickle.dumps(plan) + + permutation = Permutation.from_tables(tbl, plan) + with pytest.raises(TypeError, match="Session"): + pickle.dumps(permutation) + + +def test_persist_direct_result_preserves_manifest_connection_state(tmp_path): + import pickle + + db = connect(tmp_path, manifest_enabled=True) + tbl = db.create_table("base", pa.table({"id": range(5)})) + plan = permutation_builder(tbl).persist(db, "splits").execute() + + restored = pickle.loads(pickle.dumps(plan)) + assert restored._conn._manifest_enabled is True + assert restored.count_rows() == 5 + + +def test_base_branch_property_reads_plan_metadata(tmp_path): + db = connect(tmp_path) + tbl = db.create_table("base", pa.table({"id": range(10)})) + branch = tbl.branches.create("exp") + branch.add(pa.table({"id": range(10, 20)})) + + plan = permutation_builder(branch).persist(db, "branch_splits").execute() + permutation = Permutation.from_tables(branch, plan) + + assert permutation.base_branch == "exp" + assert permutation.base_version == branch.version + assert permutation.num_rows == 20 + + +def test_persisted_plan_pickle_reopens_same_snapshot_after_overwrite(tmp_path): + from datetime import timedelta + import pickle + + db = connect(tmp_path, read_consistency_interval=timedelta(0)) + tbl = db.create_table("base", pa.table({"id": range(20)})) + plan = permutation_builder(tbl).filter("id < 10").persist(db, "splits").execute() + permutation = Permutation.from_tables(tbl, plan) + old_base_version = permutation.base_version + old_plan_version = permutation._plan_version + state = permutation.__getstate__() + assert "permutation_data" not in state + assert ( + state["permutation_table_state"]["state"]["checkout_version"] + == old_plan_version + ) + + # Replace the plan with disjoint rows of the same cardinality. + permutation_builder(tbl).filter("id >= 10").persist( + db, "splits", mode="overwrite" + ).execute() + assert plan.version == old_plan_version + 1 + assert permutation.permutation_table.version == old_plan_version + + live_ids = [ + row["id"] for row in permutation.__getitems__(list(range(permutation.num_rows))) + ] + assert live_ids == list(range(10)) + + # A reader recreated after the overwrite must still use the pinned snapshot. + permutation.reader = None + permutation._pid = None + recreated_ids = [ + row["id"] for row in permutation.__getitems__(list(range(permutation.num_rows))) + ] + assert recreated_ids == list(range(10)) + + restored = pickle.loads(pickle.dumps(permutation)) + assert restored.base_version == old_base_version + restored_ids = [ + row["id"] for row in restored.__getitems__(list(range(restored.num_rows))) + ] + assert restored_ids == list(range(10)) + + # A newly constructed permutation sees the overwritten plan. + fresh = Permutation.from_tables(tbl, db.open_table("splits")) + assert fresh.base_version == old_base_version + fresh_ids = [row["id"] for row in fresh.__getitems__(list(range(fresh.num_rows)))] + assert fresh_ids == list(range(10, 20)) + + +def test_persisted_plan_pickle_uses_captured_main_branch(tmp_path): + import pickle + + db = connect(tmp_path) + tbl = db.create_table("base", pa.table({"id": range(20)})) + permutation_builder(tbl).persist(db, "splits").execute() + + initial_plan = db.open_table("splits") + initial_plan.branches.create("exp", from_version=1) + + # Main plan version 2 still has all 20 rows. + permutation_builder(tbl).persist(db, "splits", mode="overwrite").execute() + main_plan = db.open_table("splits") + assert main_plan.version == 2 + + # Branch plan version 2 has different contents, so the numeric version alone + # does not identify the snapshot. + branch_plan = db.open_table("splits", branch="exp") + branch_plan.add( + pa.table( + { + "row_id": pa.array([0], type=pa.uint64()), + "split_id": pa.array([0], type=pa.uint32()), + } + ) + ) + branch_plan = db.open_table("splits", branch="exp") + assert branch_plan.version == 2 + assert branch_plan.count_rows() == 21 + branch_plan.tags.create("exp_v2", 2) + + permutation = Permutation.from_tables(tbl, main_plan) + + # Move the same passed-in plan handle to the other branch at the same + # numeric version. Pickle must still reopen the captured main snapshot. + main_plan.checkout("exp_v2") + assert main_plan.current_branch() == "exp" + assert main_plan.version == 2 + payload = pickle.dumps(permutation) + + restored = pickle.loads(payload) + assert restored.permutation_table.current_branch() is None + assert restored.permutation_table.version == 2 + assert restored.num_rows == 20 + + +def test_persisted_plan_pickle_reopens_in_spawned_process(tmp_path): + import multiprocessing as mp + import pickle + + db = connect(tmp_path) + tbl = db.create_table("base", pa.table({"id": range(12)})) + plan = permutation_builder(tbl).persist(db, "splits").execute() + payload = pickle.dumps(Permutation.from_tables(tbl, plan)) + + tbl.add(pa.table({"id": range(12, 24)})) + permutation_builder(tbl).persist(db, "splits", mode="overwrite").execute() + + context = mp.get_context("spawn") + output = context.Queue() + process = context.Process( + target=_read_permutation_in_spawned_process, args=(payload, output) + ) + process.start() + try: + ids = output.get(timeout=60) + finally: + process.join(timeout=60) + + assert process.exitcode == 0 + assert sorted(ids) == list(range(12)) + + +def test_old_permutation_pickle_state_still_round_trips(tmp_path): + db = connect(tmp_path) + tbl = db.create_table("base", pa.table({"id": range(20)})) + plan = permutation_builder(tbl).execute() + state = { + "base_table_name": tbl.name, + "permutation_data": plan.to_arrow(), + "split": 0, + "selection": {"id": "id"}, + "batch_size": DEFAULT_BATCH_SIZE, + "transform_fn": Transforms.arrow2python, + "offset": None, + "limit": None, + "connection_factory": None, + "base_table_uri": str(tmp_path), + "base_table_storage_options": None, + "base_table_namespace": [], + } + + restored = Permutation.__new__(Permutation) + restored.__setstate__(state) + + assert restored.base_version == tbl.version + assert restored.base_branch is None + assert sorted( + row["id"] for row in restored.__getitems__(list(range(restored.num_rows))) + ) == list(range(20)) + + def test_builder_copy_is_shallow_and_does_not_materialize( some_table: Table, some_perm_table: Table, monkeypatch ): diff --git a/python/python/tests/test_s3.py b/python/python/tests/test_s3.py index 70b423adb..348f0ea78 100644 --- a/python/python/tests/test_s3.py +++ b/python/python/tests/test_s3.py @@ -11,6 +11,7 @@ import threading import pytest import pyarrow as pa import lancedb +from lancedb.permutation import Permutation, permutation_builder # These are all keys that are accepted by storage_options @@ -87,6 +88,36 @@ def test_s3_lifecycle(s3_bucket: str): asyncio.run(test()) +@pytest.mark.s3_test +def test_s3_permutation_persist_direct_result_pickle(s3_bucket: str): + import pickle + + storage_options = copy.copy(CONFIG) + uri = f"s3://{s3_bucket}/test_permutation_persist" + db = lancedb.connect(uri, storage_options=storage_options) + try: + tbl = db.create_table("base", pa.table({"id": range(20)})) + plan = ( + permutation_builder(tbl) + .split_sequential(fixed=2, split_names=["train", "test"]) + .persist(db, "splits") + .execute() + ) + assert plan._storage_options == storage_options + + restored_plan = pickle.loads(pickle.dumps(plan)) + assert restored_plan.count_rows() == 20 + + permutation = Permutation.from_tables(tbl, plan, split="train") + restored = pickle.loads(pickle.dumps(permutation)) + assert restored.num_rows == 10 + assert sorted( + row["id"] for row in restored.__getitems__(list(range(restored.num_rows))) + ) == list(range(10)) + finally: + db.drop_all_tables() + + @pytest.mark.s3_test def test_concurrent_open_table(s3_bucket: str): uri = f"s3://{s3_bucket}/test_concurrent_open_table" diff --git a/python/src/permutation.rs b/python/src/permutation.rs index 9cb4da247..f29cc7265 100644 --- a/python/src/permutation.rs +++ b/python/src/permutation.rs @@ -9,7 +9,10 @@ use crate::{ use arrow::pyarrow::{PyArrowType, ToPyArrow}; use lancedb::{ dataloader::permutation::{ - builder::{PermutationBuilder as LancePermutationBuilder, ShuffleStrategy}, + builder::{ + PermutationBuilder as LancePermutationBuilder, PermutationPersistMode, + PermutationPersistOptions, ShuffleStrategy, + }, reader::PermutationReader, split::{SplitSizes, SplitStrategy}, }, @@ -17,7 +20,7 @@ use lancedb::{ }; use pyo3::{ Bound, PyAny, PyRef, PyRefMut, PyResult, Python, - exceptions::PyRuntimeError, + exceptions::{PyRuntimeError, PyValueError}, pyclass, pymethods, types::{PyAnyMethods, PyDict, PyDictMethods, PyType}, }; @@ -247,6 +250,37 @@ impl PyAsyncPermutationBuilder { slf.modify(|builder| builder.with_filter(filter)) } + /// Store the permutation table in a database. + /// + /// This is only supported for embedded databases. The destination table is + /// created in the selected namespace, and an existing table is replaced only + /// when ``mode="overwrite"`` is explicit. + #[pyo3(signature = (db, table_name, *, namespace_path=None, mode="create"))] + pub fn persist( + slf: PyRefMut<'_, Self>, + db: PyRef<'_, crate::connection::Connection>, + table_name: String, + namespace_path: Option>, + mode: &str, + ) -> PyResult { + let mode = match mode { + "create" => PermutationPersistMode::Create, + "overwrite" => PermutationPersistMode::Overwrite, + other => { + return Err(PyValueError::new_err(format!( + "Invalid mode {other}; expected 'create' or 'overwrite'" + ))); + } + }; + let database = db.database()?; + let options = PermutationPersistOptions { + namespace_path: namespace_path.unwrap_or_default(), + mode, + }; + + slf.modify(|builder| builder.persist_with_options(database, table_name, options)) + } + pub fn execute(slf: PyRefMut<'_, Self>) -> PyResult> { let mut state = slf.state.lock().unwrap(); let builder = state diff --git a/python/src/table.rs b/python/src/table.rs index 227247307..35337b194 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -2120,6 +2120,15 @@ impl Table { }) } + /// Return an independent handle pinned to the currently selected snapshot. + pub fn _checkout_current(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let current = inner.checkout_current().await.infer_error()?; + Ok(Table::new(current)) + }) + } + #[pyo3(signature = (version=None))] pub fn restore( self_: PyRef<'_, Self>, diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs index 770a956eb..93efb130f 100644 --- a/rust/lancedb/src/dataloader/permutation/builder.rs +++ b/rust/lancedb/src/dataloader/permutation/builder.rs @@ -15,7 +15,7 @@ use crate::{ Error, Result, Table, arrow::{SendableRecordBatchStream, SendableRecordBatchStreamExt, SimpleRecordBatchStream}, connect, - database::{CreateTableRequest, Database}, + database::{CreateTableMode, CreateTableRequest, Database}, dataloader::permutation::{ shuffle::{Shuffler, ShufflerConfig}, split::{SPLIT_ID_COLUMN, SplitStrategy, Splitter}, @@ -43,7 +43,34 @@ enum PermutationDestination { #[default] Temporary, /// The permutation table is a permanent table in a database - Permanent(Arc, String), + Permanent { + database: Arc, + table_name: String, + namespace_path: Vec, + mode: PermutationPersistMode, + }, +} + +/// How a persisted permutation table handles an existing table of the same name. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum PermutationPersistMode { + /// Fail if the destination table already exists. + #[default] + Create, + /// Replace the destination table with the new plan. + /// + /// The previous table version remains readable by handles that were already + /// opened against it. + Overwrite, +} + +/// Options for storing a permutation table in a database. +#[derive(Debug, Clone, Default)] +pub struct PermutationPersistOptions { + /// The namespace path to create the table in. Empty means the root namespace. + pub namespace_path: Vec, + /// Whether an existing table may be replaced. + pub mode: PermutationPersistMode, } /// Configuration for creating a permutation table @@ -161,9 +188,29 @@ impl PermutationBuilder { /// Stores the permutation as a table in a database /// /// By default, the permutation is stored in memory. If this method is called then - /// the permutation will be stored as a table in the given database. - pub fn persist(mut self, database: Arc, table_name: String) -> Self { - self.config.destination = PermutationDestination::Permanent(database, table_name); + /// the permutation will be stored as a table in the given database. The table is + /// created in the root namespace and an existing table is not replaced; use + /// [`Self::persist_with_options`] to choose a namespace or overwrite mode. + pub fn persist(self, database: Arc, table_name: String) -> Self { + self.persist_with_options(database, table_name, PermutationPersistOptions::default()) + } + + /// Stores the permutation as a table in a database with explicit options. + /// + /// This is the same as [`Self::persist`] but lets the caller select the target + /// namespace and whether an existing table may be overwritten. + pub fn persist_with_options( + mut self, + database: Arc, + table_name: String, + options: PermutationPersistOptions, + ) -> Self { + self.config.destination = PermutationDestination::Permanent { + database, + table_name, + namespace_path: options.namespace_path, + mode: options.mode, + }; self } @@ -369,17 +416,31 @@ impl PermutationBuilder { let streaming_data = Self::add_config_metadata(renamed, metadata)?; let (name, database) = match &self.config.destination { - PermutationDestination::Permanent(database, table_name) => { - (table_name.as_str(), database.clone()) - } + PermutationDestination::Permanent { + database, + table_name, + .. + } => (table_name.as_str(), database.clone()), PermutationDestination::Temporary => { let conn = connect("memory:///").execute().await?; ("permutation", conn.database().clone()) } }; - let create_table_request = + let mut create_table_request = CreateTableRequest::new(name.to_string(), Box::new(streaming_data)); + if let PermutationDestination::Permanent { + namespace_path, + mode, + .. + } = &self.config.destination + { + create_table_request.namespace_path = namespace_path.clone(); + create_table_request.mode = match mode { + PermutationPersistMode::Create => CreateTableMode::Create, + PermutationPersistMode::Overwrite => CreateTableMode::Overwrite, + }; + } let table = database.create_table(create_table_request).await?; @@ -1034,4 +1095,89 @@ mod tests { ); assert!(metadata.contains_key(BASE_VERSION_CONFIG_KEY)); } + + #[tokio::test] + async fn test_permutation_persist_create_overwrite_and_namespace() { + use lance_namespace::models::CreateNamespaceRequest; + + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let initial_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(100), BatchCount::from(1)); + let data_table = db + .create_table("base_tbl", initial_data) + .execute() + .await + .unwrap(); + + let namespace_path = vec!["plans".to_string()]; + db.create_namespace(CreateNamespaceRequest { + id: Some(namespace_path.clone()), + ..Default::default() + }) + .await + .unwrap(); + + let persist = |mode| PermutationPersistOptions { + namespace_path: namespace_path.clone(), + mode, + }; + let first_plan = PermutationBuilder::new(data_table.clone()) + .persist_with_options( + db.database().clone(), + "splits".to_string(), + persist(PermutationPersistMode::Create), + ) + .build() + .await + .unwrap(); + let first_version = first_plan.version().await.unwrap(); + assert_eq!(first_plan.count_rows(None).await.unwrap(), 100); + + let opened = db + .open_table("splits") + .namespace(namespace_path.clone()) + .execute() + .await + .unwrap(); + assert_eq!(opened.count_rows(None).await.unwrap(), 100); + + let err = PermutationBuilder::new(data_table.clone()) + .persist_with_options( + db.database().clone(), + "splits".to_string(), + persist(PermutationPersistMode::Create), + ) + .build() + .await + .unwrap_err(); + assert!( + matches!(err, Error::TableAlreadyExists { .. }), + "expected TableAlreadyExists, got: {err:?}" + ); + + let more_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(50), BatchCount::from(1)); + data_table.add(more_data).execute().await.unwrap(); + + let second_plan = PermutationBuilder::new(data_table) + .persist_with_options( + db.database().clone(), + "splits".to_string(), + persist(PermutationPersistMode::Overwrite), + ) + .build() + .await + .unwrap(); + assert_eq!(second_plan.count_rows(None).await.unwrap(), 150); + + // Overwrite creates a new table version; the old handle stays on its snapshot. + assert_eq!(first_plan.count_rows(None).await.unwrap(), 100); + assert_eq!(first_plan.version().await.unwrap(), first_version); + } } From baea02eebdeb68604e49d64f681a32ae118ea985 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Fri, 20 Nov 2026 14:34:07 -0800 Subject: [PATCH 60/78] feat: add cleanup jobs and previews across SDKs (#5107) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LanceDB SDK users connected to Enterprise had no explicit API to submit durable cleanup or preview its work; Python's existing cleanup helper remained a warning-only no-op. This PR adds the SDK support for [ENT-2687](https://linear.app/lancedb/issue/ENT-2687) through public SQL and Job APIs. It requires a compatible Enterprise release supporting `VACUUM`, JSON preview and result format version 1. Existing cleanup/optimize helpers retain their behavior; the new APIs reject Embedded and historical-version handles. This was accomplished with the following changes: - Add `cleanup_async()` / `cleanupAsync()` and `explain_cleanup()` / `explainCleanup()` in Python sync/async, TypeScript and Rust. - Preserve the handle's namespace/branch and resolve retention as invocation → table/branch TTL → deployment default. Omission inherits, zero is explicit, and malformed options fail rather than being discarded. - Require one nonempty durable SQL receipt, preserving diagnostics without REST fallback, query-ID substitution or automatic resubmission after ambiguous acceptance. - Add versioned `CleanupPlan` estimates and `CleanupResult` measurements. Preview creates no cleanup job or reservation; results preserve known zero, unknown retry/recovery totals and nonfatal failed deletes, excluding auxiliary sweeps. - Retain typed results on reopening and reuse shared status/progress/events/wait/cancel APIs. Timeout leaves work running; cancellation cannot undo deletion or prove storage I/O stopped. - Document Ownership/parent Usage and required coordination at every retention value: disable/drain automatic cleanup and prevent competing cleanup, tag creation/update, branch creation and restore across all clients until completion. The server does not enforce exclusion; concurrent restore can leave the current table unreadable. - Update Python's legacy no-op warning and the maintenance, Python, Rust and generated TypeScript references. | Interface | Submit with seven-day retention | | --- | --- | | SQL | `VACUUM events WITH (min_age_seconds = 604800);` | | CLI | `lancedb admin table cleanup --table events --min-age-seconds 604800 --wait` | | Python | `job = table.cleanup_async(min_age_seconds=604800)` (use `await` with AsyncTable) | | TypeScript | `const job = await table.cleanupAsync({ minAgeSeconds: 604800 });` | | Rust | `let job = table.cleanup_async(CleanupOptions::new().min_age_seconds(604800)).await?;` | ### Testing Added submission/preview, validation, typed-result and reopening tests, and updated the legacy no-op warning assertion. Focused Python cleanup/Job and compaction/prewarm regressions passed, alongside **34 TypeScript** and **46 Rust** tests. **31 end-to-end scenarios** passed against a real Enterprise server, covering CLI/SQL/REST/SDK submission, retention precedence, restart/reopening, timeouts, cancellation and branch/namespace isolation. Local native SDK validation used a separate `libsais-rs 0.2.0` lockfile because the registry could not resolve `0.2.4`; this PR retains main's dependency pins and lockfile. --- docs/src/js/classes/Table.md | 50 ++++ docs/src/js/globals.md | 3 + docs/src/js/interfaces/CleanupOptions.md | 19 ++ docs/src/js/interfaces/CleanupPlan.md | 57 +++++ docs/src/js/interfaces/CleanupResult.md | 61 +++++ docs/src/python/python.md | 4 + .../intelligent-auto-maintenance.mdx | 17 +- docs/web/maintenance/cleanup.mdx | 119 ++++++++- nodejs/__test__/cleanup.test.ts | 83 +++++++ nodejs/__test__/remote.test.ts | 56 +++++ nodejs/lancedb/cleanup.ts | 120 +++++++++ nodejs/lancedb/index.ts | 1 + nodejs/lancedb/job.ts | 5 +- nodejs/lancedb/table.ts | 45 ++++ nodejs/src/connection.rs | 5 + nodejs/src/table.rs | 43 ++++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/cleanup.py | 92 +++++++ python/python/lancedb/job.py | 3 + python/python/lancedb/remote/table.py | 17 +- python/python/lancedb/table.py | 60 +++++ python/python/tests/test_cleanup.py | 187 ++++++++++++++ python/python/tests/test_remote_db.py | 15 +- python/src/connection.rs | 4 + python/src/table.rs | 31 +++ rust/lancedb/src/remote/sql_test.rs | 123 +++++++++ rust/lancedb/src/remote/table.rs | 62 +++++ rust/lancedb/src/remote/table/cleanup.rs | 234 ++++++++++++++++++ rust/lancedb/src/table.rs | 44 ++++ rust/lancedb/src/table/cleanup.rs | 135 ++++++++++ 30 files changed, 1679 insertions(+), 18 deletions(-) create mode 100644 docs/src/js/interfaces/CleanupOptions.md create mode 100644 docs/src/js/interfaces/CleanupPlan.md create mode 100644 docs/src/js/interfaces/CleanupResult.md create mode 100644 nodejs/__test__/cleanup.test.ts create mode 100644 nodejs/lancedb/cleanup.ts create mode 100644 python/python/lancedb/cleanup.py create mode 100644 python/python/tests/test_cleanup.py create mode 100644 rust/lancedb/src/remote/table/cleanup.rs create mode 100644 rust/lancedb/src/table/cleanup.rs diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 72f68c40f..67962578f 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -268,6 +268,38 @@ const after = await table.getRTEStats(); *** +### cleanupAsync() + +```ts +cleanupAsync(_options?): Promise> +``` + +Submit durable remote cleanup through SQL VACUUM and return after acceptance. +Requires table Ownership and parent Usage. Retention inherits from the table +then deployment when omitted. Local/historical handles are unsupported. +Before submission, disable/drain automatic cleanup and prevent other cleanup, +tag/branch publication and restore until completion, including direct clients. +Coordination is not enforced by the server. Cancellation cannot undo deletion +or prove storage I/O stopped. Preview is available without deletion. +Wait timeout leaves work running; save the ID and reopen with db.openJob(). + +#### Parameters + +* **\_options?**: [`CleanupOptions`](../interfaces/CleanupOptions.md) + +#### Returns + +`Promise`<[`Job`](Job.md)<[`CleanupResult`](../interfaces/CleanupResult.md)>> + +#### Example + +```ts +const job = await table.cleanupAsync({ minAgeSeconds: 604800 }); +const result = await job.wait({ timeoutMs: 600000 }); +``` + +*** + ### close() ```ts @@ -653,6 +685,24 @@ await table.enableRTE({ *** +### explainCleanup() + +```ts +explainCleanup(_options?): Promise +``` + +Preview version deletion without creating a job. Execution re-evaluates current state. + +#### Parameters + +* **\_options?**: [`CleanupOptions`](../interfaces/CleanupOptions.md) + +#### Returns + +`Promise`<[`CleanupPlan`](../interfaces/CleanupPlan.md)> + +*** + ### explainPrewarmData() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 2aab45c12..0817755fc 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -71,6 +71,9 @@ - [CherryPickError](interfaces/CherryPickError.md) - [CherryPickPreview](interfaces/CherryPickPreview.md) - [CherryPickResult](interfaces/CherryPickResult.md) +- [CleanupOptions](interfaces/CleanupOptions.md) +- [CleanupPlan](interfaces/CleanupPlan.md) +- [CleanupResult](interfaces/CleanupResult.md) - [ClientConfig](interfaces/ClientConfig.md) - [ColumnAlteration](interfaces/ColumnAlteration.md) - [ColumnOrdering](interfaces/ColumnOrdering.md) diff --git a/docs/src/js/interfaces/CleanupOptions.md b/docs/src/js/interfaces/CleanupOptions.md new file mode 100644 index 000000000..853dfad9a --- /dev/null +++ b/docs/src/js/interfaces/CleanupOptions.md @@ -0,0 +1,19 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / CleanupOptions + +# Interface: CleanupOptions + +Per-run retention; omission inherits selected table/branch then deployment policy. + +## Properties + +### minAgeSeconds? + +```ts +optional minAgeSeconds: number; +``` + +Minimum old-version age in seconds. Zero is explicit, not omitted. diff --git a/docs/src/js/interfaces/CleanupPlan.md b/docs/src/js/interfaces/CleanupPlan.md new file mode 100644 index 000000000..14fc7600c --- /dev/null +++ b/docs/src/js/interfaces/CleanupPlan.md @@ -0,0 +1,57 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / CleanupPlan + +# Interface: CleanupPlan + +Read-only deletion estimates; no job or deletion snapshot is reserved. + +## Properties + +### bytesToRemove + +```ts +bytesToRemove: number; +``` + +*** + +### cutoffMillis + +```ts +cutoffMillis: number; +``` + +*** + +### formatVersion + +```ts +formatVersion: number; +``` + +*** + +### minAgeSeconds + +```ts +minAgeSeconds: number; +``` + +*** + +### sourceVersion + +```ts +sourceVersion: number; +``` + +*** + +### versionsToRemove + +```ts +versionsToRemove: number; +``` diff --git a/docs/src/js/interfaces/CleanupResult.md b/docs/src/js/interfaces/CleanupResult.md new file mode 100644 index 000000000..c3d8c51d7 --- /dev/null +++ b/docs/src/js/interfaces/CleanupResult.md @@ -0,0 +1,61 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / CleanupResult + +# Interface: CleanupResult + +Version-deletion outcome. Best-effort auxiliary sweeps are excluded. + +## Properties + +### bytesRemoved + +```ts +bytesRemoved: null | number; +``` + +*** + +### failedDeletes + +```ts +failedDeletes: null | number; +``` + +Failed object deletions, if measured. Successful removals are retained. + +*** + +### formatVersion + +```ts +formatVersion: number; +``` + +*** + +### minAgeSeconds + +```ts +minAgeSeconds: number; +``` + +*** + +### oldVersions + +```ts +oldVersions: null | number; +``` + +*** + +### statisticsComplete + +```ts +statisticsComplete: boolean; +``` + +False after uncertain retry/recovery; both counts are then null. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index a453114eb..d6389bf83 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -1580,6 +1580,10 @@ Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or ::: lancedb.compaction.CompactionResult +::: lancedb.cleanup.CleanupPlan + +::: lancedb.cleanup.CleanupResult + ::: lancedb.prewarm.PrewarmDataResult ::: lancedb.prewarm.PrewarmDataPlan diff --git a/docs/web/enterprise/intelligent-auto-maintenance.mdx b/docs/web/enterprise/intelligent-auto-maintenance.mdx index cabac3643..13cc4f50b 100644 --- a/docs/web/enterprise/intelligent-auto-maintenance.mdx +++ b/docs/web/enterprise/intelligent-auto-maintenance.mdx @@ -125,14 +125,19 @@ for the fields, precedence, source-budget planning failures, and compatible-vers they referenced. In LanceDB Embedded, that always happens because you asked for it, through a call to `optimize()`. In LanceDB Enterprise, a [manual `optimize()` call](/maintenance/compaction#enterprise-manual-compaction) -submits compaction only. Cleanup remains this planner's own decision, off by -default unless the deployment sets a minimum version age: +submits compaction only. This planner controls automatic cleanup, which is +disabled by default unless the deployment sets a minimum version age: with no minimum age configured, nothing is ever old enough to clean up -automatically, and old versions simply accumulate until an operator enables -it. A table can also disable it individually even when the deployment allows -it, overriding the deployment-wide setting for just that table. +automatically. A table can also disable automatic cleanup individually even +when the deployment allows it, overriding the deployment-wide setting for +just that table. -Once enabled, a table becomes due for cleanup when any one of these is true: +You can [submit manual cleanup](/maintenance/cleanup#enterprise-manual-cleanup) +even when automatic cleanup is disabled. Follow the coordination requirements +in that guide before submitting a manual run. + +Once automatic cleanup is enabled, a table becomes due when any one of these +is true: | Trigger | Condition | | --- | --- | diff --git a/docs/web/maintenance/cleanup.mdx b/docs/web/maintenance/cleanup.mdx index 8ccf4e242..8575acba0 100644 --- a/docs/web/maintenance/cleanup.mdx +++ b/docs/web/maintenance/cleanup.mdx @@ -17,12 +17,15 @@ those versions referenced. **Enterprise job type:** `cleanup`. Distinct from `compact`: compaction merges files, cleanup removes them. `optimize()` in LanceDB Embedded runs both in one call; -Enterprise schedules them as separate jobs, and runs cleanup only when the -deployment's configuration enables it. +Enterprise schedules them as separate jobs. Automatic cleanup follows deployment +and table policy; authorized manual cleanup can run while automatic cleanup is disabled. ## Retention {#retention} +The Embedded examples below keep their existing behavior. For an explicit +Enterprise job, use [manual cleanup](#enterprise-manual-cleanup). + ```python Python icon="python" from datetime import timedelta @@ -77,6 +80,114 @@ to cover the range you need before running this, not after. +## Enterprise manual cleanup {#enterprise-manual-cleanup} + +Requires compatible SDK and Enterprise query-node, agent and worker releases +with SQL `VACUUM` and cleanup result format version 1. Submission requires table +Ownership and database/namespace Usage. SDK methods use the table handle's +namespace and branch; historical-version handles and LanceDB Embedded are unsupported. + + +Before submission, disable automatic cleanup for the table and its branches, +drain existing cleanup workers, and prevent other cleanup, tag creation/update, +branch creation and restore until completion, including direct storage clients. +The server does not enforce this coordination. Restore prior scheduling settings +afterward. Disabling scheduling or cancelling a job does not prove outstanding +storage requests stopped. Concurrent restore can make the current table unreadable. +These restrictions apply to every retention value, including zero. + + + +```python Python icon="python" +from datetime import timedelta + +job = table.cleanup_async(min_age_seconds=604800) +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) +``` + +```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) +``` + +```typescript TypeScript icon="js" +const job = await table.cleanupAsync({ minAgeSeconds: 604800 }); +const result = await job.wait({ timeoutMs: 600000, onProgress: console.log }); +console.log(result.oldVersions, result.bytesRemoved); +const reopened = await db.openJob(job.id!); +``` + +```rust Rust icon="rust" +use lancedb::table::{CleanupOptions, CleanupResult}; + +let job = table.cleanup_async(CleanupOptions::new().min_age_seconds(604800)).await?; +let result = job.wait().await?; +println!("{:?} {:?}", result.old_versions, result.bytes_removed); +let reopened = db.open_job(job.id().unwrap()).await?.into_typed::()?; +``` + + +Submission returns after durable acceptance, before deletion finishes. Omit the +retention option to inherit selected table/branch `job_types.cleanup.ttl_seconds`, +then deployment retention. Zero is explicit; invalid/missing effective retention +fails. The resolved age stays with the job and does not change table policy. +The worker calculates its cutoff against latest state at execution; the observed +submission version is not a reserved deletion snapshot. + +Status, progress, events, waiting, cancellation and reopening reuse the shared +[Job APIs](/basics/jobs) and their existing REST permissions. Describe supports +scoped database/namespace Usage; events require system Usage and cancellation +requires system Operate. Waiting timeout leaves the job running. Failure or +cancellation may follow partial deletion and cannot roll it back. + +`CleanupResult` reports effective retention, `statistics_complete` and optional +`old_versions` / `bytes_removed` (`statisticsComplete`, `oldVersions` and +`bytesRemoved` in TypeScript). Counts cover version deletion, not best-effort +auxiliary sweeps. Unknown totals after retry/recovery remain None/null; measured +zero stays zero. `failed_deletes` / `failedDeletes` reports nonfatal object deletion failures +when measured; successful removals are retained. Missing or incompatible typed results raise an error rather +than inventing counts. Completion does not guarantee every orphaned file was reclaimed. + +Preview deletion using the same options, without creating a job: + + +```python Python icon="python" +plan = table.explain_cleanup(min_age_seconds=604800) +print(plan.source_version, plan.versions_to_remove, plan.bytes_to_remove) +# AsyncTable: plan = await table.explain_cleanup(min_age_seconds=604800) +``` + +```typescript TypeScript icon="js" +const plan = await table.explainCleanup({ minAgeSeconds: 604800 }); +console.log(plan.sourceVersion, plan.versionsToRemove, plan.bytesToRemove); +``` + +```rust Rust icon="rust" +let plan = table.explain_cleanup(CleanupOptions::new().min_age_seconds(604800)).await?; +println!("{} {}", plan.versions_to_remove, plan.bytes_to_remove); +``` + + +`CleanupPlan` is a versioned SQL `EXPLAIN (FORMAT JSON) VACUUM` response. It +reports observed source version, effective retention, cutoff milliseconds and +version/byte deletion estimates. It can list metadata/storage objects but does +not delete, submit or monitor a job, expose file paths, or reserve the preview +snapshot. Auxiliary sweeps are excluded. Execution re-evaluates latest state; +actual removals can differ. `EXPLAIN ANALYZE` is rejected. Read-only preview does +not require draining automatic work; actual cleanup still requires coordination. + +The SDK does not fall back to execution/REST or silently drop unsupported +options. If acceptance is ambiguous, inspect jobs before retrying; an independent +submission can create another job. + +Python's existing Enterprise `cleanup_old_versions()` remains a warning-only +no-op for compatibility. Use `cleanup_async()` explicitly to submit a job. +Embedded cleanup and Enterprise `optimize()` retain their existing behavior. + ## Managed blob objects {#managed-blobs} [Managed blobs](/management/table#managed-blobs) store out-of-line payloads @@ -98,8 +209,8 @@ them, and reopen handles created before that upgrade. For LanceDB Embedded tables, `optimize()` performs compaction and cleanup. Enterprise schedules them as separate background jobs. With compatible releases, remote `optimize()` also submits [manual compaction](/maintenance/compaction#enterprise-manual-compaction), -but does not prune versions or remove their files. Cleanup remains governed by -the deployment's separate policy. +but does not prune versions or remove their files. Automatic cleanup remains governed by +the deployment's separate policy; explicit manual cleanup uses the retention rules above. See [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance#cleanup) for the Enterprise path. ## Disk usage does not drop immediately {#disk} diff --git a/nodejs/__test__/cleanup.test.ts b/nodejs/__test__/cleanup.test.ts new file mode 100644 index 000000000..8c68f833a --- /dev/null +++ b/nodejs/__test__/cleanup.test.ts @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { + type CleanupOptions, + decodeCleanupPlan, + decodeCleanupResult, + validateCleanupOptions, +} from "../lancedb/cleanup"; + +test.each([null, [], 1, true, "options"])( + "cleanup rejects malformed options instead of inheriting retention (%p)", + (options) => { + expect(() => + validateCleanupOptions(options as unknown as CleanupOptions), + ).toThrow("cleanup options must be an object"); + }, +); + +test("cleanup never silently discards an unknown option", () => { + expect(() => + validateCleanupOptions({ force: true } as unknown as CleanupOptions), + ).toThrow("Unknown cleanup option"); +}); + +test.each([undefined, 0, 604800])( + "cleanup retention accepts omission and explicit zero (%s)", + (age) => { + expect(() => validateCleanupOptions({ minAgeSeconds: age })).not.toThrow(); + }, +); + +test.each([ + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + Number.MAX_SAFE_INTEGER + 1, +])("cleanup retention rejects invalid values (%s)", (age) => { + expect(() => validateCleanupOptions({ minAgeSeconds: age })).toThrow(); +}); + +test.each([0, 2, null])( + "cleanup results distinguish known zero and unknown (%s)", + (count) => { + const result = decodeCleanupResult( + JSON.parse( + JSON.stringify({ + ["format_version"]: 1, + ["min_age_seconds"]: 0, + ["statistics_complete"]: count !== null, + ["old_versions"]: count, + ["bytes_removed"]: count, + future: "ignored", + }), + ), + ); + expect(result.oldVersions).toBe(count); + }, +); + +test.each([ + null, + {}, + { ["format_version"]: 2 }, + { + ["format_version"]: 1, + ["min_age_seconds"]: 0, + ["statistics_complete"]: false, + ["old_versions"]: 1, + }, +])("cleanup rejects incompatible results (%p)", (value) => { + expect(() => decodeCleanupResult(value)).toThrow(); +}); + +test("cleanup preview validates its versioned contract", () => { + const value = JSON.parse( + '{"format_version":1,"source_version":42,"min_age_seconds":0,"cutoff_millis":-1,"versions_to_remove":2,"bytes_to_remove":100}', + ); + expect(decodeCleanupPlan(value).versionsToRemove).toBe(2); + value.format_version = 2; + expect(() => decodeCleanupPlan(value)).toThrow(); +}); diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index eccfb9ffd..9c042c00e 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -3223,3 +3223,59 @@ describe("table overrides", () => { expect(requests).toEqual([]); }); }); + +describe("cleanup typed results", () => { + test.each(["counts", "no_op", "unknown", "missing", "FAILED", "CANCELLED"])( + "reopens and waits for cleanup (%s)", + async (outcome) => { + const known = outcome !== "unknown"; + await withMockDatabase( + (request, response) => { + expect(request.url).toBe("/v1/jobs/describe"); + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + JSON.stringify({ + ["job_id"]: "cleanup-job", + ["job_type"]: "cleanup", + ["job_state"]: ["FAILED", "CANCELLED"].includes(outcome) + ? outcome + : "DONE", + result: + outcome === "missing" + ? null + : { + ["format_version"]: 1, + ["min_age_seconds"]: 0, + ["statistics_complete"]: known, + ["old_versions"]: known + ? outcome === "no_op" + ? 0 + : 2 + : null, + ["bytes_removed"]: known + ? outcome === "no_op" + ? 0 + : 123 + : null, + }, + }), + ); + }, + async (db) => { + const job = + await db.openJob("cleanup-job"); + if (["missing", "FAILED", "CANCELLED"].includes(outcome)) { + await expect(job.wait()).rejects.toThrow(); + } else { + const result = await job.wait(); + expect(result.statisticsComplete).toBe(known); + expect(result.oldVersions).toBe( + known ? (outcome === "no_op" ? 0 : 2) : null, + ); + expect(result.minAgeSeconds).toBe(0); + } + }, + ); + }, + ); +}); diff --git a/nodejs/lancedb/cleanup.ts b/nodejs/lancedb/cleanup.ts new file mode 100644 index 000000000..dfcc04564 --- /dev/null +++ b/nodejs/lancedb/cleanup.ts @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/** Per-run retention; omission inherits selected table/branch then deployment policy. */ +export interface CleanupOptions { + /** Minimum old-version age in seconds. Zero is explicit, not omitted. */ + minAgeSeconds?: number; +} + +/** Version-deletion outcome. Best-effort auxiliary sweeps are excluded. */ +export interface CleanupResult { + formatVersion: number; + minAgeSeconds: number; + /** False after uncertain retry/recovery; both counts are then null. */ + statisticsComplete: boolean; + oldVersions: number | null; + bytesRemoved: number | null; + /** Failed object deletions, if measured. Successful removals are retained. */ + failedDeletes: number | null; +} + +/** Read-only deletion estimates; no job or deletion snapshot is reserved. */ +export interface CleanupPlan { + formatVersion: number; + sourceVersion: number; + minAgeSeconds: number; + cutoffMillis: number; + versionsToRemove: number; + bytesToRemove: number; +} + +/** @internal */ +export function decodeCleanupPlan(value: unknown): CleanupPlan { + if (typeof value !== "object" || value === null) + throw new Error("invalid cleanup preview"); + const plan = value as Record; + if ( + plan.format_version !== 1 || + [ + "source_version", + "min_age_seconds", + "cutoff_millis", + "versions_to_remove", + "bytes_to_remove", + ].some( + (key) => + !Number.isSafeInteger(plan[key]) || + (key !== "cutoff_millis" && (plan[key] as number) < 0), + ) + ) { + throw new Error("unsupported or invalid cleanup preview"); + } + return { + formatVersion: 1, + sourceVersion: plan.source_version as number, + minAgeSeconds: plan.min_age_seconds as number, + cutoffMillis: plan.cutoff_millis as number, + versionsToRemove: plan.versions_to_remove as number, + bytesToRemove: plan.bytes_to_remove as number, + }; +} + +/** @internal */ +export function validateCleanupOptions(options?: CleanupOptions): void { + if ( + options !== undefined && + (typeof options !== "object" || options === null || Array.isArray(options)) + ) { + throw new Error("cleanup options must be an object"); + } + for (const key of Object.keys(options ?? {})) { + if (key !== "minAgeSeconds") + throw new Error(`Unknown cleanup option: ${key}`); + } + const age = options?.minAgeSeconds; + if (age !== undefined && (!Number.isSafeInteger(age) || age < 0)) { + throw new Error("minAgeSeconds must be a nonnegative safe integer"); + } +} + +/** @internal */ +export function decodeCleanupResult(value: unknown): CleanupResult { + if (typeof value !== "object" || value === null) + throw new Error("invalid cleanup result"); + const result = value as Record; + const counts = [result.old_versions ?? null, result.bytes_removed ?? null]; + const failed = result.failed_deletes ?? null; + if ( + failed !== null && + (!Number.isSafeInteger(failed) || + (failed as number) < 0 || + result.statistics_complete !== true) + ) { + throw new Error("invalid cleanup failed-deletion measurement"); + } + if ( + result.format_version !== 1 || + typeof result.statistics_complete !== "boolean" || + !Number.isSafeInteger(result.min_age_seconds) || + (result.min_age_seconds as number) < 0 || + counts.some( + (count) => + count !== null && + (!Number.isSafeInteger(count) || (count as number) < 0), + ) || + (result.statistics_complete + ? counts.some((count) => count === null) + : counts.some((count) => count !== null)) + ) { + throw new Error("unsupported or inconsistent cleanup result"); + } + return { + formatVersion: 1, + minAgeSeconds: result.min_age_seconds as number, + statisticsComplete: result.statistics_complete, + oldVersions: counts[0] as number | null, + bytesRemoved: counts[1] as number | null, + failedDeletes: (result.failed_deletes as number | null) ?? null, + }; +} diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index aa51c2b56..d99f8675e 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -668,6 +668,7 @@ export { export { Listing, ListingOptions } from "./listing"; export type { CompactionResult } from "./compaction"; +export type { CleanupOptions, CleanupPlan, CleanupResult } from "./cleanup"; export type { PrewarmDataPlan, diff --git a/nodejs/lancedb/job.ts b/nodejs/lancedb/job.ts index 40c27365e..aa8e9dc10 100644 --- a/nodejs/lancedb/job.ts +++ b/nodejs/lancedb/job.ts @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors import { Table as ArrowTable, tableFromIPC } from "apache-arrow"; +import { decodeCleanupResult } from "./cleanup"; import { decodeCompactionResult } from "./compaction"; import { JobFailureInfo, Job as NativeJob } from "./native"; import { decodePrewarmDataResult } from "./prewarm"; @@ -123,7 +124,9 @@ export class Job { ? (decodePrewarmDataResult as (value: unknown) => T) : inner.jobType === "compact" ? (decodeCompactionResult as (value: unknown) => T) - : undefined); + : inner.jobType === "cleanup" + ? (decodeCleanupResult as (value: unknown) => T) + : undefined); } /** diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index eecb83fb6..97677866e 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -1,6 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +import { + CleanupOptions, + CleanupPlan, + CleanupResult, + decodeCleanupPlan, + decodeCleanupResult, + validateCleanupOptions, +} from "./cleanup"; import { CompactionResult, decodeCompactionResult } from "./compaction"; import { PrewarmDataPlan, @@ -1341,6 +1349,28 @@ export abstract class Table { * out state and the read_consistency_interval, if any, will apply. */ abstract restore(): Promise; + /** + * Submit durable remote cleanup through SQL VACUUM and return after acceptance. + * Requires table Ownership and parent Usage. Retention inherits from the table + * then deployment when omitted. Local/historical handles are unsupported. + * Before submission, disable/drain automatic cleanup and prevent other cleanup, + * tag/branch publication and restore until completion, including direct clients. + * Coordination is not enforced by the server. Cancellation cannot undo deletion + * or prove storage I/O stopped. Preview is available without deletion. + * Wait timeout leaves work running; save the ID and reopen with db.openJob(). + * @example + * const job = await table.cleanupAsync({ minAgeSeconds: 604800 }); + * const result = await job.wait({ timeoutMs: 600000 }); + */ + async cleanupAsync(_options?: CleanupOptions): Promise> { + throw new Error("durable cleanup jobs are only supported on remote tables"); + } + + /** Preview version deletion without creating a job. Execution re-evaluates current state. */ + async explainCleanup(_options?: CleanupOptions): Promise { + throw new Error("cleanup previews require LanceDB Enterprise"); + } + /** * Submit remote compaction and return its durable job after acceptance. * @@ -2091,6 +2121,21 @@ export class LocalTable extends Table { ); } + async cleanupAsync(options?: CleanupOptions): Promise> { + validateCleanupOptions(options); + return new Job( + await this.inner.cleanupAsync(options?.minAgeSeconds), + decodeCleanupResult, + ); + } + + async explainCleanup(options?: CleanupOptions): Promise { + validateCleanupOptions(options); + return decodeCleanupPlan( + await this.inner.explainCleanup(options?.minAgeSeconds), + ); + } + async optimize(options?: Partial): Promise { validateCompactionOptions(options?.compactionOptions); return await this.inner.optimize( diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index fa1c289b1..7a32756c3 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -572,6 +572,11 @@ impl Connection { job.into_typed::() .default_error()?, )) + } else if job.job_type().as_deref() == Some("cleanup") { + Ok(crate::job::Job::new_typed( + job.into_typed::() + .default_error()?, + )) } else if job.job_type().as_deref() == Some("compact") { Ok(crate::job::Job::new_typed( job.into_typed::() diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 1a4c3e91c..20f5a43cf 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -1001,6 +1001,33 @@ impl Table { Ok(self.inner_ref()?.current_branch()) } + #[napi(catch_unwind)] + pub async fn explain_cleanup( + &self, + min_age_seconds: Option, + ) -> napi::Result { + let plan = self + .inner_ref()? + .explain_cleanup(parse_cleanup_options(min_age_seconds)?) + .await + .default_error()?; + serde_json::to_value(plan).map_err(|error| napi::Error::from_reason(error.to_string())) + } + + #[napi(catch_unwind)] + pub async fn cleanup_async( + &self, + min_age_seconds: Option, + ) -> napi::Result { + let options = parse_cleanup_options(min_age_seconds)?; + let job = self + .inner_ref()? + .cleanup_async(options) + .await + .default_error()?; + Ok(crate::job::Job::new_typed(job)) + } + #[napi(catch_unwind)] pub async fn compact_async( &self, @@ -2557,3 +2584,19 @@ impl Branches { }) } } + +fn parse_cleanup_options( + min_age_seconds: Option, +) -> napi::Result { + let mut options = lancedb::table::CleanupOptions::new(); + if let Some(age) = min_age_seconds { + if !age.is_finite() || age.fract() != 0.0 || !(0.0..=9_007_199_254_740_991.0).contains(&age) + { + return Err(napi::Error::from_reason( + "minAgeSeconds must be a nonnegative safe integer", + )); + } + options.min_age_seconds = Some(age as u64); + } + Ok(options) +} diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 82b2a3513..c1177e849 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -813,6 +813,8 @@ class Table: async def update_field_metadata( self, updates: list[dict[str, Any]] ) -> UpdateFieldMetadataResult: ... + async def cleanup_async(self, min_age_seconds: Optional[int] = None) -> Job: ... + async def explain_cleanup(self, min_age_seconds: Optional[int] = None) -> str: ... async def compact_async( self, compaction_options: Optional[Dict[str, Any]] = None ) -> Job: ... diff --git a/python/python/lancedb/cleanup.py b/python/python/lancedb/cleanup.py new file mode 100644 index 000000000..8e4fd448c --- /dev/null +++ b/python/python/lancedb/cleanup.py @@ -0,0 +1,92 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Results of durable remote version cleanup.""" + +from dataclasses import dataclass, fields +import json +from typing import Optional + + +@dataclass(frozen=True) +class CleanupResult: + """Version-deletion outcome, excluding best-effort auxiliary sweeps. + + Unknown totals after retry/recovery are None, never fabricated zeroes. + Completion does not guarantee that every orphaned file was reclaimed. + """ + + format_version: int + min_age_seconds: int + statistics_complete: bool + old_versions: Optional[int] = None + bytes_removed: Optional[int] = None + failed_deletes: Optional[int] = None + + @classmethod + def from_json(cls, raw: str) -> "CleanupResult": + """Decode the versioned contract, preserving unknown measurements.""" + value = json.loads(raw) + if ( + not isinstance(value, dict) + or type(value.get("format_version")) is not int + or value["format_version"] != 1 + ): + raise ValueError("unsupported cleanup result format") + if type(value.get("statistics_complete")) is not bool: + raise ValueError("invalid cleanup result statistics_complete") + for key in ( + "min_age_seconds", + "old_versions", + "bytes_removed", + "failed_deletes", + ): + count = value.get(key) + if count is None and key != "min_age_seconds": + continue + if type(count) is not int or count < 0: + raise ValueError(f"invalid cleanup result {key}") + counts = [value.get("old_versions"), value.get("bytes_removed")] + if not value["statistics_complete"] and value.get("failed_deletes") is not None: + raise ValueError("inconsistent cleanup failed-deletion measurement") + if ( + value["statistics_complete"] and any(count is None for count in counts) + ) or ( + not value["statistics_complete"] + and any(count is not None for count in counts) + ): + raise ValueError("inconsistent cleanup result statistics") + names = {field.name for field in fields(cls)} + return cls(**{key: item for key, item in value.items() if key in names}) + + +@dataclass(frozen=True) +class CleanupPlan: + """Read-only version-deletion estimates, excluding auxiliary sweeps. + + No job or deletion snapshot is reserved. Execution plans current state again. + """ + + format_version: int + source_version: int + min_age_seconds: int + cutoff_millis: int + versions_to_remove: int + bytes_to_remove: int + + @classmethod + def from_json(cls, raw: str) -> "CleanupPlan": + value = json.loads(raw) + if not isinstance(value, dict) or value.get("format_version") != 1: + raise ValueError("unsupported cleanup preview format") + names = {field.name for field in fields(cls)} + for name in names: + item = value.get(name) + if type(item) is not int or (name != "cutoff_millis" and item < 0): + raise ValueError(f"invalid cleanup preview {name}") + return cls(**{key: item for key, item in value.items() if key in names}) + + +def _validate_min_age_seconds(value: Optional[int]) -> None: + if value is not None and (type(value) is not int or value < 0): + raise ValueError("min_age_seconds must be a nonnegative integer or None") diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 9191bf497..81ffea602 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -22,6 +22,7 @@ from . import _lancedb from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url from .functions import RefreshColumnResult from .compaction import CompactionResult +from .cleanup import CleanupResult from .prewarm import PrewarmDataResult from .remote.errors import HttpError, RetryError @@ -858,6 +859,8 @@ def _typed_job( def _opened_job(inner: "_lancedb.Job") -> AsyncJob: + if inner.job_type == "cleanup": + return _typed_job(inner, CleanupResult.from_json) if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"): return _typed_job(inner, RefreshColumnResult.from_json) if inner.job_type == "prewarm_page_cache": diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index dba3a9eaf..f0722acd0 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -50,6 +50,7 @@ from lancedb.index import ( LabelList, ) from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult +from lancedb.cleanup import CleanupPlan, CleanupResult from lancedb.job import Job from lancedb.functions import ( FunctionProvenance, @@ -1101,7 +1102,8 @@ class RemoteTable(Table): cleanup_old_versions() is a no-op in LanceDB Enterprise. """ warnings.warn( - "cleanup_old_versions() is a no-op in LanceDB Enterprise.", + "cleanup_old_versions() is a no-op in LanceDB Enterprise. " + "Use cleanup_async() to submit durable cleanup explicitly.", stacklevel=2, ) pass @@ -1116,6 +1118,19 @@ class RemoteTable(Table): ) pass + def explain_cleanup(self, *, min_age_seconds: Optional[int] = None) -> CleanupPlan: + """Preview cleanup without submitting a job or deleting files.""" + return LOOP.run(self._table.explain_cleanup(min_age_seconds=min_age_seconds)) + + def cleanup_async( + self, *, min_age_seconds: Optional[int] = None + ) -> Job[CleanupResult]: + """Submit cleanup. See + + [Table.cleanup_async][lancedb.table.Table.cleanup_async]. + """ + return Job(LOOP.run(self._table.cleanup_async(min_age_seconds=min_age_seconds))) + def compact_async( self, *, compaction_options: Optional[CompactionOptions] = None ) -> Job[CompactionResult]: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 57588948f..9cd82638d 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -52,6 +52,7 @@ from lancedb.background_loop import LOOP, embedding_executor from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult from lancedb.job import AsyncJob, Job, _typed_job from lancedb.compaction import CompactionResult +from lancedb.cleanup import CleanupPlan, CleanupResult, _validate_min_age_seconds from .dependencies import ( _check_for_hugging_face, _check_for_lance, @@ -3194,6 +3195,38 @@ class Table(ABC): compaction for you automatically. """ + def explain_cleanup(self, *, min_age_seconds: Optional[int] = None) -> CleanupPlan: + """Preview version deletion without submitting a job or deleting files. + + Uses the same retention, branch and Ownership boundary as cleanup_async. + Estimates exclude auxiliary sweeps and reserve no snapshot for execution. + """ + raise NotImplementedError("cleanup previews require LanceDB Enterprise") + + def cleanup_async( + self, *, min_age_seconds: Optional[int] = None + ) -> Job[CleanupResult]: + """Submit durable remote version cleanup through SQL VACUUM. + + Omitted retention inherits selected table/branch then deployment policy. + Requires Ownership and parent Usage. Local/historical handles are unsupported. + Disable/drain automatic cleanup and prevent other cleanup, tag/branch + publication and restore until completion, including direct storage clients. + 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 + [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. + + >>> job = table.cleanup_async(min_age_seconds=604800) # doctest: +SKIP + >>> result = job.wait() # doctest: +SKIP + """ + raise NotImplementedError( + "durable cleanup jobs are only supported on remote tables" + ) + def compact_async( self, *, compaction_options: Optional[CompactionOptions] = None ) -> Job[CompactionResult]: @@ -6240,6 +6273,14 @@ class LanceTable(Table): LOOP.run(self._table.compact_async(compaction_options=compaction_options)) ) + def explain_cleanup(self, *, min_age_seconds: Optional[int] = None) -> CleanupPlan: + return LOOP.run(self._table.explain_cleanup(min_age_seconds=min_age_seconds)) + + def cleanup_async( + self, *, min_age_seconds: Optional[int] = None + ) -> Job[CleanupResult]: + return Job(LOOP.run(self._table.cleanup_async(min_age_seconds=min_age_seconds))) + def optimize( self, *, @@ -9983,6 +10024,25 @@ class AsyncTable: """The branch this table handle is scoped to, or ``None`` for ``main``.""" return self._inner.current_branch() + async def explain_cleanup( + self, *, min_age_seconds: Optional[int] = None + ) -> CleanupPlan: + """Read-only preview; see Table.explain_cleanup.""" + _validate_min_age_seconds(min_age_seconds) + return CleanupPlan.from_json(await self._inner.explain_cleanup(min_age_seconds)) + + async def cleanup_async( + self, *, min_age_seconds: Optional[int] = None + ) -> AsyncJob[CleanupResult]: + """Submit cleanup. See + + [Table.cleanup_async][lancedb.table.Table.cleanup_async]. + """ + _validate_min_age_seconds(min_age_seconds) + return _typed_job( + await self._inner.cleanup_async(min_age_seconds), CleanupResult.from_json + ) + async def compact_async( self, *, compaction_options: Optional[CompactionOptions] = None ) -> AsyncJob[CompactionResult]: diff --git a/python/python/tests/test_cleanup.py b/python/python/tests/test_cleanup.py new file mode 100644 index 000000000..4d7c285dd --- /dev/null +++ b/python/python/tests/test_cleanup.py @@ -0,0 +1,187 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json + +import pyarrow as pa +import pytest + +import lancedb +from lancedb.cleanup import CleanupResult +from test_remote_db import _create_table_handler, _mock_remote_sql_connection + + +@pytest.mark.parametrize("counts", [(0, 0), (2, 123), (None, None)]) +def test_cleanup_result_preserves_measurements(counts): + versions, size = counts + result = CleanupResult.from_json( + json.dumps( + { + "format_version": 1, + "min_age_seconds": 0, + "statistics_complete": versions is not None, + "old_versions": versions, + "bytes_removed": size, + "future": True, + } + ) + ) + assert result.old_versions == versions + assert result.bytes_removed == size + + +@pytest.mark.parametrize( + "payload", + [ + None, + {}, + {"format_version": 2}, + { + "format_version": 1, + "min_age_seconds": 0, + "statistics_complete": False, + "old_versions": 1, + }, + ], +) +def test_cleanup_result_rejects_missing_unknown_or_inconsistent_contract(payload): + with pytest.raises(ValueError): + CleanupResult.from_json(json.dumps(payload)) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "outcome", ["counts", "no_op", "unknown", "missing", "FAILED", "CANCELLED"] +) +async def test_cleanup_submission_wait_and_reopen(asynchronous, outcome): + flight = pytest.importorskip("pyarrow.flight") + polls = [] + result = { + "format_version": 1, + "min_age_seconds": 0, + "statistics_complete": outcome != "unknown", + "old_versions": None + if outcome == "unknown" + else 0 + if outcome == "no_op" + else 2, + "bytes_removed": None + if outcome == "unknown" + else 0 + if outcome == "no_op" + else 123, + } + + class Server(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream(pa.table({"job_id": ["cleanup-job"]})) + + def handler(request): + if request.path != "/v1/jobs/describe": + return _create_table_handler(request) + polls.append( + json.loads(request.rfile.read(int(request.headers["Content-Length"]))) + ) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "cleanup-job", + "job_type": "cleanup", + "job_state": outcome + if outcome in ("FAILED", "CANCELLED") + else "DONE", + "result": None if outcome == "missing" else result, + } + ).encode() + ) + + server = Server() + with _mock_remote_sql_connection(server, handler) as kwargs: + if asynchronous: + db = await lancedb.connect_async(**kwargs) + table = await db.create_table("test", [{"id": 1}]) + job = await table.cleanup_async(min_age_seconds=0) + else: + 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 + if outcome in ("missing", "FAILED", "CANCELLED"): + with pytest.raises( + Exception, + match={ + "missing": "did not contain a result", + "FAILED": "failed", + "CANCELLED": "cancel", + }[outcome], + ): + if asynchronous: + await job.wait() + else: + job.wait() + else: + stats = await job.wait() if asynchronous else job.wait() + 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) + ) + assert (await reopened.wait() if asynchronous else reopened.wait()) == stats + assert len(server.tickets) == 1 + assert b"VACUUM" in server.tickets[0] + assert b"min_age_seconds = 0" in server.tickets[0] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_cleanup_preview_is_read_only(asynchronous): + flight = pytest.importorskip("pyarrow.flight") + payload = { + "format_version": 1, + "source_version": 42, + "min_age_seconds": 0, + "cutoff_millis": 123, + "versions_to_remove": 2, + "bytes_to_remove": 100, + } + + class Server(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream( + pa.table({"plan_type": ["logical_plan"], "plan": [json.dumps(payload)]}) + ) + + def handler(request): + assert not request.path.startswith("/v1/jobs"), ( + "preview must not submit/monitor jobs" + ) + return _create_table_handler(request) + + server = Server() + with _mock_remote_sql_connection(server, handler) as kwargs: + if asynchronous: + db = await lancedb.connect_async(**kwargs) + table = await db.create_table("test", [{"id": 1}]) + plan = await table.explain_cleanup(min_age_seconds=0) + else: + db = lancedb.connect(**kwargs) + table = db.create_table("test", [{"id": 1}]) + plan = table.explain_cleanup(min_age_seconds=0) + assert plan.source_version == 42 + assert plan.versions_to_remove == 2 + assert len(server.tickets) == 1 + assert b"EXPLAIN (FORMAT JSON) VACUUM" in server.tickets[0] diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 7089f1e0b..fed3ae1bf 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -3737,13 +3737,16 @@ def test_remote_python_only_messages(): f"{method}() is not supported in LanceDB Enterprise. " f"Use table.search().{method}() instead." ) - for method in ["compact_files", "cleanup_old_versions"]: + for method, expected in { + "compact_files": "compact_files() is a no-op in LanceDB Enterprise.", + "cleanup_old_versions": ( + "cleanup_old_versions() is a no-op in LanceDB Enterprise. " + "Use cleanup_async() to submit durable cleanup explicitly." + ), + }.items(): with pytest.warns(UserWarning) as warning: - getattr(table, method)() - assert ( - str(warning[0].message) - == f"{method}() is a no-op in LanceDB Enterprise." - ) + assert getattr(table, method)() is None + assert str(warning[0].message) == expected def test_remote_embedding_config_does_not_warn_or_drop_metadata(caplog): diff --git a/python/src/connection.rs b/python/src/connection.rs index 60f53e782..40e3c7b42 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -1054,6 +1054,10 @@ impl Connection { job.into_typed::() .infer_error()?, )), + Some("cleanup") => Ok(crate::job::Job::new_typed( + job.into_typed::() + .infer_error()?, + )), Some("compact") => Ok(crate::job::Job::new_typed( job.into_typed::() .infer_error()?, diff --git a/python/src/table.rs b/python/src/table.rs index 35337b194..c94b3c106 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -2326,6 +2326,37 @@ impl Table { }) } + /// Explain Enterprise version cleanup without submitting a job. + #[pyo3(signature = (min_age_seconds=None))] + pub fn explain_cleanup<'py>( + self_: PyRef<'py, Self>, + min_age_seconds: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let mut options = lancedb::table::CleanupOptions::new(); + options.min_age_seconds = min_age_seconds; + future_into_py(self_.py(), async move { + let plan = inner.explain_cleanup(options).await.infer_error()?; + serde_json::to_string(&plan) + .map_err(|error| pyo3::exceptions::PyRuntimeError::new_err(error.to_string())) + }) + } + + /// Submit Enterprise version cleanup and retain its durable job and result. + #[pyo3(signature = (min_age_seconds=None))] + pub fn cleanup_async<'py>( + self_: PyRef<'py, Self>, + min_age_seconds: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let mut options = lancedb::table::CleanupOptions::new(); + options.min_age_seconds = min_age_seconds; + future_into_py(self_.py(), async move { + let job = inner.cleanup_async(options).await.infer_error()?; + Ok(crate::job::Job::new_typed(job)) + }) + } + /// Submit remote compaction and retain its durable job and actual result. #[pyo3(signature = (compaction_options=None))] pub fn compact_async<'py>( diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index a8f39fc2e..eb70e87ac 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -4802,6 +4802,84 @@ async fn remote_prewarm_rejects_historical_checkout_without_submitting() { shutdown.send(()).unwrap(); } +#[tokio::test] +async fn remote_cleanup_tracks_registry_job_and_real_result() { + use crate::table::CleanupOptions; + let service = TestSqlService { + adaptive: true, + result: RecordBatch::try_from_iter([( + "job_id", + Arc::new(StringArray::from(vec!["cleanup-job"])) as ArrayRef, + )]) + .unwrap(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let polls = Arc::new(AtomicUsize::new(0)); + let observed = polls.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"cleanup-job","job_type":"cleanup","job_state":"DONE", + "result":{"format_version":1,"min_age_seconds":0,"statistics_complete":true, + "old_versions":2,"bytes_removed":123} + }) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into(), "inner".into()], + "team$inner$events".into(), + Default::default(), + Some(sql), + ) + .with_branch(Some("o'brien".into())); + let job = table + .cleanup_async(CleanupOptions::new().min_age_seconds(0)) + .await + .unwrap(); + assert_eq!(job.id(), Some("cleanup-job")); + assert_eq!(polls.load(Ordering::SeqCst), 0); + let result = job.wait().await.unwrap(); + assert_eq!(result.old_versions, Some(2)); + assert_eq!(result.bytes_removed, Some(123)); + assert_eq!( + *statements.lock().unwrap(), + ["VACUUM \"events\" WITH (branch = 'o''brien', min_age_seconds = 0)"] + ); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_cleanup_rejects_historical_checkout_without_submitting() { + let table = RemoteTable::new_with_sql_client( + client_with_handler(|request| { + assert_eq!(request.url().path(), "/v1/table/events/describe/"); + http::Response::builder() + .status(200) + .body(r#"{"version":7,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + }), + "analytics".into(), + "events".into(), + vec![], + "events".into(), + Default::default(), + None, + ); + table.checkout(7).await.unwrap(); + assert!(table.cleanup_async(Default::default()).await.is_err()); +} + #[tokio::test] async fn remote_compaction_tracks_registry_job_and_real_result() { use crate::table::optimize::CompactionOverrides; @@ -4943,3 +5021,48 @@ async fn remote_prewarm_preview_uses_sql_without_any_http_jobs() { shutdown.send(()).unwrap(); } } + +#[tokio::test] +async fn remote_cleanup_preview_uses_sql_without_job_calls() { + let payload = serde_json::json!({"format_version":1,"source_version":42,"min_age_seconds":0, + "cutoff_millis":123,"versions_to_remove":2,"bytes_to_remove":100}); + let service = TestSqlService { + adaptive: true, + result: RecordBatch::try_from_iter([ + ( + "plan_type", + Arc::new(StringArray::from(vec!["logical_plan"])) as ArrayRef, + ), + ( + "plan", + Arc::new(StringArray::from(vec![payload.to_string()])) as ArrayRef, + ), + ]) + .unwrap(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|_| -> http::Response { + panic!("preview must not use HTTP jobs or execution fallback") + }), + "analytics".into(), + "events".into(), + vec!["team".into()], + "team$events".into(), + Default::default(), + Some(sql), + ); + let plan = table + .explain_cleanup(crate::table::CleanupOptions::new().min_age_seconds(0)) + .await + .unwrap(); + assert_eq!(plan.source_version, 42); + assert_eq!(plan.versions_to_remove, 2); + assert_eq!( + *statements.lock().unwrap(), + ["EXPLAIN (FORMAT JSON) VACUUM \"events\" WITH (min_age_seconds = 0)"] + ); + shutdown.send(()).unwrap(); +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index fc888e32b..bb647d819 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors pub mod blobs; +mod cleanup; pub mod insert; mod ipc_stream; mod optimize; @@ -4175,6 +4176,67 @@ impl BaseTable for RemoteTable { prune: None, }) } + async fn explain_cleanup( + &self, + options: crate::table::CleanupOptions, + ) -> Result { + self.check_mutable().await?; + let statement = format!( + "EXPLAIN (FORMAT JSON) {}", + cleanup::statement(&self.name, self.branch.as_deref(), &options)? + ); + let client = self.sql_client.as_ref().ok_or_else(|| Error::NotSupported { + message: "cleanup previews require a Flight SQL endpoint with EXPLAIN (FORMAT JSON) VACUUM support".into(), + })?; + let query = client + .execute(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + }) + .await + .map_err(cleanup::map_error)?; + let mut reader = query.reader().await.map_err(cleanup::map_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader.try_next().await.map_err(cleanup::map_error)? { + batches.push(batch); + } + cleanup::plan(&batches) + } + + async fn cleanup_async( + &self, + options: crate::table::CleanupOptions, + ) -> Result> { + self.check_mutable().await?; + let statement = cleanup::statement(&self.name, self.branch.as_deref(), &options)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "manual cleanup requires a Flight SQL endpoint and SQL VACUUM support" + .into(), + })?; + let query = client + .execute(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + }) + .await + .map_err(cleanup::map_error)?; + let mut reader = query.reader().await.map_err(cleanup::map_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader.try_next().await.map_err(cleanup::map_error)? { + batches.push(batch); + } + let job_id = cleanup::receipt(&batches)?; + Ok(Job::new_typed(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) + } + async fn compact_async( &self, options: crate::table::optimize::CompactionOverrides, diff --git a/rust/lancedb/src/remote/table/cleanup.rs b/rust/lancedb/src/remote/table/cleanup.rs new file mode 100644 index 000000000..c20417742 --- /dev/null +++ b/rust/lancedb/src/remote/table/cleanup.rs @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! SQL VACUUM submission; never replay an ambiguous acceptance response. + +use crate::{Error, Result, table::CleanupOptions}; +use arrow_array::{Array, RecordBatch, StringArray}; + +pub(super) fn statement( + table: &str, + branch: Option<&str>, + options: &CleanupOptions, +) -> Result { + let mut settings = Vec::new(); + if let Some(branch) = branch { + if branch.trim().is_empty() { + return Err(Error::InvalidInput { + message: "cleanup branch must not be empty".into(), + }); + } + settings.push(format!("branch = {}", super::quote_sql_string(branch))); + } + if let Some(age) = options.min_age_seconds { + if i64::try_from(age) + .ok() + .and_then(chrono::Duration::try_seconds) + .and_then(|duration| chrono::Utc::now().checked_sub_signed(duration)) + .is_none() + { + return Err(Error::InvalidInput { + message: "min_age_seconds is out of range".into(), + }); + } + settings.push(format!("min_age_seconds = {age}")); + } + let mut sql = format!("VACUUM {}", super::quote_sql_identifier(table)); + if !settings.is_empty() { + sql.push_str(&format!(" WITH ({})", settings.join(", "))); + } + Ok(sql) +} + +pub(super) fn receipt(batches: &[RecordBatch]) -> Result { + let invalid = || { + Error::Runtime { message: "VACUUM did not return a single nonempty job_id receipt; inspect jobs before retrying because cleanup may already have been submitted".into() } + }; + if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { + return Err(invalid()); + } + let batch = batches + .iter() + .find(|batch| batch.num_rows() == 1) + .ok_or_else(invalid)?; + let ids = batch + .column_by_name("job_id") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if ids.is_null(0) || ids.value(0).trim().is_empty() { + return Err(invalid()); + } + Ok(ids.value(0).to_string()) +} + +pub(super) fn plan(batches: &[RecordBatch]) -> Result { + let invalid = || { + Error::Runtime { message: "EXPLAIN VACUUM did not return a valid versioned preview; a compatible EXPLAIN (FORMAT JSON) VACUUM server is required. No execution fallback was attempted".into() } + }; + if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { + return Err(invalid()); + } + let batch = batches + .iter() + .find(|batch| batch.num_rows() == 1) + .ok_or_else(invalid)?; + let kind = batch + .column_by_name("plan_type") + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + let payload = batch + .column_by_name("plan") + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if kind.is_null(0) || kind.value(0) != "logical_plan" || payload.is_null(0) { + return Err(invalid()); + } + serde_json::from_str(payload.value(0)).map_err(|_| invalid()) +} + +pub(super) fn map_error(error: Error) -> Error { + fn unsupported(error: &Error) -> Option<&Error> { + match error { + Error::Sql { + message, grpc_code, .. + } => { + let message = message.to_ascii_lowercase(); + (*grpc_code == tonic::Code::Unimplemented as i32 + || (*grpc_code == tonic::Code::Internal as i32 + && message.contains("invalid explain format") + && message.contains("json")) + || (*grpc_code == tonic::Code::InvalidArgument as i32 + && (message.contains("parsererror") + || message.contains("unknown vacuum option") + || message.contains("vacuum is not supported by this deployment")))) + .then_some(error) + } + Error::JobFailed { failure, .. } => failure.source.as_deref().and_then(unsupported), + _ => None, + } + } + if let Some(source) = unsupported(&error) { + let diagnostic = if matches!(error, Error::Sql { .. }) { + error.to_string() + } else { + format!("{error}; {source}") + }; + Error::NotSupported { + message: format!( + "Manual cleanup requires a compatible SQL VACUUM server; upgrade the server. No options were removed and no REST fallback was attempted. Server diagnostic: {diagnostic}" + ), + } + } else { + error + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + #[test] + fn wrapped_cleanup_compatibility_keeps_job_and_request_identity() { + let sql = Error::Sql { + message: "ParserError: found VACUUM".into(), + request_id: "cleanup-request".into(), + grpc_code: tonic::Code::InvalidArgument as i32, + metadata: Default::default(), + }; + let error = Error::JobFailed { + job_id: Some("query-job".into()), + failure: Box::new(crate::error::JobFailure { + phase: Some("planning".into()), + message: Some("statement failed".into()), + source: Some(Arc::new(sql)), + ..Default::default() + }), + }; + let mapped = map_error(error); + assert!(matches!(mapped, Error::NotSupported { .. })); + let diagnostic = mapped.to_string(); + assert!(diagnostic.contains("query-job")); + assert!(diagnostic.contains("cleanup-request")); + } + + #[test] + fn cleanup_statement_preserves_inheritance_zero_and_quoting() { + assert_eq!( + statement("events", None, &CleanupOptions::new()).unwrap(), + "VACUUM \"events\"" + ); + assert_eq!( + statement( + "a\"b", + Some("o'brien"), + &CleanupOptions::new().min_age_seconds(0) + ) + .unwrap(), + "VACUUM \"a\"\"b\" WITH (branch = 'o''brien', min_age_seconds = 0)" + ); + assert!(statement("t", None, &CleanupOptions::new().min_age_seconds(u64::MAX)).is_err()); + } + + #[test] + fn ambiguous_cleanup_receipts_never_become_query_handles() { + let batch = |values: Vec>| { + RecordBatch::try_from_iter([( + "job_id", + Arc::new(StringArray::from(values)) as arrow_array::ArrayRef, + )]) + .unwrap() + }; + for batches in [ + vec![], + vec![batch(vec![])], + vec![batch(vec![None])], + vec![batch(vec![Some("")])], + vec![batch(vec![Some("one"), Some("two")])], + ] { + assert!( + receipt(&batches) + .unwrap_err() + .to_string() + .contains("inspect jobs before retrying") + ); + } + assert_eq!( + receipt(&[batch(vec![]), batch(vec![Some("durable-job")])]).unwrap(), + "durable-job" + ); + } + + #[test] + fn cleanup_compatibility_preserves_permissions_and_transport_errors() { + for (code, diagnostic, expected) in [ + ( + tonic::Code::InvalidArgument, + "ParserError: found VACUUM", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown VACUUM option future", + true, + ), + (tonic::Code::PermissionDenied, "ParserError: denied", false), + (tonic::Code::Unavailable, "transport unavailable", false), + ( + tonic::Code::InvalidArgument, + "min_age_seconds is out of range", + false, + ), + ] { + let error = Error::Sql { + message: diagnostic.into(), + request_id: "cleanup-request".into(), + grpc_code: code as i32, + metadata: Default::default(), + }; + let mapped = map_error(error); + assert_eq!(matches!(mapped, Error::NotSupported { .. }), expected); + assert!(mapped.to_string().contains("cleanup-request")); + } + } +} diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index b79beca55..69a7f1b28 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -89,6 +89,8 @@ pub mod function_column_status; pub mod merge; pub mod optimize; pub use optimize::CompactionResult; +mod cleanup; +pub use cleanup::{CleanupOptions, CleanupPlan, CleanupResult}; mod prewarm; pub use prewarm::{PrewarmDataOptions, PrewarmDataPlan, PrewarmDataResult, PrewarmPruningSummary}; pub(crate) mod primary_key; @@ -907,6 +909,19 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn tags(&self) -> Result>; /// Optimize the dataset. async fn optimize(&self, action: OptimizeAction) -> Result; + /// Submit Enterprise version cleanup and retain its durable job and outcome. + async fn cleanup_async(&self, _options: CleanupOptions) -> Result> { + Err(Error::NotSupported { + message: "durable cleanup jobs are only supported on remote tables".into(), + }) + } + + async fn explain_cleanup(&self, _options: CleanupOptions) -> Result { + Err(Error::NotSupported { + message: "cleanup previews require LanceDB Enterprise".into(), + }) + } + /// Submit remote compaction and retain its durable job and actual outcome. async fn compact_async( &self, @@ -2140,6 +2155,35 @@ impl Table { self.inner.compact_async(options).await } + /// Submit durable version cleanup through SQL VACUUM and return after acceptance. + /// + /// Retention resolves invocation > selected table/branch > deployment. Requires + /// Ownership and parent Usage. Local and historical handles are unsupported. + /// Operators must disable/drain automatic cleanup and prevent other cleanup, + /// tag/branch publication and restore until completion, including direct clients. + /// The server does not enforce that coordination. Preview is available without deletion. + /// Wait, cancel and reopen reuse the shared Job APIs; timeout does not cancel, + /// and cancellation cannot undo deletion or prove storage I/O has stopped. + /// + /// ``` + /// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> { + /// let job = table.cleanup_async(lancedb::table::CleanupOptions::new() + /// .min_age_seconds(604800)).await?; + /// let result = job.wait().await?; + /// println!("{:?}", result.old_versions); + /// # Ok(()) } + /// ``` + pub async fn cleanup_async(&self, options: CleanupOptions) -> Result> { + self.inner.cleanup_async(options).await + } + + /// Explain Enterprise version cleanup without deleting files or submitting a job. + /// Requires the same ownership and retention options as [`Self::cleanup_async`]. + /// Counts are observational estimates, not a reservation for later execution. + pub async fn explain_cleanup(&self, options: CleanupOptions) -> Result { + self.inner.explain_cleanup(options).await + } + /// Language-binding entry point retaining optional compaction fields. #[doc(hidden)] pub async fn optimize_full_with_overrides( diff --git a/rust/lancedb/src/table/cleanup.rs b/rust/lancedb/src/table/cleanup.rs new file mode 100644 index 000000000..8d4eb67e6 --- /dev/null +++ b/rust/lancedb/src/table/cleanup.rs @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Options and results for durable remote version cleanup. + +/// Per-invocation retention. Omission inherits table/branch then deployment policy. +#[derive(Debug, Clone, Default)] +#[non_exhaustive] +pub struct CleanupOptions { + /// Minimum old-version age in seconds. None inherits server policy. + pub min_age_seconds: Option, +} + +impl CleanupOptions { + /// Inherit selected table/branch and deployment retention. + pub fn new() -> Self { + Self::default() + } + + /// Set the minimum old-version age in seconds; zero is explicit, not omitted. + pub fn min_age_seconds(mut self, seconds: u64) -> Self { + self.min_age_seconds = Some(seconds); + self + } +} + +/// Successful remote version cleanup. Auxiliary sweeps are best effort and +/// excluded from the counts. Retry/recovery can leave counts unknown (`None`). +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(try_from = "CleanupResultWire")] +#[non_exhaustive] +pub struct CleanupResult { + /// Objects that could not be deleted, if measured. Other removals remain committed. + pub failed_deletes: Option, + /// Public result schema version; currently 1. + pub format_version: u32, + /// Retention resolved and recorded when the server accepted this job. + pub min_age_seconds: u64, + /// Whether the entire invocation's version-deletion counts are known. + pub statistics_complete: bool, + /// Old versions removed, or None after uncertain retry/recovery. + pub old_versions: Option, + /// Bytes removed by version deletion, excluding auxiliary sweeps. + pub bytes_removed: Option, +} + +#[derive(serde::Deserialize)] +struct CleanupResultWire { + failed_deletes: Option, + format_version: u32, + min_age_seconds: u64, + statistics_complete: bool, + old_versions: Option, + bytes_removed: Option, +} + +impl TryFrom for CleanupResult { + type Error = &'static str; + fn try_from(value: CleanupResultWire) -> std::result::Result { + if value.format_version != 1 + || if value.statistics_complete { + value.old_versions.is_none() || value.bytes_removed.is_none() + } else { + value.old_versions.is_some() + || value.bytes_removed.is_some() + || value.failed_deletes.is_some() + } + { + return Err("unsupported or inconsistent cleanup result"); + } + Ok(Self { + failed_deletes: value.failed_deletes, + format_version: value.format_version, + min_age_seconds: value.min_age_seconds, + statistics_complete: value.statistics_complete, + old_versions: value.old_versions, + bytes_removed: value.bytes_removed, + }) + } +} + +/// Read-only version-deletion estimate. Execution re-evaluates current state; +/// no job or deletion snapshot is reserved and auxiliary sweeps are excluded. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct CleanupPlan { + #[serde(deserialize_with = "preview_version")] + pub format_version: u32, + pub source_version: u64, + pub min_age_seconds: u64, + pub cutoff_millis: i64, + pub versions_to_remove: u64, + pub bytes_to_remove: u64, +} + +fn preview_version<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + let version = ::deserialize(deserializer)?; + if version != 1 { + return Err(serde::de::Error::custom( + "unsupported cleanup preview format", + )); + } + Ok(version) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cleanup_result_distinguishes_known_zero_unknown_and_invalid() { + let mut value = serde_json::json!({"format_version":1,"min_age_seconds":0, + "statistics_complete":true,"old_versions":0,"bytes_removed":0,"future":true}); + assert_eq!( + serde_json::from_value::(value.clone()) + .unwrap() + .old_versions, + Some(0) + ); + value["statistics_complete"] = false.into(); + assert!(serde_json::from_value::(value.clone()).is_err()); + value["old_versions"] = serde_json::Value::Null; + value["bytes_removed"] = serde_json::Value::Null; + assert_eq!( + serde_json::from_value::(value.clone()) + .unwrap() + .old_versions, + None + ); + value["format_version"] = 2.into(); + assert!(serde_json::from_value::(value).is_err()); + } +} From 8dc03bd28828dec90c0de448e6e5354fffea1e6a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 06:41:38 +0800 Subject: [PATCH 61/78] feat: add table.delta for version-to-version row changes (#5135) Adds native `Table::delta(from_version, to_version=None)` and Python sync/async `table.delta(...)` for version-to-version row changes. `TableDelta` exposes streaming `inserted_rows()`, `updated_rows()`, `upserted_rows()`, `deleted_row_ids()`, and `list_transactions()`. Endpoints are resolved once on independent dataset handles. `to_version=None` uses the table handle's visible snapshot, and the handle's checkout is not changed. Only versions `>= 1` and tags on the current branch are accepted; cross-branch tags, reversed ranges, version 0, and missing endpoints are rejected. Equal valid endpoints return empty readers with the same schemas. Row-level readers require stable row ids at both endpoints and report the `storage_options={"new_table_enable_stable_row_ids": "true"}` creation guidance when they are absent. `list_transactions()` does not require stable row ids. Row-level readers also fail closed when the range contains a `Restore`, or when transaction history cannot prove the range is restore-free, because restored rows can retain older row-version metadata that the delta readers omit. The error directs consumers to a full rescan and reinitializing the checkpoint at the range end version. `list_transactions()` remains available for readable history. The Versioning guide includes Python and Rust checkpoint-delta examples with stable-row-ID setup and this Embedded limitation. Embedded `branches.diff()` remains a separate API. Refs OSS-2860 --- docs/src/python/python.md | 4 + docs/web-tests/py/test_table_delta_docs.py | 41 + docs/web/management/table.mdx | 44 + docs/web/snippets/table_delta_docs.mdx | 5 + python/python/lancedb/_lancedb.pyi | 14 + python/python/lancedb/remote/table.py | 14 + python/python/lancedb/table.py | 207 ++++- python/python/tests/test_table.py | 264 ++++++ python/src/lib.rs | 1 + python/src/table.rs | 117 ++- rust/lancedb/src/remote/table.rs | 13 + rust/lancedb/src/table.rs | 67 ++ rust/lancedb/src/table/delta.rs | 969 +++++++++++++++++++++ rust/lancedb/tests/table_delta_docs.rs | 135 +++ 14 files changed, 1892 insertions(+), 3 deletions(-) create mode 100644 docs/web-tests/py/test_table_delta_docs.py create mode 100644 docs/web/snippets/table_delta_docs.mdx create mode 100644 rust/lancedb/src/table/delta.rs create mode 100644 rust/lancedb/tests/table_delta_docs.rs diff --git a/docs/src/python/python.md b/docs/src/python/python.md index d6389bf83..f315910ed 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -428,6 +428,8 @@ code that used the former LanceDB Enterprise-only argument order. ::: lancedb.table.Branches +::: lancedb.table.TableDelta + ::: lancedb.RTEWriteSpec ## Functions and Jobs @@ -1317,6 +1319,8 @@ Table hold your actual data as a collection of records / rows. ::: lancedb.table.AsyncBranches +::: lancedb.table.AsyncTableDelta + ## Materialized Views (Asynchronous) ::: lancedb.materialized_view.AsyncMaterializedView diff --git a/docs/web-tests/py/test_table_delta_docs.py b/docs/web-tests/py/test_table_delta_docs.py new file mode 100644 index 000000000..15e8f3e22 --- /dev/null +++ b/docs/web-tests/py/test_table_delta_docs.py @@ -0,0 +1,41 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + + +def test_versioning_checkpoint_delta(tmp_db): + db = tmp_db + + # --8<-- [start:versioning_checkpoint_delta] + table = db.create_table( + "checkpoint_delta_example", + [ + {"id": 1, "author": "Richard", "quote": "Wubba Lubba Dub Dub!"}, + {"id": 2, "author": "Morty", "quote": "Rick, what's going on?"}, + ], + storage_options={"new_table_enable_stable_row_ids": "true"}, + mode="overwrite", + ) + table.tags.create("baseline", table.version) + table.add([{"id": 3, "author": "Summer", "quote": "Whatever, Grandpa"}]) + table.update(where="id = 2", values={"quote": "Aww geez, Rick!"}) + table.delete("id = 1") + + delta = table.delta("baseline") + print("inserted:", delta.inserted_rows().read_all()["id"].to_pylist()) + print("updated:", delta.updated_rows().read_all()["id"].to_pylist()) + print("deleted:", delta.deleted_row_ids().read_all()["_rowid"].to_pylist()) + print( + "transactions:", + [transaction["operation"] for transaction in delta.list_transactions()], + ) + # --8<-- [end:versioning_checkpoint_delta] + + assert table.version == 4 + assert delta.inserted_rows().read_all()["id"].to_pylist() == [3] + assert delta.updated_rows().read_all()["id"].to_pylist() == [2] + assert delta.deleted_row_ids().read_all().num_rows == 1 + assert [transaction["operation"] for transaction in delta.list_transactions()] == [ + "Append", + "Update", + "Delete", + ] diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 14c1a9fc2..e09369dbd 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -87,6 +87,10 @@ import { RsVersioningTags as RsVersioningTags, RsVersioningMakeQuotesReader as RsVersioningMakeQuotesReader, } from '/snippets/tables.mdx'; +import { + PyVersioningCheckpointDelta as VersioningCheckpointDelta, + RsVersioningCheckpointDelta as RsVersioningCheckpointDelta, +} from '/snippets/table_delta_docs.mdx'; import { PyMultimodalImports as MultimodalImports, TsMultimodalImports as TsMultimodalImports, @@ -1766,6 +1770,46 @@ Deleting a tag only removes the label, not the version it points to. After deletion, the underlying table version becomes eligible for cleanup again. +{/* +Draft until the checkpoint-delta API is released. + +### Compute changes since a checkpoint {#versioning-checkpoint-delta} + +Use `table.delta(from_version, to_version=None)` to stream the rows inserted, +updated, or deleted since a checkpoint. Tag the checkpoint version, then create +a delta from that tag. Omitting `to_version` uses the table's current visible +snapshot. The endpoints are fixed when the delta is created, so later writes or +tag moves do not change the comparison. + +The row-level readers require stable row IDs at both endpoints. Create the table +with stable row IDs enabled, as shown below. If a table does not have them, the +row-level readers explain how to recreate it with the option. `list_transactions()` +reports the transactions in the range and works without stable row IDs. + +This preview supports Python and Rust for LanceDB Embedded. TypeScript support +is a follow-up. The API accepts versions and tags on the current branch only, +and rejects tags that belong to another branch. LanceDB Enterprise tables do +not support row-level deltas. + +A `Restore` can reintroduce rows with older row-version metadata that the delta +readers do not report as changed. For that reason, the row-level readers reject +a nonempty range that contains a `Restore`. They also reject a range whose +transaction history is incomplete, because they cannot rule out a hidden +`Restore`. Recompute the checkpoint with a full rescan and reinitialize it at +the range end version. `list_transactions()` remains available for the same +range. Branch-vs-main summaries remain a separate `branches.diff()` API. + + + + {VersioningCheckpointDelta} + + + + {RsVersioningCheckpointDelta} + + +*/} + {/* Draft until branching reaches early access. diff --git a/docs/web/snippets/table_delta_docs.mdx b/docs/web/snippets/table_delta_docs.mdx new file mode 100644 index 000000000..a1beb901b --- /dev/null +++ b/docs/web/snippets/table_delta_docs.mdx @@ -0,0 +1,5 @@ +{/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} + +export const PyVersioningCheckpointDelta = "table = db.create_table(\n \"checkpoint_delta_example\",\n [\n {\"id\": 1, \"author\": \"Richard\", \"quote\": \"Wubba Lubba Dub Dub!\"},\n {\"id\": 2, \"author\": \"Morty\", \"quote\": \"Rick, what's going on?\"},\n ],\n storage_options={\"new_table_enable_stable_row_ids\": \"true\"},\n mode=\"overwrite\",\n)\ntable.tags.create(\"baseline\", table.version)\ntable.add([{\"id\": 3, \"author\": \"Summer\", \"quote\": \"Whatever, Grandpa\"}])\ntable.update(where=\"id = 2\", values={\"quote\": \"Aww geez, Rick!\"})\ntable.delete(\"id = 1\")\n\ndelta = table.delta(\"baseline\")\nprint(\"inserted:\", delta.inserted_rows().read_all()[\"id\"].to_pylist())\nprint(\"updated:\", delta.updated_rows().read_all()[\"id\"].to_pylist())\nprint(\"deleted:\", delta.deleted_row_ids().read_all()[\"_rowid\"].to_pylist())\nprint(\n \"transactions:\",\n [transaction[\"operation\"] for transaction in delta.list_transactions()],\n)\n"; + +export const RsVersioningCheckpointDelta = "use futures::TryStreamExt;\n\nlet table = db\n .create_table(\n \"checkpoint_delta_example\",\n make_quotes_reader(vec![\n (1, \"Richard\", \"Wubba Lubba Dub Dub!\"),\n (2, \"Morty\", \"Rick, what's going on?\"),\n ]),\n )\n .storage_option(\"new_table_enable_stable_row_ids\", \"true\")\n .execute()\n .await?;\n\nlet mut tags = table.tags().await?;\ntags.create(\"baseline\", table.version().await?).await?;\ntable\n .add(make_quotes_reader(vec![(3, \"Summer\", \"Whatever, Grandpa\")]))\n .execute()\n .await?;\ntable\n .update()\n .only_if(\"id = 2\")\n .column(\"quote\", \"'Aww geez, Rick!'\")\n .execute()\n .await?;\ntable.delete(\"id = 1\").await?;\n\nlet delta = table.delta(\"baseline\", None).await?;\nlet mut inserted = delta.inserted_rows().await?;\nwhile let Some(batch) = inserted.try_next().await? {\n println!(\"inserted: {:?}\", batch.column_by_name(\"id\"));\n}\nlet mut deleted = delta.deleted_row_ids().await?;\nwhile let Some(batch) = deleted.try_next().await? {\n println!(\"deleted row ids: {batch:?}\");\n}\nfor transaction in delta.list_transactions().await? {\n println!(\"{}\", transaction.operation.name());\n}\n"; diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index c1177e849..7af833c79 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -649,6 +649,11 @@ class Table: ) -> Job: ... async def list_versions(self) -> List[Dict[str, Any]]: ... async def version(self) -> int: ... + async def delta( + self, + from_version: Union[int, str], + to_version: Optional[Union[int, str]] = None, + ) -> TableDelta: ... async def checkout(self, version: Union[int, str]): ... async def checkout_latest(self): ... async def _checkout_current(self) -> Table: ... @@ -966,6 +971,15 @@ class ColumnOrdering(TypedDict): ascending: bool nulls_first: bool +class TableDelta: + def begin_version(self) -> int: ... + def end_version(self) -> int: ... + async def inserted_rows(self) -> RecordBatchStream: ... + async def updated_rows(self) -> RecordBatchStream: ... + async def upserted_rows(self) -> RecordBatchStream: ... + async def deleted_row_ids(self) -> RecordBatchStream: ... + async def list_transactions(self) -> List[Dict[str, Any]]: ... + class Query: def where(self, filter: str): ... def where_expr(self, expr: PyExpr): ... diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index f0722acd0..4fe2c3175 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -85,6 +85,7 @@ from ..table import ( IndexStatistics, Query, Table, + TableDelta, Tags, ) from ..types import BaseTokenizerType, ScalarIndexType @@ -287,6 +288,19 @@ class RemoteTable(Table): """List all versions of the table""" return LOOP.run(self._table.list_versions()) + def delta( + self, + from_version: int | str, + to_version: Optional[int | str] = None, + ) -> TableDelta: + """Compare two versions or tags. + + Streamed version deltas are not supported by LanceDB Enterprise tables; + this raises ``NotImplementedError``. + """ + async_delta = LOOP.run(self._table.delta(from_version, to_version)) + return TableDelta(async_delta._inner) + def to_arrow(self, *, blob_mode: BlobMode = "lazy") -> pa.Table: """to_arrow() is not supported in LanceDB Enterprise.""" validate_blob_mode(blob_mode) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 9cd82638d..52212a3de 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -46,7 +46,7 @@ from ._blob import ( validate_blob_mode, ) from .types import BlobMode -from lancedb.arrow import peek_reader +from lancedb.arrow import AsyncRecordBatchReader, peek_reader from lancedb.sql import QueryParameters, to_parameter_batch from lancedb.background_loop import LOOP, embedding_executor from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult @@ -1598,6 +1598,63 @@ class Table(ABC): """The branch this table handle is scoped to, or ``None`` for ``main``.""" raise NotImplementedError("current_branch is not supported for this table type") + def delta( + self, + from_version: int | str, + to_version: Optional[int | str] = None, + ) -> "TableDelta": + """Compare two persisted versions of this table on its current branch. + + ``from_version`` is exclusive and ``to_version`` is inclusive. Both + accept a version number (starting at 1) or a tag on the current branch. + Omitting ``to_version`` uses the version this handle currently sees, + including a time-travel checkout. Endpoints are resolved once when this + method is called, so moving a tag or advancing the table later does not + change the delta, and this table's checkout state is left untouched. + + The returned [TableDelta][lancedb.table.TableDelta] streams inserted, + updated, upserted, and deleted rows. Those row-level readers require + stable row ids at both endpoints; create the table with + ``storage_options={"new_table_enable_stable_row_ids": "true"}`` to + enable them. ``list_transactions()`` works without stable row ids. + Equal valid versions produce empty readers with the same schemas. + + Reversed ranges, version 0, missing versions or tags, and tags from a + different branch are rejected. A row-level range that contains a + ``Restore``, or whose transaction history is incomplete, is rejected + because the restored snapshot can retain older row-version metadata that + the delta readers would omit; recompute the checkpoint with a full + rescan and reinitialize it at the end version. Remote tables raise + ``NotImplementedError``. + + Parameters + ---------- + from_version: int | str + The version or tag to compare from (exclusive). + to_version: int | str, optional + The version or tag to compare to (inclusive). Defaults to the + currently visible version. + + Examples + -------- + >>> import lancedb + >>> db = lancedb.connect("memory://") + >>> table = db.create_table( + ... "delta_example", + ... [{"id": 1}, {"id": 2}], + ... storage_options={"new_table_enable_stable_row_ids": "true"}, + ... ) + >>> table.tags.create("baseline", table.version) + >>> _ = table.add([{"id": 3}]) + >>> delta = table.delta("baseline") + >>> inserted = delta.inserted_rows().read_all() + >>> inserted["id"].to_pylist() + [3] + >>> [transaction["operation"] for transaction in delta.list_transactions()] + ['Append'] + """ + raise NotImplementedError("delta is not supported for this table type") + def __len__(self) -> int: """The number of rows in this Table""" return self.count_rows(None) @@ -4618,6 +4675,18 @@ class LanceTable(Table): """List all versions of the table""" return LOOP.run(self._table.list_versions()) + def delta( + self, + from_version: int | str, + to_version: Optional[int | str] = None, + ) -> "TableDelta": + """Compare two versions or tags. + + See [Table.delta][lancedb.table.Table.delta]. + """ + async_delta = LOOP.run(self._table.delta(from_version, to_version)) + return TableDelta(async_delta._inner) + @property def version(self) -> int: """Get the current version of the table""" @@ -9764,6 +9833,20 @@ class AsyncTable: return versions + async def delta( + self, + from_version: int | str, + to_version: Optional[int | str] = None, + ) -> "AsyncTableDelta": + """Compare two versions or tags. + + See [Table.delta][lancedb.table.Table.delta] for endpoint, stable-row-id, + and branch-tag semantics. The returned + [AsyncTableDelta][lancedb.table.AsyncTableDelta] streams + ``AsyncRecordBatchReader`` values. + """ + return AsyncTableDelta(await self._inner.delta(from_version, to_version)) + async def checkout(self, version: int | str): """ Checks out a specific version of the Table @@ -10569,6 +10652,128 @@ class Branches: return self._parent._wrap_branch_handle(async_table, version) +class TableDelta: + """Streaming row changes between two table versions. + + Created by [Table.delta][lancedb.table.Table.delta]. The endpoints are + fixed when the delta is created. + + Row-level readers require stable row ids at both endpoints. Create the + table with ``storage_options={"new_table_enable_stable_row_ids": "true"}`` + to enable them. [list_transactions][lancedb.table.TableDelta.list_transactions] + works without stable row ids. + + A nonempty range that contains a ``Restore``, or whose transaction history + is incomplete, rejects the row-level readers. Recompute the checkpoint with + a full rescan and reinitialize it at the end version; transaction history + remains available. + """ + + def __init__(self, inner: Any): + self._inner = inner + self._async = AsyncTableDelta(inner) + + @property + def begin_version(self) -> int: + """The version this delta starts from (exclusive).""" + return self._inner.begin_version() + + @property + def end_version(self) -> int: + """The version this delta ends at (inclusive).""" + return self._inner.end_version() + + def inserted_rows(self) -> pa.RecordBatchReader: + """Stream rows inserted in ``(begin_version, end_version]``. + + Each batch carries the table columns plus ``_rowid``, + ``_row_created_at_version``, and ``_row_last_updated_at_version``. + """ + return _record_batch_reader(LOOP.run(self._async.inserted_rows())) + + def updated_rows(self) -> pa.RecordBatchReader: + """Stream rows updated in ``(begin_version, end_version]``. + + Newly inserted rows are excluded; use + [upserted_rows][lancedb.table.TableDelta.upserted_rows] for both. + """ + return _record_batch_reader(LOOP.run(self._async.updated_rows())) + + def upserted_rows(self) -> pa.RecordBatchReader: + """Stream inserted and updated rows in ``(begin_version, end_version]``.""" + return _record_batch_reader(LOOP.run(self._async.upserted_rows())) + + def deleted_row_ids(self) -> pa.RecordBatchReader: + """Stream the ``_rowid`` values of rows deleted in the range. + + Each batch carries one ``_rowid`` column of type ``uint64``. Deleted + rows are not reconstructed from earlier versions. + """ + return _record_batch_reader(LOOP.run(self._async.deleted_row_ids())) + + def list_transactions(self) -> List[Dict[str, Any]]: + """List transactions committed in ``(begin_version, end_version]``. + + Each item has ``read_version``, ``uuid``, ``operation``, ``tag``, and + ``transaction_properties``. Unlike row readers, this works without + stable row ids. + """ + return LOOP.run(self._async.list_transactions()) + + +class AsyncTableDelta: + """Async streaming row changes between two table versions. + + Created by [AsyncTable.delta][lancedb.table.AsyncTable.delta]. See + [TableDelta][lancedb.table.TableDelta] for the endpoint and stable-row-id + contract. + """ + + def __init__(self, inner: Any): + self._inner = inner + + @property + def begin_version(self) -> int: + """The version this delta starts from (exclusive).""" + return self._inner.begin_version() + + @property + def end_version(self) -> int: + """The version this delta ends at (inclusive).""" + return self._inner.end_version() + + async def inserted_rows(self) -> AsyncRecordBatchReader: + """Stream rows inserted in ``(begin_version, end_version]``.""" + return AsyncRecordBatchReader(await self._inner.inserted_rows()) + + async def updated_rows(self) -> AsyncRecordBatchReader: + """Stream rows updated in ``(begin_version, end_version]``.""" + return AsyncRecordBatchReader(await self._inner.updated_rows()) + + async def upserted_rows(self) -> AsyncRecordBatchReader: + """Stream inserted and updated rows in ``(begin_version, end_version]``.""" + return AsyncRecordBatchReader(await self._inner.upserted_rows()) + + async def deleted_row_ids(self) -> AsyncRecordBatchReader: + """Stream the ``_rowid`` values of rows deleted in the range.""" + return AsyncRecordBatchReader(await self._inner.deleted_row_ids()) + + async def list_transactions(self) -> List[Dict[str, Any]]: + """List transactions committed in ``(begin_version, end_version]``.""" + return await self._inner.list_transactions() + + +def _record_batch_reader(stream) -> pa.RecordBatchReader: + def iter_sync(): + try: + while True: + yield LOOP.run(stream.__anext__()) + except StopAsyncIteration: + return + + return pa.RecordBatchReader.from_batches(stream.schema, iter_sync()) + + class AsyncTags: """ Async table tag manager. diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index c9a587950..420a29bd4 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1373,6 +1373,270 @@ def test_versioning(mem_db: DBConnection): assert len(table) == 2 +def test_delta_streams_and_pins_endpoints(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table( + "delta", + data=[ + {"id": 1, "value": 0}, + {"id": 2, "value": 0}, + ], + storage_options={"new_table_enable_stable_row_ids": "true"}, + ) + + table.add([{"id": 3, "value": 0}]) + table.tags.create("baseline", 2) + table.update(where="id = 1", values_sql={"value": "value + 10"}) + table.delete("id = 2") + assert table.version == 4 + + delta = table.delta(1) + assert delta.begin_version == 1 + assert delta.end_version == 4 + + inserted = delta.inserted_rows().read_all() + assert inserted["id"].to_pylist() == [3] + assert inserted.schema.names == [ + "id", + "value", + "_rowid", + "_row_created_at_version", + "_row_last_updated_at_version", + ] + + updated = delta.updated_rows().read_all() + assert updated["id"].to_pylist() == [1] + assert updated["value"].to_pylist() == [10] + + upserted = delta.upserted_rows().read_all() + assert sorted(upserted["id"].to_pylist()) == [1, 3] + + deleted = delta.deleted_row_ids().read_all() + assert deleted.schema.names == ["_rowid"] + assert deleted.schema.field("_rowid").type == pa.uint64() + assert deleted.num_rows == 1 + + transactions = delta.list_transactions() + assert [transaction["operation"] for transaction in transactions] == [ + "Append", + "Update", + "Delete", + ] + assert transactions[0]["read_version"] == 1 + + # Tags are resolved on the current branch and can be either endpoint. + from_tag = table.delta("baseline") + assert from_tag.begin_version == 2 + assert from_tag.end_version == 4 + assert from_tag.updated_rows().read_all()["id"].to_pylist() == [1] + + to_tag = table.delta(1, "baseline") + assert to_tag.end_version == 2 + assert to_tag.inserted_rows().read_all()["id"].to_pylist() == [3] + + # Equal valid versions keep the reader schemas even when no rows change. + equal = table.delta(2, 2) + empty_inserted = equal.inserted_rows().read_all() + assert empty_inserted.num_rows == 0 + assert empty_inserted.schema == inserted.schema + empty_deleted = equal.deleted_row_ids().read_all() + assert empty_deleted.num_rows == 0 + assert empty_deleted.schema.names == ["_rowid"] + + # Reversed, zero, missing, and missing-tag endpoints are input errors. + with pytest.raises(ValueError, match="newer than"): + table.delta(4, 2) + with pytest.raises(ValueError, match="start at 1"): + table.delta(0) + with pytest.raises(ValueError, match="does not exist"): + table.delta(999) + with pytest.raises(ValueError, match="does not exist"): + table.delta("missing-tag") + + # An omitted target follows the visible checkout and leaves the shared + # checkout in place. + table.checkout(2) + checked_out = table.delta(1) + assert checked_out.end_version == 2 + assert checked_out.inserted_rows().read_all()["id"].to_pylist() == [3] + assert table.version == 2 + + # An explicit target works from a pinned handle without moving it. + explicit = table.delta(1, 3) + assert explicit.updated_rows().read_all()["id"].to_pylist() == [1] + assert table.version == 2 + table.checkout_latest() + assert table.version == 4 + + +@pytest.mark.parametrize("mutation", ["update", "delete"]) +def test_delta_rejects_restore_ranges(tmp_path, mutation): + table = lancedb.connect(tmp_path).create_table( + "restore_delta", + [{"id": 1, "value": 0}], + storage_options={"new_table_enable_stable_row_ids": "true"}, + ) + if mutation == "update": + table.update(values={"value": 10}) + else: + table.delete("id = 1") + assert table.version == 2 + + table.restore(1) + assert table.version == 3 + assert table.to_arrow().to_pylist() == [{"id": 1, "value": 0}] + + restore_range = table.delta(2, 3) + assert [tx["operation"] for tx in restore_range.list_transactions()] == ["Restore"] + for reader in ( + restore_range.inserted_rows, + restore_range.updated_rows, + restore_range.upserted_rows, + restore_range.deleted_row_ids, + ): + with pytest.raises(ValueError) as exc_info: + reader() + message = str(exc_info.value) + assert "Restore" in message + assert "full rescan" in message + assert "reinitialize" in message + + # A restore in the middle of the range is still unverifiable. + table.add([{"id": 2, "value": 0}]) + assert table.version == 4 + with pytest.raises(ValueError, match="Restore"): + table.delta(2, 4).upserted_rows() + + # A restore at the exclusive boundary is the base snapshot, so later + # changes remain usable. + after_restore = table.delta(3, 4) + assert after_restore.inserted_rows().read_all()["id"].to_pylist() == [2] + assert [tx["operation"] for tx in after_restore.list_transactions()] == ["Append"] + + # Equal endpoints remain empty and do not run the restore guard. + equal = table.delta(3, 3) + assert equal.inserted_rows().read_all().num_rows == 0 + + +def test_delta_rejects_restore_after_same_uri_recreate(tmp_path): + stable = {"new_table_enable_stable_row_ids": "true"} + old_db = lancedb.connect(tmp_path) + old = old_db.create_table("t", [{"id": 1, "value": 0}], storage_options=stable) + old.add([{"id": 2, "value": 0}]) + old.add([{"id": 3, "value": 0}]) + assert [tx["operation"] for tx in old.delta(2, 3).list_transactions()] == ["Append"] + + writer_db = lancedb.connect(tmp_path) + writer_db.drop_table("t") + schema = pa.schema( + [("id", pa.int32()), ("value", pa.int32())], + metadata={"padding": "x" * (256 * 1024)}, + ) + recreated = writer_db.create_table( + "t", + pa.Table.from_pylist([{"id": 1, "value": 0}], schema=schema), + storage_options=stable, + ) + recreated.update(values={"value": 10}) + recreated.restore(1) + assert [tx["operation"] for tx in recreated.delta(2, 3).list_transactions()] == [ + "Restore" + ] + + delta = old_db.open_table("t").delta(2, 3) + assert [tx["operation"] for tx in delta.list_transactions()] == ["Restore"] + with pytest.raises(ValueError, match="Restore"): + delta.upserted_rows() + + +def test_delta_requires_stable_row_ids(mem_db: DBConnection): + table = mem_db.create_table("delta_no_stable", data=[{"id": 1}]) + table.add([{"id": 2}]) + delta = table.delta(1) + + for reader in ( + delta.inserted_rows, + delta.updated_rows, + delta.upserted_rows, + delta.deleted_row_ids, + ): + with pytest.raises(ValueError) as exc_info: + reader() + message = str(exc_info.value) + assert "new_table_enable_stable_row_ids" in message + assert "list_transactions" in message + + # Transactions remain available without stable row ids. + transactions = delta.list_transactions() + assert [transaction["operation"] for transaction in transactions] == ["Append"] + + # Equal endpoints need no row lineage, so they are empty rather than + # rejected. + version = table.version + equal = table.delta(version, version) + assert equal.inserted_rows().read_all().num_rows == 0 + assert equal.deleted_row_ids().read_all().num_rows == 0 + + +def test_delta_rejects_cross_branch_tags(tmp_path): + db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0)) + table = db.create_table( + "delta_branches", + data=[{"id": 0}], + storage_options={"new_table_enable_stable_row_ids": "true"}, + ) + branch = table.branches.create("exp") + branch.add([{"id": 1}]) + table.add([{"id": 100}, {"id": 101}, {"id": 102}]) + assert branch.version == table.version + + table.tags.create("main_tag", table.version) + branch.tags.create("exp_tag", branch.version) + + # The same-branch tag resolves through the branch, not main's data at the + # same version number. + delta = branch.delta(1, "exp_tag") + assert delta.inserted_rows().read_all()["id"].to_pylist() == [1] + + # Cross-branch tags are rejected even though the version number exists on + # both branches. + with pytest.raises(ValueError) as exc_info: + branch.delta("main_tag") + message = str(exc_info.value) + assert "main_tag" in message + assert "main" in message + assert "exp" in message + + with pytest.raises(ValueError, match="exp_tag"): + table.delta("exp_tag") + + +@pytest.mark.asyncio +async def test_async_delta(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table( + "async_delta", + data=[{"id": 1}], + storage_options={"new_table_enable_stable_row_ids": "true"}, + ) + await table.add([{"id": 2}]) + + delta = await table.delta(1) + assert delta.begin_version == 1 + assert delta.end_version == 2 + + reader = await delta.inserted_rows() + inserted = await reader.read_all() + assert inserted[0]["id"].to_pylist() == [2] + + transactions = await delta.list_transactions() + assert [transaction["operation"] for transaction in transactions] == ["Append"] + + equal = await table.delta(2, 2) + reader = await equal.inserted_rows() + assert await reader.read_all() == [] + + def test_tags(mem_db: DBConnection): table = mem_db.create_table( "test", diff --git a/python/src/lib.rs b/python/src/lib.rs index a8217d2b1..4680aab4c 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -98,6 +98,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(catalog::connect_catalog, m)?)?; m.add_class::()?; m.add_class::
          ()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/python/src/table.rs b/python/src/table.rs index c94b3c106..7b92eab27 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -29,10 +29,10 @@ use lancedb::blob::{BlobDescriptor, BlobFile, BlobRangeRequest}; use lancedb::connection::LanceFileVersion; use lancedb::index::scalar::FtsIndexBuilder; use lancedb::table::{ - AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration, + AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, DeltaRef, Duration, FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig, FunctionRefreshPodResources, FunctionWorkerResourceBudget, IndexRemapMode, NewColumnTransform, - Ref, RefreshColumnOptions, Table as LanceDbTable, + Ref, RefreshColumnOptions, Table as LanceDbTable, TableDelta as LanceDbTableDelta, }; use lancedb::tokenize as lancedb_tokenize; use pyo3::{ @@ -2075,6 +2075,22 @@ impl Table { ) } + #[pyo3(signature = (from_version, to_version=None))] + pub fn delta( + self_: PyRef<'_, Self>, + from_version: LanceVersion, + to_version: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let delta = inner + .delta(from_version, to_version.map(Into::into)) + .await + .infer_error()?; + Ok(TableDelta::new(delta)) + }) + } + pub fn list_versions(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -3244,6 +3260,103 @@ pub enum LanceVersion { Tag(String), } +impl From for DeltaRef { + fn from(version: LanceVersion) -> Self { + match version { + LanceVersion::Version(version) => DeltaRef::Version(version), + LanceVersion::Tag(tag) => DeltaRef::Tag(tag), + } + } +} + +/// Streaming row changes between two table versions. +#[pyclass] +pub struct TableDelta { + inner: Arc, +} + +impl TableDelta { + fn new(inner: LanceDbTableDelta) -> Self { + Self { + inner: Arc::new(inner), + } + } +} + +#[pymethods] +impl TableDelta { + /// The version this delta starts from (exclusive). + pub fn begin_version(&self) -> u64 { + self.inner.begin_version() + } + + /// The version this delta ends at (inclusive). + pub fn end_version(&self) -> u64 { + self.inner.end_version() + } + + pub fn inserted_rows(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + let stream = inner.inserted_rows().await.infer_error()?; + Ok(crate::arrow::RecordBatchStream::new(stream.into())) + }) + } + + pub fn updated_rows(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + let stream = inner.updated_rows().await.infer_error()?; + Ok(crate::arrow::RecordBatchStream::new(stream.into())) + }) + } + + pub fn upserted_rows(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + let stream = inner.upserted_rows().await.infer_error()?; + Ok(crate::arrow::RecordBatchStream::new(stream.into())) + }) + } + + pub fn deleted_row_ids(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + let stream = inner.deleted_row_ids().await.infer_error()?; + Ok(crate::arrow::RecordBatchStream::new(stream.into())) + }) + } + + pub fn list_transactions(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + let transactions = inner.list_transactions().await.infer_error()?; + Python::attach(|py| { + let output = PyList::empty(py); + for transaction in transactions { + let item = PyDict::new(py); + item.set_item("read_version", transaction.read_version)?; + item.set_item("uuid", transaction.uuid)?; + item.set_item("operation", transaction.operation.name())?; + item.set_item("tag", transaction.tag)?; + match transaction.transaction_properties { + Some(properties) => { + let py_properties = PyDict::new(py); + for (key, value) in properties.iter() { + py_properties.set_item(key, value)?; + } + item.set_item("transaction_properties", py_properties)?; + } + None => item.set_item("transaction_properties", py.None())?, + } + output.append(item)?; + } + Ok(output.unbind()) + }) + }) + } +} + #[derive(FromPyObject)] #[pyo3(from_item_all)] pub struct MergeInsertParams { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index bb647d819..023f3bb69 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -5251,6 +5251,19 @@ mod tests { } } + #[tokio::test] + async fn test_delta_not_supported() { + let table = Table::new_with_handler("my_table", |_| -> http::Response { + panic!("table.delta must not send a remote request") + }); + + let error = table.delta(1u64, None).await.unwrap_err(); + assert!( + matches!(error, Error::NotSupported { .. }), + "expected NotSupported, got {error:?}" + ); + } + #[tokio::test] async fn test_version() { let table = Table::new_with_handler("my_table", |request| { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 69a7f1b28..3ad3d0c24 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -84,6 +84,7 @@ mod create_index; pub mod datafusion; pub(crate) mod dataset; pub mod delete; +pub mod delta; pub mod freshness; pub mod function_column_status; pub mod merge; @@ -114,6 +115,7 @@ pub use computed_columns::{ ComputedColumn, ComputedColumnKind, computed_column_from_field, computed_columns, }; pub use delete::DeleteResult; +pub use delta::{DeltaRef, TableDelta}; pub use function_column_status::{ FunctionColumnAutoRefreshBlockedReason, FunctionColumnAutoRefreshState, FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus, @@ -1071,6 +1073,20 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn drop_columns(&self, columns: &[&str]) -> Result; /// Get the version of the table. async fn version(&self) -> Result; + /// Compare two persisted versions on this table's current branch. + /// + /// The default implementation returns [`Error::NotSupported`]; table types + /// without a local Lance dataset, such as remote tables, cannot stream row + /// changes. + async fn delta( + &self, + _from_version: DeltaRef, + _to_version: Option, + ) -> Result { + Err(Error::NotSupported { + message: "table.delta is only supported on LanceDB Embedded tables".into(), + }) + } /// Return a new table handle pinned to the exact revision currently visible. async fn checkout_current(&self) -> Result> { Err(Error::NotSupported { @@ -2923,6 +2939,48 @@ impl Table { self.inner.version().await } + /// Compare two persisted versions of this table on its current branch. + /// + /// `from_version` is exclusive and `to_version` is inclusive. Both accept + /// a version number (starting at 1) or a tag on the current branch. + /// Omitting `to_version` uses the version this handle currently sees, + /// including a time-travel [`Self::checkout`]. The endpoints are resolved + /// once when this method is called, so moving a tag or advancing the table + /// later does not change the delta, and the table's own checkout state is + /// left untouched. + /// + /// The returned [`TableDelta`] streams the rows inserted, updated, + /// upserted, or deleted between the endpoints. Those row-level readers + /// require stable row ids at both endpoints; create the table with + /// `storage_options={"new_table_enable_stable_row_ids": "true"}` to enable + /// them. [`TableDelta::list_transactions`] works without stable row ids. + /// Equal valid versions produce empty streams with the same schemas. + /// + /// Reversed ranges, version 0, missing versions or tags, and tags from a + /// different branch are rejected. A row-level range that contains a + /// `Restore`, or whose transaction history is incomplete, is rejected + /// because the restored snapshot can retain older row-version metadata that + /// the delta readers would omit; recompute the checkpoint with a full + /// rescan and reinitialize it at the end version. Remote tables return + /// [`Error::NotSupported`]. + /// + /// ```no_run + /// # use lancedb::table::DeltaRef; + /// # async fn example(table: &lancedb::Table) -> Result<(), Box> { + /// let delta = table.delta(1u64, Some(DeltaRef::Version(table.version().await?))).await?; + /// let _inserted = delta.inserted_rows().await?; + /// let transactions = delta.list_transactions().await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn delta( + &self, + from_version: impl Into, + to_version: Option, + ) -> Result { + self.inner.delta(from_version.into(), to_version).await + } + /// Return a new table handle pinned to the exact revision currently visible. /// /// This is used when asynchronous preparation must remain consistent with @@ -4270,6 +4328,15 @@ impl BaseTable for NativeTable { Ok(self.dataset.get().await?.version().version) } + async fn delta( + &self, + from_version: DeltaRef, + to_version: Option, + ) -> Result { + let visible = self.dataset.get().await?; + TableDelta::from_visible_snapshot(&visible, from_version, to_version).await + } + async fn checkout_current(&self) -> Result> { let current = self.dataset.get().await?; let dataset = dataset::DatasetConsistencyWrapper::new_time_travel( diff --git a/rust/lancedb/src/table/delta.rs b/rust/lancedb/src/table/delta.rs new file mode 100644 index 000000000..6b2bff241 --- /dev/null +++ b/rust/lancedb/src/table/delta.rs @@ -0,0 +1,969 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Streaming row changes between two persisted table versions. + +use std::sync::Arc; + +use arrow_array::RecordBatch; +use arrow_schema::{Schema as ArrowSchema, SchemaRef}; +use datafusion_common::DataFusionError; +use datafusion_physical_plan::stream::RecordBatchStreamAdapter; +use futures::stream; +use lance::Dataset; +use lance::dataset::delta::{DatasetDelta, DatasetDeltaBuilder}; +use lance::dataset::scanner::DatasetRecordBatchStream; +use lance::dataset::transaction::{Operation, Transaction}; +use lance_core::{ROW_CREATED_AT_VERSION_FIELD, ROW_ID_FIELD, ROW_LAST_UPDATED_AT_VERSION_FIELD}; + +use crate::error::{Error, Result}; + +/// A version or tag that identifies one end of a [`TableDelta`]. +/// +/// Version numbers start at 1. Tags are resolved on the table handle's current +/// branch; a tag that belongs to another branch is rejected instead of being +/// followed to that branch. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DeltaRef { + /// A persisted table version on the current branch. + Version(u64), + /// A tag that points at a version on the current branch. + Tag(String), +} + +impl From for DeltaRef { + fn from(version: u64) -> Self { + Self::Version(version) + } +} + +impl From<&str> for DeltaRef { + fn from(tag: &str) -> Self { + Self::Tag(tag.to_string()) + } +} + +impl From for DeltaRef { + fn from(tag: String) -> Self { + Self::Tag(tag) + } +} + +/// Streaming row changes between two versions of an embedded LanceDB table. +/// +/// A delta is created by [`crate::Table::delta`]. The two endpoints are +/// resolved when the delta is created, so moving a tag or advancing the table +/// afterwards does not change what the delta compares. +/// +/// Row-level readers require stable row ids at both endpoints. Tables created +/// with the default local settings do not enable them; create the table with +/// `storage_options={"new_table_enable_stable_row_ids": "true"}` to use +/// [`Self::inserted_rows`], [`Self::updated_rows`], [`Self::upserted_rows`], +/// and [`Self::deleted_row_ids`]. [`Self::list_transactions`] works without +/// stable row ids. +/// +/// A nonempty range that contains a `Restore` rejects the row-level readers, +/// because a restored snapshot can retain older row-version metadata that the +/// delta readers would omit. The same happens when transaction history in the +/// range is incomplete. Recompute the checkpoint with a full rescan and +/// reinitialize it at the end version; [`Self::list_transactions`] remains +/// available. +pub struct TableDelta { + /// The resolved start endpoint. Kept alongside the numeric version so the + /// handle remains pinned even if the source table is checked out or moves + /// forward later. + begin: Dataset, + /// The resolved end endpoint. Kept for schema construction and to pin the + /// endpoint independently of the table handle. + end: Dataset, + begin_version: u64, + end_version: u64, + delta: DatasetDelta, + transactions: Vec, + row_change_error: Option, + row_schema: SchemaRef, + deleted_schema: SchemaRef, +} + +impl std::fmt::Debug for TableDelta { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TableDelta") + .field("begin_version", &self.begin_version) + .field("end_version", &self.end_version) + .finish_non_exhaustive() + } +} + +impl TableDelta { + /// Resolve both endpoints from the snapshot currently visible through + /// `visible`. The table wrapper is not touched, so its checkout state and + /// version stay exactly as they were. + pub(crate) async fn from_visible_snapshot( + visible: &Dataset, + from_version: DeltaRef, + to_version: Option, + ) -> Result { + let begin = resolve_endpoint(visible, from_version, "from_version").await?; + let end = match to_version { + Some(to_version) => resolve_endpoint(visible, to_version, "to_version").await?, + // The visible snapshot is the implicit target, including when the + // table handle is in time-travel mode. + None => visible.clone(), + }; + + let begin_version = begin.version().version; + let end_version = end.version().version; + if begin_version > end_version { + return Err(Error::InvalidInput { + message: format!( + "delta begin version {begin_version} is newer than end version {end_version}; \ + from_version must be less than or equal to to_version" + ), + }); + } + + let delta = DatasetDeltaBuilder::new(end.clone()) + .with_begin_version(begin_version) + .with_end_version(end_version) + .build()?; + + // Read the pinned range once so every row reader shares the same + // Restore/history check instead of scanning it again. Use the end + // dataset because its branch is the one the delta is pinned to. + let (transactions, row_change_error) = if begin_version == end_version { + (Vec::new(), None) + } else { + read_range_history(&end, begin_version, end_version).await? + }; + + Ok(Self { + row_schema: row_change_schema(&end), + deleted_schema: deleted_row_ids_schema(), + begin, + end, + begin_version, + end_version, + delta, + transactions, + row_change_error, + }) + } + + /// The version this delta starts from (exclusive). + pub fn begin_version(&self) -> u64 { + self.begin_version + } + + /// The version this delta ends at (inclusive). + pub fn end_version(&self) -> u64 { + self.end_version + } + + /// Stream rows inserted in `(begin_version, end_version]`. + /// + /// Each batch carries the table columns plus `_rowid`, + /// `_row_created_at_version`, and `_row_last_updated_at_version`, read as + /// of the end version. + pub async fn inserted_rows(&self) -> Result { + self.scan_rows(DeltaRowChange::Inserted).await + } + + /// Stream rows updated in `(begin_version, end_version]`. + /// + /// Newly inserted rows are excluded; see [`Self::upserted_rows`] for both. + /// Each batch carries the table columns plus `_rowid`, + /// `_row_created_at_version`, and `_row_last_updated_at_version`, read as + /// of the end version. + pub async fn updated_rows(&self) -> Result { + self.scan_rows(DeltaRowChange::Updated).await + } + + /// Stream inserted and updated rows in `(begin_version, end_version]`. + /// + /// Each batch carries the table columns plus `_rowid`, + /// `_row_created_at_version`, and `_row_last_updated_at_version`, read as + /// of the end version. + pub async fn upserted_rows(&self) -> Result { + self.scan_rows(DeltaRowChange::Upserted).await + } + + /// Stream the ids of rows deleted in `(begin_version, end_version]`. + /// + /// Each batch carries one `_rowid` column of type `UInt64`. Deleted rows + /// are not reconstructed from earlier versions. + pub async fn deleted_row_ids(&self) -> Result { + if self.begin_version == self.end_version { + return Ok(empty_stream(self.deleted_schema.clone())); + } + self.ensure_row_changes_allowed()?; + Ok(self.delta.get_deleted_row_ids().await?) + } + + /// List the transactions committed in `(begin_version, end_version]`. + /// + /// Unlike the row readers, this does not require stable row ids. A version + /// with no readable transaction entry is skipped; the returned list keeps + /// any transactions that are available. + pub async fn list_transactions(&self) -> Result> { + Ok(self.transactions.clone()) + } + + async fn scan_rows(&self, change: DeltaRowChange) -> Result { + if self.begin_version == self.end_version { + return Ok(empty_stream(self.row_schema.clone())); + } + self.ensure_row_changes_allowed()?; + let rows = match change { + DeltaRowChange::Inserted => self.delta.get_inserted_rows().await?, + DeltaRowChange::Updated => self.delta.get_updated_rows().await?, + DeltaRowChange::Upserted => self.delta.get_upserted_rows().await?, + }; + Ok(rows) + } + + fn ensure_row_changes_allowed(&self) -> Result<()> { + if let Some(message) = &self.row_change_error { + return Err(Error::InvalidInput { + message: message.clone(), + }); + } + self.ensure_stable_row_ids() + } + + fn ensure_stable_row_ids(&self) -> Result<()> { + if self.begin.manifest().uses_stable_row_ids() && self.end.manifest().uses_stable_row_ids() + { + return Ok(()); + } + Err(Error::InvalidInput { + message: format!( + "row-level delta requires stable row ids at both endpoints (versions {} and {}); \ + create the table with storage_options={{\"new_table_enable_stable_row_ids\": \"true\"}} \ + to use inserted_rows(), updated_rows(), upserted_rows(), or deleted_row_ids(). \ + list_transactions() is available without stable row ids", + self.begin_version, self.end_version + ), + }) + } +} + +/// Read the pinned range's transactions through Lance's lineage-aware, +/// cache-bypassing path. This matters when a table is dropped and recreated at +/// the same URI in the same session: `read_transaction()` can return the old +/// incarnation's transaction for a version number. +async fn read_range_history( + end: &Dataset, + begin_version: u64, + end_version: u64, +) -> Result<(Vec, Option)> { + let mut transactions = Vec::new(); + let mut missing_transactions = 0u64; + let mut has_restore = false; + + for version in (begin_version + 1)..=end_version { + let record = end.read_version_transaction(version).await?; + match record.transaction { + Some(transaction) => { + if matches!(&transaction.operation, Operation::Restore { .. }) { + has_restore = true; + } + transactions.push(transaction); + } + // A missing entry is readable as a gap for list_transactions(), but + // it cannot prove the version was not a Restore. + None => missing_transactions += 1, + } + } + + let row_change_error = row_change_error( + begin_version, + end_version, + has_restore, + missing_transactions, + ); + Ok((transactions, row_change_error)) +} + +fn row_change_error( + begin_version: u64, + end_version: u64, + has_restore: bool, + missing_transactions: u64, +) -> Option { + if begin_version == end_version { + return None; + } + if has_restore { + return Some(format!( + "row-level table.delta cannot verify versions ({begin_version}, {end_version}] \ + because the range contains a Restore; a restore can reintroduce rows with older \ + row-version metadata that the delta readers omit. Recompute the checkpoint with a \ + full rescan and reinitialize it at version {end_version}, or use \ + list_transactions() to inspect the range" + )); + } + + if missing_transactions > 0 { + let expected_transactions = end_version - begin_version; + return Some(format!( + "row-level table.delta cannot verify versions ({begin_version}, {end_version}] \ + because transaction history is missing for {missing_transactions} of \ + {expected_transactions} versions; a Restore may be hidden. Recompute the checkpoint \ + with a full rescan and reinitialize it at version {end_version}, or use \ + list_transactions() to inspect the available history" + )); + } + None +} + +#[derive(Clone, Copy)] +enum DeltaRowChange { + Inserted, + Updated, + Upserted, +} + +async fn resolve_endpoint(visible: &Dataset, endpoint: DeltaRef, field: &str) -> Result { + let current_branch = visible.manifest().branch.clone(); + match endpoint { + DeltaRef::Version(version) => { + if version == 0 { + return Err(Error::InvalidInput { + message: format!( + "{field} version 0 is not a persisted table version; delta versions start at 1" + ), + }); + } + visible + .checkout_version(version) + .await + .map_err(|error| endpoint_error(error, field, current_branch.as_deref())) + } + DeltaRef::Tag(tag) => { + let tag_contents = visible + .tags() + .get(&tag) + .await + .map_err(|error| endpoint_error(error, field, current_branch.as_deref()))?; + if tag_contents.version == 0 { + return Err(Error::InvalidInput { + message: format!( + "{field} tag '{tag}' points at version 0, which is not a persisted table version" + ), + }); + } + let tag_branch = normalize_branch(tag_contents.branch.as_deref()); + if tag_branch != current_branch { + return Err(Error::InvalidInput { + message: format!( + "{field} tag '{tag}' belongs to branch '{}', but this table is on branch '{}'; \ + table.delta only compares endpoints on the current branch", + branch_label(tag_branch.as_deref()), + branch_label(current_branch.as_deref()) + ), + }); + } + visible + .checkout_version(tag_contents.version) + .await + .map_err(|error| endpoint_error(error, field, current_branch.as_deref())) + } + } +} + +fn endpoint_error(error: lance::Error, field: &str, branch: Option<&str>) -> Error { + match error { + lance::Error::VersionNotFound { message } => Error::InvalidInput { + message: format!( + "{field} does not exist on branch '{}': {message}", + branch_label(branch) + ), + }, + lance::Error::DatasetNotFound { source, .. } => Error::InvalidInput { + message: format!( + "{field} does not exist on branch '{}': {source}", + branch_label(branch) + ), + }, + lance::Error::RefNotFound { message } => Error::InvalidInput { + message: format!("{field} tag does not exist: {message}"), + }, + other => other.into(), + } +} + +fn normalize_branch(branch: Option<&str>) -> Option { + match branch { + None | Some("main") => None, + Some(name) => Some(name.to_string()), + } +} + +fn branch_label(branch: Option<&str>) -> &str { + branch.unwrap_or("main") +} + +fn row_change_schema(end: &Dataset) -> SchemaRef { + let base = ArrowSchema::from(end.schema()); + let mut fields = base.fields().to_vec(); + fields.push(Arc::new((*ROW_ID_FIELD).clone())); + fields.push(Arc::new((*ROW_CREATED_AT_VERSION_FIELD).clone())); + fields.push(Arc::new((*ROW_LAST_UPDATED_AT_VERSION_FIELD).clone())); + Arc::new(ArrowSchema::new_with_metadata( + fields, + base.metadata().clone(), + )) +} + +fn deleted_row_ids_schema() -> SchemaRef { + Arc::new(ArrowSchema::new(vec![Arc::new((*ROW_ID_FIELD).clone())])) +} + +fn empty_stream(schema: SchemaRef) -> DatasetRecordBatchStream { + let batches = stream::empty::>(); + DatasetRecordBatchStream::new(Box::pin(RecordBatchStreamAdapter::new(schema, batches))) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow_array::{Array, Int32Array, RecordBatch, UInt64Array}; + use arrow_schema::{DataType, Field, Schema as ArrowSchema}; + use futures::TryStreamExt; + use lance::dataset::WriteParams; + use lance::io::RecordBatchStream; + use lance_file::format::{MAGIC, MAJOR_VERSION, MINOR_VERSION}; + use lance_io::object_writer::ObjectWriter; + use lance_io::traits::{WriteExt, Writer}; + use lance_table::format::pb; + use tempfile::tempdir; + + use super::*; + use crate::connect; + use crate::query::{ExecutableQuery, QueryBase}; + use crate::table::{BaseTable, NativeTable, WriteOptions}; + + fn rows(ids: &[i32]) -> RecordBatch { + let schema = Arc::new(ArrowSchema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("value", DataType::Int32, false), + ])); + RecordBatch::try_new( + schema, + vec![ + Arc::new(Int32Array::from(ids.to_vec())), + Arc::new(Int32Array::from(vec![0; ids.len()])), + ], + ) + .unwrap() + } + + async fn collect(stream: DatasetRecordBatchStream) -> Vec { + stream.try_collect().await.unwrap() + } + + fn i32_column(batches: &[RecordBatch], name: &str) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch + .column_by_name(name) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect() + } + + fn u64_column(batches: &[RecordBatch], name: &str) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch + .column_by_name(name) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect() + } + + fn schema_names(schema: &ArrowSchema) -> Vec { + schema + .fields() + .iter() + .map(|field| field.name().clone()) + .collect() + } + + fn stable_row_ids() -> WriteOptions { + WriteOptions { + lance_write_params: Some(WriteParams { + enable_stable_row_ids: true, + ..Default::default() + }), + } + } + + #[tokio::test] + async fn test_delta_streams_versions_tags_and_checkout() { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()); + let conn = conn.execute().await.unwrap(); + + let table = conn + .create_table("t", rows(&[0, 1])) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + assert_eq!(table.version().await.unwrap(), 1); + + table.add(rows(&[2])).execute().await.unwrap(); + assert_eq!(table.version().await.unwrap(), 2); + let mut tags = table.tags().await.unwrap(); + tags.create("baseline", 2).await.unwrap(); + + table + .update() + .column("value", "value + 10") + .execute() + .await + .unwrap(); + assert_eq!(table.version().await.unwrap(), 3); + + // Remember the stable row id before deletion so the deleted reader can + // be checked against a value derived from the table, not the delta. + let row_id_batches = table + .query() + .only_if("id = 1") + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let deleted_row_id = u64_column(&row_id_batches, ROW_ID_FIELD.name())[0]; + + table.delete("id = 1").await.unwrap(); + assert_eq!(table.version().await.unwrap(), 4); + + let delta = table.delta(DeltaRef::Version(1), None).await.unwrap(); + assert_eq!(delta.begin_version(), 1); + assert_eq!(delta.end_version(), 4); + + let inserted = collect(delta.inserted_rows().await.unwrap()).await; + assert_eq!(i32_column(&inserted, "id"), vec![2]); + assert_eq!( + schema_names(&inserted[0].schema()), + vec![ + "id".to_string(), + "value".to_string(), + "_rowid".to_string(), + "_row_created_at_version".to_string(), + "_row_last_updated_at_version".to_string(), + ] + ); + + let updated = collect(delta.updated_rows().await.unwrap()).await; + assert_eq!(i32_column(&updated, "id"), vec![0]); + + let upserted = collect(delta.upserted_rows().await.unwrap()).await; + let mut upserted_ids = i32_column(&upserted, "id"); + upserted_ids.sort_unstable(); + assert_eq!(upserted_ids, vec![0, 2]); + + let deleted = collect(delta.deleted_row_ids().await.unwrap()).await; + assert_eq!( + u64_column(&deleted, ROW_ID_FIELD.name()), + vec![deleted_row_id] + ); + assert_eq!( + schema_names(&deleted[0].schema()), + vec!["_rowid".to_string()] + ); + assert_eq!( + deleted[0] + .column_by_name(ROW_ID_FIELD.name()) + .unwrap() + .data_type(), + &DataType::UInt64 + ); + + let transactions = delta.list_transactions().await.unwrap(); + assert_eq!( + transactions + .iter() + .map(|transaction| transaction.operation.name()) + .collect::>(), + vec!["Append", "Update", "Delete"] + ); + + // A tag is resolved on the current branch and can be either endpoint. + let from_tag = table.delta("baseline", None).await.unwrap(); + assert_eq!(from_tag.begin_version(), 2); + assert_eq!(from_tag.end_version(), 4); + let mut updated_ids = + i32_column(&collect(from_tag.updated_rows().await.unwrap()).await, "id"); + updated_ids.sort_unstable(); + // Row 2 was created exactly at the baseline, so the later update to it + // counts as an update in this range. + assert_eq!(updated_ids, vec![0, 2]); + + let to_tag = table + .delta(1u64, Some(DeltaRef::Tag("baseline".to_string()))) + .await + .unwrap(); + assert_eq!(to_tag.end_version(), 2); + let inserted = collect(to_tag.inserted_rows().await.unwrap()).await; + assert_eq!(i32_column(&inserted, "id"), vec![2]); + + // Moving a tag does not change an existing delta; a new delta sees the + // new target. + tags.update("baseline", 3).await.unwrap(); + assert_eq!(from_tag.begin_version(), 2); + assert_eq!(to_tag.end_version(), 2); + let moved_tag = table.delta("baseline", None).await.unwrap(); + assert_eq!(moved_tag.begin_version(), 3); + + // Equal endpoints are empty but keep the reader schemas, without + // needing to scan or require stable row ids again. + let equal = table.delta(2u64, Some(DeltaRef::Version(2))).await.unwrap(); + let inserted = collect(equal.inserted_rows().await.unwrap()).await; + assert!(inserted.is_empty()); + let inserted_schema = equal.inserted_rows().await.unwrap().schema(); + assert_eq!( + schema_names(&inserted_schema), + vec![ + "id".to_string(), + "value".to_string(), + "_rowid".to_string(), + "_row_created_at_version".to_string(), + "_row_last_updated_at_version".to_string(), + ] + ); + let deleted = collect(equal.deleted_row_ids().await.unwrap()).await; + assert!(deleted.is_empty()); + assert_eq!( + schema_names(&equal.deleted_row_ids().await.unwrap().schema()), + vec!["_rowid".to_string()] + ); + + // Invalid and reversed endpoints are actionable input errors. + for result in [ + table.delta(0u64, None).await, + table.delta(1u64, Some(DeltaRef::Version(0))).await, + table.delta(4u64, Some(DeltaRef::Version(2))).await, + table.delta(999u64, None).await, + table.delta(1u64, Some(DeltaRef::Version(999))).await, + table.delta("missing-tag", None).await, + table + .delta(1u64, Some(DeltaRef::Tag("missing-tag".to_string()))) + .await, + ] { + assert!( + matches!(result, Err(Error::InvalidInput { .. })), + "expected an invalid input error, got {result:?}" + ); + } + + // An omitted target follows the visible checkout and leaves the shared + // table checkout exactly where it was. + table.checkout(2).await.unwrap(); + let checked_out = table.delta(1u64, None).await.unwrap(); + assert_eq!(checked_out.end_version(), 2); + let inserted = collect(checked_out.inserted_rows().await.unwrap()).await; + assert_eq!(i32_column(&inserted, "id"), vec![2]); + assert_eq!(table.version().await.unwrap(), 2); + + // An explicit target still works from a pinned handle without moving it. + let explicit = table.delta(1u64, Some(DeltaRef::Version(3))).await.unwrap(); + let mut updated_ids = + i32_column(&collect(explicit.updated_rows().await.unwrap()).await, "id"); + updated_ids.sort_unstable(); + assert_eq!(updated_ids, vec![0, 1]); + assert_eq!(table.version().await.unwrap(), 2); + table.checkout_latest().await.unwrap(); + assert_eq!(table.version().await.unwrap(), 4); + } + + #[tokio::test] + async fn test_delta_resolves_endpoints_on_the_current_branch() { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .read_consistency_interval(std::time::Duration::ZERO) + .execute() + .await + .unwrap(); + + let main = conn + .create_table("t", rows(&[0])) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + let fork = main.version().await.unwrap(); + let branch = main.create_branch("exp", fork).await.unwrap(); + + branch.add(rows(&[1])).execute().await.unwrap(); + main.add(rows(&[100, 101, 102])).execute().await.unwrap(); + assert_eq!( + branch.version().await.unwrap(), + main.version().await.unwrap(), + "branch and main must share a version number for this test" + ); + + let mut main_tags = main.tags().await.unwrap(); + main_tags + .create("main-tag", main.version().await.unwrap()) + .await + .unwrap(); + let mut branch_tags = branch.tags().await.unwrap(); + branch_tags + .create("exp-tag", branch.version().await.unwrap()) + .await + .unwrap(); + + // The same-branch tag resolves through the branch, not main's data at + // the same version number. + let branch_delta = branch + .delta(1u64, Some(DeltaRef::Tag("exp-tag".to_string()))) + .await + .unwrap(); + let inserted = collect(branch_delta.inserted_rows().await.unwrap()).await; + assert_eq!(i32_column(&inserted, "id"), vec![1]); + + // A tag from another branch is rejected even though its version number + // also exists on this branch. + let wrong_branch = branch.delta("main-tag", None).await; + match wrong_branch { + Err(Error::InvalidInput { message }) => { + assert!(message.contains("main-tag"), "{message}"); + assert!(message.contains("exp"), "{message}"); + assert!(message.contains("main"), "{message}"); + } + other => panic!("expected cross-branch tag rejection, got {other:?}"), + } + + let wrong_branch = main.delta("exp-tag", None).await; + assert!( + matches!(wrong_branch, Err(Error::InvalidInput { .. })), + "main must reject a branch tag" + ); + } + + #[tokio::test] + async fn test_delta_rejects_restore_ranges() { + for mutation in ["update", "delete"] { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = conn + .create_table("t", rows(&[0])) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + assert_eq!(table.version().await.unwrap(), 1); + + if mutation == "update" { + table.update().column("value", "1").execute().await.unwrap(); + } else { + table.delete("id = 0").await.unwrap(); + } + assert_eq!(table.version().await.unwrap(), 2); + + table.checkout(1).await.unwrap(); + table.restore().await.unwrap(); + assert_eq!(table.version().await.unwrap(), 3); + assert_eq!(table.count_rows(None).await.unwrap(), 1); + + let restore_range = table.delta(2u64, Some(DeltaRef::Version(3))).await.unwrap(); + assert_eq!( + restore_range + .list_transactions() + .await + .unwrap() + .iter() + .map(|transaction| transaction.operation.name()) + .collect::>(), + vec!["Restore"] + ); + for result in [ + restore_range.inserted_rows().await, + restore_range.updated_rows().await, + restore_range.upserted_rows().await, + restore_range.deleted_row_ids().await, + ] { + match result { + Err(Error::InvalidInput { message }) => { + assert!(message.contains("Restore"), "{mutation}: {message}"); + assert!(message.contains("full rescan"), "{mutation}: {message}"); + assert!(message.contains("reinitialize"), "{mutation}: {message}"); + } + Ok(_) => panic!("{mutation}: restore range must be rejected"), + Err(other) => panic!("{mutation}: expected invalid input, got {other:?}"), + } + } + + // A restore in the middle of the range is still unverifiable. + table.add(rows(&[1])).execute().await.unwrap(); + assert_eq!(table.version().await.unwrap(), 4); + match table + .delta(2u64, Some(DeltaRef::Version(4))) + .await + .unwrap() + .upserted_rows() + .await + { + Err(Error::InvalidInput { message }) => { + assert!(message.contains("Restore"), "{mutation}: {message}"); + } + Ok(_) => panic!("{mutation}: restore inside the range must be rejected"), + Err(other) => panic!("{mutation}: expected invalid input, got {other:?}"), + } + + // A restore at the exclusive boundary is the base snapshot, so + // changes after it are usable. + let after_restore = table.delta(3u64, Some(DeltaRef::Version(4))).await.unwrap(); + let inserted = collect(after_restore.inserted_rows().await.unwrap()).await; + assert_eq!(i32_column(&inserted, "id"), vec![1]); + assert_eq!( + after_restore + .list_transactions() + .await + .unwrap() + .iter() + .map(|transaction| transaction.operation.name()) + .collect::>(), + vec!["Append"] + ); + + // Equal endpoints remain empty and do not run the restore guard. + let equal = table.delta(3u64, Some(DeltaRef::Version(3))).await.unwrap(); + assert!( + collect(equal.upserted_rows().await.unwrap()) + .await + .is_empty() + ); + } + } + + #[tokio::test] + async fn test_delta_rejects_missing_transaction_history() { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = conn + .create_table("t", rows(&[0])) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + table.add(rows(&[1])).execute().await.unwrap(); + let uri = table.uri().await.unwrap(); + + // Simulate a supported dataset whose latest version has no transaction + // entry. Lance cannot then tell us whether that version was a Restore, + // so row readers must fail closed instead of treating it as restore-free. + let dataset = Dataset::open(&uri).await.unwrap(); + let manifest_path = dataset.manifest_location().path.clone(); + let store = dataset.object_store(None).await.unwrap(); + let mut writer = ObjectWriter::new(store.as_ref(), &manifest_path) + .await + .unwrap(); + let mut manifest = pb::Manifest::from(dataset.manifest()); + manifest.transaction_section = None; + manifest.transaction_section_deprecated = None; + manifest.transaction_file = String::new(); + let pos = writer.write_protobuf(&manifest).await.unwrap(); + writer + .write_magics(pos, MAJOR_VERSION, MINOR_VERSION, MAGIC) + .await + .unwrap(); + Writer::shutdown(&mut writer).await.unwrap(); + drop(dataset); + drop(table); + + let table = NativeTable::open(&uri).await.unwrap(); + let delta = table.delta(DeltaRef::Version(1), None).await.unwrap(); + assert!(delta.list_transactions().await.unwrap().is_empty()); + match delta.inserted_rows().await { + Err(Error::InvalidInput { message }) => { + assert!( + message.contains("transaction history is missing"), + "{message}" + ); + assert!(message.contains("full rescan"), "{message}"); + } + Ok(_) => panic!("missing transaction history must fail closed"), + Err(other) => panic!("expected invalid input, got {other:?}"), + } + } + + #[tokio::test] + async fn test_delta_without_stable_row_ids_guides_but_lists_transactions() { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + + let table = conn.create_table("t", rows(&[0])).execute().await.unwrap(); + table.add(rows(&[1])).execute().await.unwrap(); + let delta = table.delta(1u64, None).await.unwrap(); + + for result in [ + delta.inserted_rows().await, + delta.updated_rows().await, + delta.upserted_rows().await, + delta.deleted_row_ids().await, + ] { + match result { + Err(Error::InvalidInput { message }) => { + assert!( + message.contains("new_table_enable_stable_row_ids"), + "{message}" + ); + assert!(message.contains("list_transactions"), "{message}"); + } + Ok(_) => panic!("row-level delta must require stable row ids"), + Err(other) => panic!("expected invalid input, got {other:?}"), + } + } + + // Transactions remain available without stable row ids. + let transactions = delta.list_transactions().await.unwrap(); + assert_eq!(transactions.len(), 1); + assert_eq!(transactions[0].operation.name(), "Append"); + + // Equal endpoints need no row lineage, so their readers are empty. + let version = table.version().await.unwrap(); + let equal = table + .delta(version, Some(DeltaRef::Version(version))) + .await + .unwrap(); + assert!( + collect(equal.inserted_rows().await.unwrap()) + .await + .is_empty() + ); + assert!( + collect(equal.deleted_row_ids().await.unwrap()) + .await + .is_empty() + ); + } +} diff --git a/rust/lancedb/tests/table_delta_docs.rs b/rust/lancedb/tests/table_delta_docs.rs new file mode 100644 index 000000000..0fa9c9f18 --- /dev/null +++ b/rust/lancedb/tests/table_delta_docs.rs @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::sync::Arc; + +use arrow_array::cast::AsArray; +use arrow_array::types::Int64Type; +use arrow_array::{RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; +use arrow_schema::{DataType, Field, Schema}; +fn make_quotes_reader(rows: Vec<(i64, &str, &str)>) -> Box { + let ids: Vec = rows.iter().map(|(id, _, _)| *id).collect(); + let authors: Vec<&str> = rows.iter().map(|(_, author, _)| *author).collect(); + let quotes: Vec<&str> = rows.iter().map(|(_, _, quote)| *quote).collect(); + + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("author", DataType::Utf8, false), + Field::new("quote", DataType::Utf8, false), + ])); + + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(arrow_array::Int64Array::from(ids)), + Arc::new(StringArray::from(authors)), + Arc::new(StringArray::from(quotes)), + ], + ) + .unwrap(); + Box::new(RecordBatchIterator::new( + vec![Ok(batch)].into_iter(), + schema, + )) +} + +#[tokio::test] +async fn checkpoint_delta_docs() -> anyhow::Result<()> { + let directory = tempfile::tempdir()?; + let db = lancedb::connect(directory.path().to_str().unwrap()) + .execute() + .await?; + + // --8<-- [start:versioning_checkpoint_delta] + use futures::TryStreamExt; + + let table = db + .create_table( + "checkpoint_delta_example", + make_quotes_reader(vec![ + (1, "Richard", "Wubba Lubba Dub Dub!"), + (2, "Morty", "Rick, what's going on?"), + ]), + ) + .storage_option("new_table_enable_stable_row_ids", "true") + .execute() + .await?; + + let mut tags = table.tags().await?; + tags.create("baseline", table.version().await?).await?; + table + .add(make_quotes_reader(vec![(3, "Summer", "Whatever, Grandpa")])) + .execute() + .await?; + table + .update() + .only_if("id = 2") + .column("quote", "'Aww geez, Rick!'") + .execute() + .await?; + table.delete("id = 1").await?; + + let delta = table.delta("baseline", None).await?; + let mut inserted = delta.inserted_rows().await?; + while let Some(batch) = inserted.try_next().await? { + println!("inserted: {:?}", batch.column_by_name("id")); + } + let mut deleted = delta.deleted_row_ids().await?; + while let Some(batch) = deleted.try_next().await? { + println!("deleted row ids: {batch:?}"); + } + for transaction in delta.list_transactions().await? { + println!("{}", transaction.operation.name()); + } + // --8<-- [end:versioning_checkpoint_delta] + + assert_eq!(table.version().await?, 4); + + let inserted = delta.inserted_rows().await?.try_collect::>().await?; + let inserted_ids: Vec = inserted + .iter() + .flat_map(|batch| { + batch + .column_by_name("id") + .unwrap() + .as_primitive::() + .values() + .to_vec() + }) + .collect(); + assert_eq!(inserted_ids, vec![3]); + + let updated = delta.updated_rows().await?.try_collect::>().await?; + let updated_ids: Vec = updated + .iter() + .flat_map(|batch| { + batch + .column_by_name("id") + .unwrap() + .as_primitive::() + .values() + .to_vec() + }) + .collect(); + assert_eq!(updated_ids, vec![2]); + assert_eq!( + delta + .deleted_row_ids() + .await? + .try_collect::>() + .await? + .len(), + 1 + ); + assert_eq!( + delta + .list_transactions() + .await? + .iter() + .map(|transaction| transaction.operation.name()) + .collect::>(), + vec!["Append", "Update", "Delete"] + ); + + Ok(()) +} From 61cabf1ccb59ae975f158fe083735d78378171c9 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 06:53:10 +0800 Subject: [PATCH 62/78] feat(nodejs): add tag-based branch creation and default tag versions (#5145) Node.js did not provide parity with the Python tag fixes in #5136. `tags.create()` required an explicit version, and `branches.create()` could not fork from a tag without resolving a numeric version that loses the tag's branch identity. This adds Node.js parity: - `tags.create(tag, version?)` defaults an omitted version to the version visible to the table handle, including checked-out and time-travel handles. Explicit versions are unchanged. - `branches.create(name, { fromTag })` forks through `Ref::Tag`, preserving the tag's branch and version. Existing `create(name, fromRef?, fromVersion?)` calls are unchanged. Mixing `fromTag` with another source is rejected before `main` normalization. - A missing Embedded branch keeps its original error and now includes the actual `branches.create(..., { fromTag: ... })` call as guidance. Enterprise 404s keep their original error without guessing from the message. - Enterprise uses the existing tag resolution and branch-create wire contract; no wire changes. The released web guide remains on the published package examples. The new API is documented in the TypeScript API reference and source, with Node regression coverage. --- docs/src/js/classes/Branches.md | 33 ++++- docs/src/js/classes/Tags.md | 11 +- docs/src/js/globals.md | 1 + docs/src/js/interfaces/CreateBranchOptions.md | 20 +++ nodejs/__test__/remote.test.ts | 105 ++++++++++++++++ nodejs/__test__/table.test.ts | 117 ++++++++++++++++++ nodejs/lancedb/index.ts | 1 + nodejs/lancedb/table.ts | 52 +++++++- nodejs/src/table.rs | 79 ++++++++++-- 9 files changed, 404 insertions(+), 15 deletions(-) create mode 100644 docs/src/js/interfaces/CreateBranchOptions.md diff --git a/docs/src/js/classes/Branches.md b/docs/src/js/classes/Branches.md index 6680fbfee..4e154e30f 100644 --- a/docs/src/js/classes/Branches.md +++ b/docs/src/js/classes/Branches.md @@ -64,6 +64,35 @@ with `status: "failed"` instead of throwing. ### create() +#### create(name, options) + +```ts +create(name, options): Promise
          +``` + +Create a branch from a tag and return a handle scoped to it. + +##### Parameters + +* **name**: `string` + Name of the new branch. + +* **options**: [`CreateBranchOptions`](../interfaces/CreateBranchOptions.md) + Named source. `fromTag` keeps the tag's branch and version. + +##### Returns + +`Promise`<[`Table`](Table.md)> + +##### Example + +```typescript +const branches = await table.branches(); +const branch = await branches.create("exp", { fromTag: "baseline" }); +``` + +#### create(name, fromRef, fromVersion) + ```ts create( name, @@ -73,7 +102,7 @@ create( Create a branch and return a handle scoped to it. -#### Parameters +##### Parameters * **name**: `string` Name of the new branch. @@ -84,7 +113,7 @@ Create a branch and return a handle scoped to it. * **fromVersion?**: `number` A specific version on `fromRef`. Defaults to latest. -#### Returns +##### Returns `Promise`<[`Table`](Table.md)> diff --git a/docs/src/js/classes/Tags.md b/docs/src/js/classes/Tags.md index 341673b37..dff91dd70 100644 --- a/docs/src/js/classes/Tags.md +++ b/docs/src/js/classes/Tags.md @@ -6,6 +6,8 @@ # Class: Tags +Tags label table versions with human-readable names. + ## Constructors ### new Tags() @@ -23,14 +25,19 @@ new Tags(): Tags ### create() ```ts -create(tag, version): Promise +create(tag, version?): Promise ``` +Create a tag for a table version. + +Omit `version` to tag the version this handle currently shows, +including a checked-out version. + #### Parameters * **tag**: `string` -* **version**: `number` +* **version?**: `null` \| `number` #### Returns diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 0817755fc..2b4498615 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -82,6 +82,7 @@ - [CompactionStats](interfaces/CompactionStats.md) - [ConnectNamespaceOptions](interfaces/ConnectNamespaceOptions.md) - [ConnectionOptions](interfaces/ConnectionOptions.md) +- [CreateBranchOptions](interfaces/CreateBranchOptions.md) - [CreateNamespaceOptions](interfaces/CreateNamespaceOptions.md) - [CreateNamespaceResponse](interfaces/CreateNamespaceResponse.md) - [CreateTableOptions](interfaces/CreateTableOptions.md) diff --git a/docs/src/js/interfaces/CreateBranchOptions.md b/docs/src/js/interfaces/CreateBranchOptions.md new file mode 100644 index 000000000..2cfb3406d --- /dev/null +++ b/docs/src/js/interfaces/CreateBranchOptions.md @@ -0,0 +1,20 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / CreateBranchOptions + +# Interface: CreateBranchOptions + +Options for creating a branch from a named source. + +## Properties + +### fromTag + +```ts +fromTag: string; +``` + +Tag to fork from. The tag keeps the branch and version it points to. +Cannot be combined with `fromRef` or `fromVersion`. diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 9c042c00e..1576ded54 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -1382,6 +1382,111 @@ describe("remote connection", () => { ); }); + it("forks Enterprise branches from tags and defaults tag versions", async () => { + const requests: { path: string; body: Record }[] = []; + await withMockDatabase( + (req, res) => { + const path = req.url ?? ""; + if (path.endsWith("/branches/list/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + branches: { + exp: { parentVersion: 1, createAt: 1, manifestSize: 1 }, + }, + }), + ); + return; + } + if (path.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "t", + version: 2, + schema: { fields: [] }, + }), + ); + return; + } + + let raw = ""; + req.on("data", (chunk) => { + raw += chunk; + }); + req.on("end", () => { + const body = raw ? JSON.parse(raw) : {}; + requests.push({ path, body }); + if (path.endsWith("/tags/version/")) { + res + .writeHead(200, { "Content-Type": "application/json" }) + .end(JSON.stringify({ version: 3, branch: "base" })); + return; + } + if (path.endsWith("/tags/create/")) { + res + .writeHead(200, { "Content-Type": "application/json" }) + .end("{}"); + return; + } + if (path.endsWith("/branches/create/")) { + if (body["name"] === "missing") { + res + .writeHead(404, { "Content-Type": "application/json" }) + .end(JSON.stringify({ message: "not found" })); + return; + } + res + .writeHead(200, { "Content-Type": "application/json" }) + .end("{}"); + return; + } + res.writeHead(404).end(); + }); + }, + async (db) => { + const table = await db.openTable("t", undefined, { branch: "exp" }); + await (await table.tags()).create("baseline"); + + const branches = await table.branches(); + const fromTag = await branches.create("from-tag", { + fromTag: "baseline", + }); + expect(fromTag.currentBranch()).toBe("from-tag"); + + // An Enterprise 404 is an ambiguous table-or-source failure, so the + // Embedded branch hint must not be appended based on its message. + const missing = await branches + .create("missing", { fromTag: "baseline" }) + .then( + () => undefined, + (error: Error) => error, + ); + expect(missing).toBeDefined(); + expect(missing?.message).not.toContain("fromTag"); + }, + ); + + // Omitting the tag version resolves the handle's visible branch version. + expect(requests).toContainEqual({ + path: "/v1/table/t/tags/create/", + body: { + tag: "baseline", + version: 2, + branch: "exp", + }, + }); + // A tag source uses the existing coordinate lookup and the normal + // branches/create body; there is no from_tag field on the wire. + expect(requests).toContainEqual({ + path: "/v1/table/t/tags/version/", + body: { tag: "baseline" }, + }); + expect(requests).toContainEqual({ + path: "/v1/table/t/branches/create/", + // biome-ignore lint/style/useNamingConvention: snake_case is the server wire format + body: { name: "from-tag", from_branch: "base", from_version: 3 }, + }); + }); + it("sends FTS options to remote tables", async () => { let createIndexBody: Record | undefined; diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 7aac3864c..a8bec5c98 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -4020,6 +4020,123 @@ describe("when dealing with tags", () => { await table.add([{ id: 3n, vector: [0.5, 0.6] }]); expect(await table.countRows()).toBe(2); }); + + it("defaults create version to the handle's visible version", async () => { + const conn = await connect(tmpDir.name, { + readConsistencyInterval: 0, + }); + const table = await conn.createTable("my_table", [{ id: 1 }]); + await table.add([{ id: 2 }]); + const tags = await table.tags(); + + await tags.create("live"); + expect(await tags.getVersion("live")).toBe(2); + + await table.checkout(1); + await tags.create("pinned"); + expect(await tags.getVersion("pinned")).toBe(1); + + // An explicit version is independent of the version this handle shows. + await tags.create("explicit", 2); + expect(await tags.getVersion("explicit")).toBe(2); + + // A tag checkout is still a visible version, not "latest". + await table.checkoutLatest(); + await table.add([{ id: 3 }]); + expect(await table.version()).toBe(3); + await table.checkout("live"); + await tags.create("tag-checkout"); + expect(await tags.getVersion("tag-checkout")).toBe(2); + }); +}); + +describe("when dealing with branches", () => { + let tmpDir: tmp.DirResult; + beforeEach(() => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + }); + afterEach(() => { + tmpDir.removeCallback(); + }); + + it("forks from a tag on a branch with the same version as main", async () => { + const conn = await connect(tmpDir.name, { + readConsistencyInterval: 0, + }); + const table = await conn.createTable("my_table", [{ i: 0 }]); + const branches = await table.branches(); + + const exp = await branches.create("exp"); + await exp.add([{ i: 10 }]); + const expVersion = await exp.version(); + await (await exp.tags()).create("exp-v2", expVersion); + + // main reaches the same numeric version with different rows. + await table.add([{ i: 100 }]); + expect(await table.version()).toBe(expVersion); + + const fromTag = await branches.create("from-tag", { + fromTag: "exp-v2", + }); + expect(fromTag.currentBranch()).toBe("from-tag"); + expect(await fromTag.countRows("i = 10")).toBe(1); + expect(await fromTag.countRows("i = 100")).toBe(0); + + // The existing positional branch/version path keeps its ordering. + const positional = await branches.create("from-exp", "exp", expVersion); + expect(positional.currentBranch()).toBe("from-exp"); + expect(await positional.countRows("i = 10")).toBe(1); + expect(await positional.countRows("i = 100")).toBe(0); + }); + + it("rejects fromTag combined with another source before main normalization", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("my_table", [{ i: 0 }]); + await (await table.tags()).create("baseline"); + const branches = await table.branches(); + + // fromRef="main" must not normalize the conflict away. + const mixedSources = { fromTag: "baseline", fromRef: "main" }; + await expect(branches.create("conflict", mixedSources)).rejects.toThrow( + "fromTag cannot be combined", + ); + + // JavaScript callers can still pass the legacy version position. + const createWithLegacyVersion = branches.create.bind(branches) as ( + name: string, + options: { fromTag: string }, + fromVersion: number, + ) => Promise
          ; + await expect( + createWithLegacyVersion("conflict", { fromTag: "baseline" }, 1), + ).rejects.toThrow("fromTag cannot be combined"); + expect(await branches.list()).not.toHaveProperty("conflict"); + }); + + it("hints at fromTag only for a missing Embedded branch", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("my_table", [{ i: 0 }]); + const branches = await table.branches(); + const base = await branches.create("base"); + await base.add([{ i: 1 }]); + await (await table.tags()).create("baseline"); + + // A tag passed through fromRef keeps the original failure and gains a + // static hint without probing the ref again. + await expect(branches.create("missing", "baseline")).rejects.toThrow( + 'branches.create("missing", { fromTag: "baseline" })', + ); + + // A missing version is not an unresolved branch, so it gets no hint. + const missingVersion = await branches + .create("missing-version", "base", 9999) + .then( + () => undefined, + (error: Error) => error, + ); + expect(missingVersion?.message).toContain("9999"); + expect(missingVersion?.message).not.toContain("fromTag"); + }); }); /** Returns a Date strictly later than every instant observed before the call. */ diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index d99f8675e..2e52732e6 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -164,6 +164,7 @@ export { FunctionColumnStatus, FunctionColumnVersionStatus, Branches, + CreateBranchOptions, BranchColumnSummary, BranchColumnChange, BranchIndexSummary, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 97677866e..e56711731 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -2342,6 +2342,17 @@ export interface CherryPickResult { mainVersionAfter?: number; } +/** + * Options for creating a branch from a named source. + */ +export interface CreateBranchOptions { + /** + * Tag to fork from. The tag keeps the branch and version it points to. + * Cannot be combined with `fromRef` or `fromVersion`. + */ + fromTag: string; +} + /** * Branch manager for a {@link Table}. * @@ -2364,6 +2375,18 @@ export class Branches { return await this.#inner.list(); } + /** + * Create a branch from a tag and return a handle scoped to it. + * + * @param name Name of the new branch. + * @param options Named source. `fromTag` keeps the tag's branch and version. + * @example + * ```typescript + * const branches = await table.branches(); + * const branch = await branches.create("exp", { fromTag: "baseline" }); + * ``` + */ + async create(name: string, options: CreateBranchOptions): Promise
          ; /** * Create a branch and return a handle scoped to it. * @@ -2375,8 +2398,35 @@ export class Branches { name: string, fromRef?: string, fromVersion?: number, + ): Promise
          ; + async create( + name: string, + fromRefOrOptions?: string | CreateBranchOptions, + fromVersion?: number, ): Promise
          { - return new LocalTable(await this.#inner.create(name, fromRef, fromVersion)); + if (typeof fromRefOrOptions === "object" && fromRefOrOptions !== null) { + // The public options shape only adds `fromTag`. Forward any runtime + // `fromRef`/`fromVersion` fields so the native check remains the single + // authority for rejecting mixed sources before `main` normalization. + const options = fromRefOrOptions as CreateBranchOptions & { + fromRef?: string; + fromVersion?: number; + }; + if (typeof options.fromTag !== "string") { + throw new Error("branch source options must include fromTag"); + } + return new LocalTable( + await this.#inner.create( + name, + options.fromRef, + fromVersion ?? options.fromVersion, + options.fromTag, + ), + ); + } + return new LocalTable( + await this.#inner.create(name, fromRefOrOptions, fromVersion), + ); } /** diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 20f5a43cf..5457d727a 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -20,7 +20,7 @@ use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable}; -use crate::error::NapiErrorExt; +use crate::error::{NapiErrorExt, convert_error}; use crate::index::Index; use crate::job::JobFailureInfo; use crate::merge::NativeMergeInsertBuilder; @@ -2420,6 +2420,15 @@ pub struct BranchContents { pub manifest_size: i64, } +fn from_tag_hint(name: &str, tag: &str) -> String { + let name_literal = serde_json::Value::String(name.to_string()).to_string(); + let tag_literal = serde_json::Value::String(tag.to_string()).to_string(); + format!( + "If {tag_literal} is a tag, use branches.create({name_literal}, {{ fromTag: {tag_literal} }}) instead of fromRef." + ) +} + +/// Tags label table versions with human-readable names. #[napi] pub struct Tags { inner: LanceDbTable, @@ -2458,12 +2467,20 @@ impl Tags { .default_error() } + /// Create a tag for a table version. + /// + /// Omit `version` to tag the version this handle currently shows, + /// including a checked-out version. #[napi] - pub async unsafe fn create(&mut self, tag: String, version: i64) -> napi::Result<()> { + pub async unsafe fn create(&mut self, tag: String, version: Option) -> napi::Result<()> { + let version = match version { + Some(version) => version as u64, + None => self.inner.version().await.default_error()?, + }; let mut rust_tags = self.inner.tags().await.default_error()?; rust_tags .as_mut() - .create(tag.as_str(), version as u64) + .create(tag.as_str(), version) .await .default_error() } @@ -2521,7 +2538,18 @@ impl Branches { name: String, from_ref: Option, from_version: Option, + from_tag: Option, ) -> napi::Result
          { + if from_tag.is_some() && (from_ref.is_some() || from_version.is_some()) { + return Err(napi::Error::from_reason( + "fromTag cannot be combined with fromRef or fromVersion; pass only one source", + )); + } + let from_branch = if from_tag.is_none() { + from_ref.clone() + } else { + None + }; let from_ref = from_ref.filter(|b| b != "main"); let from_version = from_version .map(|v| { @@ -2530,13 +2558,27 @@ impl Branches { }) }) .transpose()?; - let from = Ref::Version(from_ref, from_version); - let table = self - .inner - .create_branch(&name, from) - .await - .default_error()?; - Ok(Table::new(table)) + let from = match from_tag { + Some(tag) => Ref::Tag(tag), + None => Ref::Version(from_ref, from_version), + }; + match self.inner.create_branch(&name, from).await { + Ok(table) => Ok(Table::new(table)), + Err(error) => { + // A missing branch is a native NotFound. A missing version is + // VersionNotFound, and an Enterprise 404 is an ambiguous + // TableNotFound, so only the native branch case gets the hint. + let missing_branch = matches!( + &error, + lancedb::Error::Lance { source } if source.is_not_found() + ); + let mut error = convert_error(&error); + if missing_branch && let Some(branch) = from_branch.as_deref() { + error.reason = format!("{}\n{}", error.reason, from_tag_hint(&name, branch)); + } + Err(error) + } + } } #[napi] @@ -2600,3 +2642,20 @@ fn parse_cleanup_options( } Ok(options) } + +#[cfg(test)] +mod tests { + use super::from_tag_hint; + + #[test] + fn from_tag_hint_uses_escaped_javascript_string_literals() { + assert_eq!( + from_tag_hint("exp", "baseline"), + r#"If "baseline" is a tag, use branches.create("exp", { fromTag: "baseline" }) instead of fromRef."# + ); + assert_eq!( + from_tag_hint("branch\"name\\path", "tag\"name\\path"), + r#"If "tag\"name\\path" is a tag, use branches.create("branch\"name\\path", { fromTag: "tag\"name\\path" }) instead of fromRef."# + ); + } +} From 8b814731c3c42c70e39dca3740f58f7c76111623 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Fri, 20 Nov 2026 16:11:29 -0800 Subject: [PATCH 63/78] docs: use function instead of deprecated udf in examples (#5027) `lancedb.udf` is a deprecated alias of `lancedb.function` and emits a `DeprecationWarning`. This switches the quickstart and the curation examples to `function`, so readers who copy them no longer see the warning. The quickstart snippet is regenerated from its test. --- docs/web-tests/py/test_quickstart.py | 8 ++++---- docs/web/curation/aggregate.mdx | 4 ++-- docs/web/curation/join.mdx | 4 ++-- docs/web/curation/statistical-sampling.mdx | 4 ++-- docs/web/curation/vend-secret.mdx | 8 ++++---- docs/web/snippets/quickstart.mdx | 2 +- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/web-tests/py/test_quickstart.py b/docs/web-tests/py/test_quickstart.py index c0bcc3b3a..ac8396db0 100644 --- a/docs/web-tests/py/test_quickstart.py +++ b/docs/web-tests/py/test_quickstart.py @@ -350,9 +350,9 @@ def test_quickstart_derived_feature(db_path_factory): flatten_stats(table) # --8<-- [start:quickstart_add_feature] - from lancedb import col, udf + from lancedb import col, function - @udf + @function def quality_score( motion: float, sharpness: float, exposure: float, framing: float ) -> float: @@ -385,9 +385,9 @@ def test_quickstart_derived_feature_on_a_deployment(deployment): table = create_frames(deployment) flatten_stats(table) - from lancedb import col, udf + from lancedb import col, function - @udf + @function def quality_score( motion: float, sharpness: float, exposure: float, framing: float ) -> float: diff --git a/docs/web/curation/aggregate.mdx b/docs/web/curation/aggregate.mdx index 170af5696..d76861fb0 100644 --- a/docs/web/curation/aggregate.mdx +++ b/docs/web/curation/aggregate.mdx @@ -144,9 +144,9 @@ same way any other curation Function is registered: ```python Python icon="python" -from lancedb import udf +from lancedb import function -@udf +@function def caption_quality(caption: str) -> float: ... # score the caption, e.g. with a lightweight heuristic or model diff --git a/docs/web/curation/join.mdx b/docs/web/curation/join.mdx index 476bbbfed..60d5456d4 100644 --- a/docs/web/curation/join.mdx +++ b/docs/web/curation/join.mdx @@ -114,9 +114,9 @@ matched rows, not before. Register `caption_quality` first: ```python Python icon="python" -from lancedb import udf +from lancedb import function -@udf +@function def caption_quality(caption: str) -> float: ... # score the caption, e.g. with a lightweight heuristic or model diff --git a/docs/web/curation/statistical-sampling.mdx b/docs/web/curation/statistical-sampling.mdx index 2d37cefe1..8a51572d3 100644 --- a/docs/web/curation/statistical-sampling.mdx +++ b/docs/web/curation/statistical-sampling.mdx @@ -159,9 +159,9 @@ before running it over the whole table. Register `caption_quality` first: ```python Python icon="python" -from lancedb import udf +from lancedb import function -@udf +@function def caption_quality(caption: str) -> float: ... # score the caption, e.g. with a lightweight heuristic or model diff --git a/docs/web/curation/vend-secret.mdx b/docs/web/curation/vend-secret.mdx index cdebc0b8d..7d272c265 100644 --- a/docs/web/curation/vend-secret.mdx +++ b/docs/web/curation/vend-secret.mdx @@ -27,11 +27,11 @@ code already reads: ```python Python icon="python" import os -from lancedb import EnvVarSecret, udf +from lancedb import EnvVarSecret, function db.create_secret("embedding-api-key", os.environ["EMBEDDING_API_KEY"]) -@udf +@function class embed_remote: def __init__(self, model: str = "text-embedding-3-small"): import os @@ -70,12 +70,12 @@ the model is loaded once per remote instance rather than once per row: ```python import os -from lancedb import EnvVarSecret, col, udf +from lancedb import EnvVarSecret, col, function db.create_secret("hf-token", os.environ["HF_TOKEN"]) -@udf( +@function( name="embed_text", pip=["sentence-transformers==3.3.1"], ) diff --git a/docs/web/snippets/quickstart.mdx b/docs/web/snippets/quickstart.mdx index 94746f2d1..a8b638085 100644 --- a/docs/web/snippets/quickstart.mdx +++ b/docs/web/snippets/quickstart.mdx @@ -2,7 +2,7 @@ export const PyQuickstartAddData = "table.add(\n [\n {\n \"frame_id\": \"4\",\n \"video_id\": \"clip-2\",\n \"caption\": \"a gripper lowering a cup onto the table\",\n \"stats\": {\"motion\": 5, \"sharpness\": 4, \"exposure\": 4, \"framing\": 2},\n \"embedding\": [0.3, 0.9, 0.6, 0.8],\n }\n ]\n)\n"; -export const PyQuickstartAddFeature = "from lancedb import col, udf\n\n@udf\ndef quality_score(\n motion: float, sharpness: float, exposure: float, framing: float\n) -> float:\n return (motion + sharpness + exposure + framing) / 4.0\n\nversion = db.create_function_async(quality_score).wait()\ntable.add_columns(\n {\n \"quality_score\": version(\n motion=col(\"motion\"),\n sharpness=col(\"sharpness\"),\n exposure=col(\"exposure\"),\n framing=col(\"framing\"),\n )\n }\n)\ntable.refresh_column(\"quality_score\")\n"; +export const PyQuickstartAddFeature = "from lancedb import col, function\n\n@function\ndef quality_score(\n motion: float, sharpness: float, exposure: float, framing: float\n) -> float:\n return (motion + sharpness + exposure + framing) / 4.0\n\nversion = db.create_function_async(quality_score).wait()\ntable.add_columns(\n {\n \"quality_score\": version(\n motion=col(\"motion\"),\n sharpness=col(\"sharpness\"),\n exposure=col(\"exposure\"),\n framing=col(\"framing\"),\n )\n }\n)\ntable.refresh_column(\"quality_score\")\n"; export const PyQuickstartAddFeatureEnterprise = "job = table.refresh_column_async(\"quality_score\")\njob.wait()\n"; From bfb55c72e9d3b1ae1cc3966580be900e69556209 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 20 Nov 2026 17:37:12 -0800 Subject: [PATCH 64/78] feat(python)!: make job data access method-only (#5095) Make all Python `Job` and `AsyncJob` data access method-only. Cached property accessors are private and underscore-prefixed; public reads use `id()`, `state()`, `job_type()`, `creation_ms()`, `spec()`, `result()` and `failure()`. `checkout_latest()` refreshes the complete cached registry record in place and returns `None`. ```python job.checkout_latest() print(job.state(), job.result(), job.failure()) print(job.id(), job.job_type(), job.creation_ms(), job.spec()) ``` Cached read methods are synchronous on both handle types. Async handles use `await job.checkout_latest()` for the live refresh; event history remains a separate request through `events()`. Update Python SDK callers, tests and guides to use method calls, including progress/timeout handling and bounded repr. Cover method-only visibility and holistic snapshot freshness through both sync and async clients. BREAKING CHANGE: Python job data access now requires method calls, such as `job.state()` instead of `job.state`. No property compatibility aliases remain. Fixes https://linear.app/lancedb/issue/ENT-3902/sdk-make-cached-versus-live-job-accessors-unambiguous --- docs/web/basics/jobs.mdx | 96 ++++--- docs/web/enterprise/cache-prewarm.mdx | 6 +- docs/web/maintenance/compaction.mdx | 2 +- docs/web/management/function-failures.mdx | 4 +- python/python/lancedb/db.py | 2 +- python/python/lancedb/job.py | 237 +++++++++++++----- python/python/lancedb/table.py | 8 +- python/python/tests/test_db.py | 4 +- python/python/tests/test_e2e_remote_db.py | 14 +- python/python/tests/test_index.py | 4 +- python/python/tests/test_job.py | 141 ++++++++++- .../python/tests/test_materialized_views.py | 28 +-- python/python/tests/test_remote_db.py | 196 +++++++++------ python/python/tests/test_table.py | 4 +- 14 files changed, 544 insertions(+), 202 deletions(-) diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 7761ab07c..f7390b69c 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -26,47 +26,85 @@ the method returns. ```python Python icon="python" job = tbl.create_index_async("vector", replace=True) +job.checkout_latest() -print(job.id) -print(job.job_type) -print(job.status()) +print(job.id()) +print(job.job_type()) +print(job.state()) ``` -## Cached properties and live calls {#snapshots} +## Cached reads and live calls {#snapshots} -Python job properties describe the last observation; reading them does not -contact the server. Submission need not fetch the full registry record, so -some properties can initially be `None`. +Python job handles expose data through methods. The cached read methods return +the last observation without contacting the server. Submission need not fetch +the full registry record, so some read methods can initially return `None`. + +Call `job.checkout_latest()` to update the handle's cached lifecycle state and +complete registry record together. This updates the values returned by +`state()`, `job_type()`, `creation_ms()`, `spec()`, `result()`, and `failure()` +from one server observation. +It updates the existing handle in place, returns `None`, and does not wait for +the job to finish or restart it. For SQL-backed or in-process jobs, it updates +the lifecycle state without registry details. | Surface | Contract | | --- | --- | -| `state` | Last observed lifecycle state. It does not update on its own. | -| `job_type`, `creation_ms` | Cached job kind and creation time in epoch milliseconds. | -| `spec` | Complete, job-specific submitted specification. Read this separately from the bounded `repr(job)` display. | -| `result` | Cached, job-specific reported data; it is not necessarily the typed object returned by `wait()`. | -| `failure` | Cached `JobFailureInfo`, when the server reports a terminal failure. | +| `id()` | Opaque operation ID, when available. | +| `state()` | Last observed lifecycle state. It does not update on its own. | +| `job_type()`, `creation_ms()` | Cached job kind and creation time in epoch milliseconds. | +| `spec()` | Complete, job-specific submitted specification. Read this separately from the bounded `repr(job)` display. | +| `result()` | Cached, job-specific reported data; it is not necessarily the typed object returned by `wait()`. | +| `failure()` | Cached `JobFailureInfo`, when the server reports a terminal failure. | +| `checkout_latest()` | Fetch and cache the latest lifecycle state and complete registry record together. Failed and cancelled states are cached without raising a job-failure exception; request errors can still raise. | | `status()` | Live lifecycle request. For registry jobs it also caches the full record. A failed state is returned without raising a job-failure exception; request errors can still raise. | -| `refresh()` | Fetch and cache the current record without waiting for completion. | -| `events(...)` | Separate live request returning a `pyarrow.Table` of recorded events; it does not refresh the properties. | +| `refresh()` | Existing method with the same cache-update behavior as `checkout_latest()`. | +| `events(...)` | Separate live request returning a `pyarrow.Table` of recorded events; it does not refresh the cached record. | | `wait(...)` | Poll until completion and return the operation's typed result, or raise on failure/cancellation. Refresh afterward when you need the complete final registry record. | +`status()`, `refresh()`, and `events(...)` remain available. Read `job.state()` +after `checkout_latest()` to poll using the same snapshot as `result()` and +`failure()`. Event history is a separate live request through `events(...)` +and does not refresh the cached record. + + +These examples require a Python SDK release with `checkout_latest()` and the +method-based read accessors. Cached reads such as `job.state()` and +`job.result()` are synchronous on both `Job` and `AsyncJob`. Async handles use +`await job.checkout_latest()` or `await job.refresh()` for the live update. + + For example, poll a registry handle and then retrieve its final details: -```python + +```python Synchronous icon="python" import time -state = job.status() -while state == "running": - print(job.state) +job.checkout_latest() +while job.state() == "running": + print(job.state(), job.failure()) time.sleep(2) - state = job.status() + job.checkout_latest() result = job.wait() -job.refresh() +job.checkout_latest() print(result) -print(job.spec) +print(job.spec()) ``` +```python Asynchronous icon="python" +import asyncio + +await job.checkout_latest() +while job.state() == "running": + print(job.state(), job.failure()) + await asyncio.sleep(2) + await job.checkout_latest() + +result = await job.wait() +await job.checkout_latest() +print(result, job.spec()) +``` + The four lifecycle strings below are the usual SDK contract; newer server states may pass through an older client. Do not infer execution progress from @@ -110,12 +148,12 @@ from datetime import timedelta from lancedb.exceptions import JobFailedError, JobCancelledError job = tbl.create_index_async("vector", replace=True) -job_id = job.id # Save the ID to reopen an Enterprise registry job later. +job_id = job.id() # Save the ID to reopen an Enterprise registry job later. try: result = job.wait(timeout=timedelta(minutes=10)) except JobFailedError: - print(f"job failed: {job.failure}") + print(f"job failed: {job.failure()}") except JobCancelledError: print("job was cancelled") except ConnectionError as exc: @@ -179,8 +217,8 @@ work. Treat the ID as an opaque identifier and pass it unchanged to the jobs API ```python Python icon="python" job = db.open_job(job_id) # raises JobNotFoundError if unknown -job.refresh() # pull the latest status from the server -print(job.status()) +job.checkout_latest() +print(job.state(), job.result(), job.failure()) events = job.events(limit=100) print(events.to_pylist()) @@ -263,8 +301,8 @@ For a Function refresh, `wait()` returns a `RefreshColumnResult` such as `rows_assigned`, `rows_failed`, `rows_remaining`, `source_version` and optional `published_version`. Other job types have different results. Do not parse the printed representation to recover a spec, result or progress measurement. -For object-shaped registry data, `job.spec` and `job.result` are decoded Python -dictionaries: access fields with keys, such as `job.result.get("summary")` +For object-shaped registry data, `job.spec()` and `job.result()` are decoded Python +dictionaries: access fields with keys, such as `job.result().get("summary")` after refreshing a successful Function job. The separate typed object from `wait()` uses attributes, such as `result.rows_assigned`. @@ -414,8 +452,8 @@ SQL query engine rather than the job registry: | Secrets | Create, alter, list, describe, drop | Credential values are bound as SQL parameters, never embedded in SQL text or returned in results. `DESCRIBE SECRET` additionally exposes rotation history. | | Views | Create, describe, list, drop | Create returns the stored definition and schema. Drop confirms catalog removal while cleanup continues separately. | -All of these report `job.job_type` as `"query"`, with `job.id` holding the -connection-scoped SQL query UUID -- use `describe_query(job.id)` to inspect +All of these report `job.job_type()` as `"query"`, with `job.id()` holding the +connection-scoped SQL query UUID -- use `describe_query(job.id())` to inspect one. Unlike registry handles, they don't expose event history, can't be reopened through `open_job()` or reattached after a client restart, and cancellation depends on the SQL server's support for it. diff --git a/docs/web/enterprise/cache-prewarm.mdx b/docs/web/enterprise/cache-prewarm.mdx index 007cff0ab..710fc0e2f 100644 --- a/docs/web/enterprise/cache-prewarm.mdx +++ b/docs/web/enterprise/cache-prewarm.mdx @@ -94,12 +94,12 @@ job = table.prewarm_data_async( ["video"], filter="quality > $minimum", parameters={"minimum": 0.7}, concurrency=4 ) -print(job.id) +print(job.id()) result = job.wait(timeout=timedelta(minutes=10), progress=print) print(result.table_version, result.executors_completed, result.fragments_selected) # Reattach in a later process using the same database connection settings. -db.open_job(job.id).wait() +db.open_job(job.id()).wait() ``` @@ -156,7 +156,7 @@ if let Some(id) = job.id() { The method returns when the job is accepted. Waiting finishes when warming reaches a terminal state; a timeout does not cancel the job. Use -`job.refresh()` and `job.spec["table_version"]` to inspect the captured source +`job.checkout_latest()` and `job.spec()["table_version"]` to inspect the captured source version. In Python's asynchronous API, await submission and `job.wait()`. The TypeScript SDK exposes `table.prewarmDataAsync({ columns, filter, parameters, concurrency })` with the diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index ad3fe636d..80a9f7c5f 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -84,7 +84,7 @@ result = job.wait(timeout=timedelta(minutes=10)) print(result.rows_succeeded, result.fragments_removed, result.fragments_added) # Resume from another process with the same connection settings. -result = db.open_job(job.id).wait() +result = db.open_job(job.id()).wait() ``` ```typescript TypeScript import type { CompactionResult } from "@lancedb/lancedb"; diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx index 76fbc0371..b7f554402 100644 --- a/docs/web/management/function-failures.mdx +++ b/docs/web/management/function-failures.mdx @@ -161,7 +161,7 @@ print(result.rows_assigned, result.rows_failed, result.rows_remaining) Choose limits for your workload; these example limits stop work when more than 100 rows or more than 10% fail. `skip` does not make initialization, infrastructure or publication failures successful. If `wait()` raises, -[refresh the job record](/basics/jobs#snapshots), inspect `job.failure`, and +[refresh the job record](/basics/jobs#snapshots), inspect `job.failure()`, and inspect any recorded row errors. A failed/cancelled job can have committed some output, but retention of every successful call is not guaranteed. External effects are not rolled back and can be repeated during recovery. @@ -173,7 +173,7 @@ Scope diagnostics to the job you are investigating: ```python from collections import Counter -errors = table.function_errors(job_id=job.id, column="embedding", limit=10000) +errors = table.function_errors(job_id=job.id(), column="embedding", limit=10000) groups = Counter((r.error_type, r.error_message) for r in errors.records) for cause, count in groups.most_common(): print(count, cause) diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 68100b852..6de3e050c 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1581,7 +1581,7 @@ class DBConnection(EnforceOverrides): [RefreshColumnResult][lancedb.functions.RefreshColumnResult], including when the refresh was started through SQL. Other job types return ``None`` from ``wait()``; their persisted result is available through - ``job.result`` after ``job.refresh()``. + ``job.result()`` after ``job.checkout_latest()``. Raises `JobNotFoundError` when the server has no such job, the way `open_table` does for a missing table. diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 81ffea602..b3a6e527f 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -215,6 +215,11 @@ class AsyncJob(Generic[T]): The operation may already be complete when the handle is created. ``T`` is the endpoint's terminal result type; unit-result jobs resolve to ``None``. + + Methods such as ``state()``, ``result()``, ``failure()`` and ``spec()`` read + cached values without contacting the backend, including on async handles. Use + ``await job.checkout_latest()`` to refresh the cached state and registry + details together. ``events()`` makes a separate request for event history. """ def __init__( @@ -232,15 +237,18 @@ class AsyncJob(Generic[T]): self._last_progress_snapshot = enriched return enriched - @property def id(self) -> Optional[str]: - """The operation's opaque ID, interpreted according to :attr:`job_type`. + """Return the operation's opaque ID, interpreted according to ``job_type()``. Registry jobs expose a registry job ID; SQL-backed jobs expose a connection-scoped query ID as a string. Local operations return ``None``. Query IDs cannot be used with registry job APIs or to resume after a client restart. """ + return self._id + + @property + def _id(self) -> Optional[str]: return self._inner.id if self._inner is not None else None async def status(self) -> str: @@ -272,9 +280,9 @@ class AsyncJob(Generic[T]): state = await self._inner.status() description = getattr(self._inner, "_description", None) if description is None or description.progress is None: - if self.job_type == "query": + if self.job_type() == "query": return { - "job_id": self.id, + "job_id": self.id(), "job_type": "query", "state": state, "client_elapsed_time_millis": int( @@ -332,7 +340,9 @@ class AsyncJob(Generic[T]): if self._inner is None: return cast(T, None) query_progress = ( - progress is not False and progress is not None and self.job_type == "query" + progress is not False + and progress is not None + and self.job_type() == "query" ) progress_obj, owns = _normalize_job_progress(progress, query=query_progress) progress_callback = _job_progress_callback(progress_obj, self._enrich_progress) @@ -406,15 +416,15 @@ class AsyncJob(Generic[T]): if timeout is None: raise raise TimeoutError( - _timeout_message(self.id, timeout, self.job_type) + _timeout_message(self.id(), timeout, self.job_type()) ) from error identity = ( - f"job {self.id!r}" if self.id is not None else "the operation" + f"job {self.id()!r}" if self.id() is not None else "the operation" ) - if self.id is not None and self.job_type != "query": + if self.id() is not None and self.job_type() != "query": reconnect = ( - f"Use db.open_job({self.id!r}) to reconnect, then call wait() " - "on the returned job." + f"Use db.open_job({self.id()!r}) to reconnect, " + "then call wait() on the returned job." ) else: reconnect = "Call wait() on this job handle to reconnect." @@ -438,7 +448,7 @@ class AsyncJob(Generic[T]): 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 properties below. + job its full record, then cache it for the read methods below. Registry details are `None` until this runs, because submitting an operation does not fetch its full registry record. Query-backed jobs @@ -450,49 +460,96 @@ class AsyncJob(Generic[T]): return await self._inner.refresh() - @property - def state(self) -> Optional[str]: - """The last observed lifecycle state, without contacting the backend. + async def checkout_latest(self) -> None: + """Refresh this handle's cached state and complete job record together. - `None` until the handle has talked to it. See :meth:`AsyncJob.refresh`. + For a registry job, each call fetches one current record and updates + the values returned by ``state()``, ``job_type()``, ``creation_ms()``, + ``spec()``, ``result()`` and ``failure()`` from that observation. Calling + those read methods afterward does not contact the backend. Query-backed + and in-process jobs update their lifecycle state without registry details. + + Updates this handle in place and returns ``None``. It does not wait for + completion or restart the operation. Failed or cancelled states are + cached without raising a job-failure exception; request errors propagate + and leave the cached record unchanged. Event history remains a separate + live request through [events()][lancedb.job.AsyncJob.events]. + + [refresh()][lancedb.job.AsyncJob.refresh] remains available with the + same behavior. + + Examples + -------- + >>> await job.checkout_latest() # doctest: +SKIP + >>> print(job.state(), job.result(), job.failure()) # doctest: +SKIP """ - if self._inner is None: - return "finished" - return self._inner._state + await self.refresh() + + def state(self) -> Optional[str]: + """Return the last observed lifecycle state without contacting the backend. + + `None` until the handle has talked to it. Call + [checkout_latest()][lancedb.job.AsyncJob.checkout_latest] to refresh + the state and registry details together. + """ + return self._state @property + def _state(self) -> Optional[str]: + return self._inner._state if self._inner is not None else "finished" + def job_type(self) -> Optional[str]: - """The job's kind of work, without contacting the backend. + """Return the job's kind of work without contacting the backend. SQL-backed handles report ``"query"`` immediately. Registry handles report the server's job type after :meth:`refresh` or :meth:`status`. In-process handles return ``None``. """ + return self._job_type + + @property + def _job_type(self) -> Optional[str]: return self._inner.job_type if self._inner is not None else None - @property def creation_ms(self) -> Optional[int]: - """When the job was created, in milliseconds since the epoch.""" + """Return the cached creation time in epoch milliseconds; no backend call.""" + return self._creation_ms + + @property + def _creation_ms(self) -> Optional[int]: return self._field("creation_ms") - @property def spec(self) -> Optional[Any]: - """The job-type-specific specification it was submitted with.""" + """Return the complete cached job specification without a backend call.""" + return self._spec + + @property + def _spec(self) -> Optional[Any]: return self._field("spec") - @property def result(self) -> Optional[Any]: - """The job-type-specific terminal result, as reported data rather than - the typed model :meth:`AsyncJob.wait` returns. + """Return the cached job-specific terminal result without a backend call. - `None` until the job succeeds, so a job that never terminates reports - its progress through :meth:`AsyncJob.events` instead. + This is reported data rather than the typed model + [wait()][lancedb.job.AsyncJob.wait] returns. It can remain `None` until + a successful registry record is fetched with + [checkout_latest()][lancedb.job.AsyncJob.checkout_latest] or another + live status request. For ongoing progress, use + [progress()][lancedb.job.AsyncJob.progress] or + [events()][lancedb.job.AsyncJob.events]. """ + return self._result + + @property + def _result(self) -> Optional[Any]: return self._field("result") - @property def failure(self) -> Optional[JobFailureInfo]: - """Why the job failed, when it failed and the server reports a reason.""" + """Return cached failure details, when reported, without a backend call.""" + return self._failure + + @property + def _failure(self) -> Optional[JobFailureInfo]: return self._field("failure") @property @@ -590,7 +647,11 @@ class AsyncJob(Generic[T]): ) -> "pa.Table": """This job's recorded lifecycle events. - Where the properties above report a terminal result only once the job + Each call requests event history without updating the cached record. + Use [checkout_latest()][lancedb.job.AsyncJob.checkout_latest] to refresh + the job's state and registry details together. + + Where the read methods above report a terminal result only once the job reaches one, events are written as the job runs and outlive the workers that produced them. A distributed job records a `claim`/`claim_complete` pair per unit of work, each carrying `rows_processed`, so a job that @@ -642,45 +703,53 @@ def _repr_payload(value: Any) -> str: def _job_repr(kind: str, job: Any) -> str: """Show cached job identity and bounded previews without backend calls. - The complete payloads remain available through ``spec`` and ``result``. + The complete payloads remain available through ``spec()`` and ``result()``. """ - state = job.state + state = job.state() if state is None: # Nothing has been fetched yet, so there is nothing to lay out. - known = f"id={_repr_payload(job.id)}, " if job.id is not None else "" + known = f"id={_repr_payload(job.id())}, " if job.id() is not None else "" return f"{kind}({known}not refreshed)" fields = [] - if job.id is not None: - fields.append(f"id={_repr_payload(job.id)}") + if job.id() is not None: + fields.append(f"id={_repr_payload(job.id())}") fields.append(f"state={_repr_payload(state)}") for name in ("job_type", "creation_ms"): - value = getattr(job, name) + value = getattr(job, name)() if value is not None: fields.append(f"{name}={_repr_payload(value)}") for name in ("spec", "result"): - value = getattr(job, name) + value = getattr(job, name)() if value is not None: fields.append(f"{name}={_repr_payload(value)}") - if job.failure is not None: - fields.append(f"failure={_repr_payload(job.failure)}") + if job.failure() is not None: + fields.append(f"failure={_repr_payload(job.failure())}") body = "".join(f"\n{_REPR_INDENT}{field}," for field in fields) return f"{kind}({body}\n)" class Job(Generic[T]): - """Synchronous counterpart of `AsyncJob` with the same result type.""" + """Synchronous counterpart of `AsyncJob` with the same result type. + + Call ``state()``, ``result()``, ``failure()`` and ``spec()`` to read the + cached record after ``job.checkout_latest()`` refreshes it holistically. + ``events()`` makes a separate live request for event history. + """ def __init__(self, inner: Optional[AsyncJob[T]]): self._inner = inner - @property def id(self) -> Optional[str]: - """Identifies the operation on the server that is running it. + """Return the operation's opaque server ID without a backend call. - See :attr:`AsyncJob.id`. + See [AsyncJob.id()][lancedb.job.AsyncJob.id]. """ - return self._inner.id if self._inner is not None else None + return self._id + + @property + def _id(self) -> Optional[str]: + return self._inner._id if self._inner is not None else None def status(self) -> str: """The operation's current lifecycle state: "running", "finished", @@ -740,35 +809,87 @@ class Job(Generic[T]): return LOOP.run(self._inner.refresh()) - @property + def checkout_latest(self) -> None: + """Refresh this handle's cached state and complete job record together. + + Updates this handle in place and returns ``None`` without waiting for + completion. See + [AsyncJob.checkout_latest()][lancedb.job.AsyncJob.checkout_latest] + for refreshed fields and availability. ``refresh()`` remains available + with the same behavior. + + Examples + -------- + >>> job.checkout_latest() # doctest: +SKIP + >>> print(job.state(), job.result(), job.failure()) # doctest: +SKIP + """ + self.refresh() + def state(self) -> Optional[str]: - """The last observed lifecycle state. See :attr:`AsyncJob.state`.""" - return self._inner.state if self._inner is not None else "finished" + """Return the cached lifecycle state without a backend call. + + See [AsyncJob.state()][lancedb.job.AsyncJob.state]. + """ + return self._state @property + def _state(self) -> Optional[str]: + return self._inner._state if self._inner is not None else "finished" + def job_type(self) -> Optional[str]: - """The job's type. See :attr:`AsyncJob.job_type`.""" - return self._inner.job_type if self._inner is not None else None + """Return the cached job type without a backend call. + + See [AsyncJob.job_type()][lancedb.job.AsyncJob.job_type]. + """ + return self._job_type @property + def _job_type(self) -> Optional[str]: + return self._inner._job_type if self._inner is not None else None + def creation_ms(self) -> Optional[int]: - """When the job was created. See :attr:`AsyncJob.creation_ms`.""" - return self._field("creation_ms") + """Return the cached creation time in epoch milliseconds. + + See [AsyncJob.creation_ms()][lancedb.job.AsyncJob.creation_ms]. + """ + return self._creation_ms @property + def _creation_ms(self) -> Optional[int]: + return self._field("_creation_ms") + def spec(self) -> Optional[Any]: - """The job's specification. See :attr:`AsyncJob.spec`.""" - return self._field("spec") + """Return the complete cached specification without a backend call. + + See [AsyncJob.spec()][lancedb.job.AsyncJob.spec]. + """ + return self._spec @property + def _spec(self) -> Optional[Any]: + return self._field("_spec") + def result(self) -> Optional[Any]: - """The job's terminal result. See :attr:`AsyncJob.result`.""" - return self._field("result") + """Return the cached terminal result without a backend call. + + See [AsyncJob.result()][lancedb.job.AsyncJob.result]. + """ + return self._result @property + def _result(self) -> Optional[Any]: + return self._field("_result") + def failure(self) -> Optional[JobFailureInfo]: - """Why the job failed. See :attr:`AsyncJob.failure`.""" - return self._field("failure") + """Return cached failure details without a backend call. + + See [AsyncJob.failure()][lancedb.job.AsyncJob.failure]. + """ + return self._failure + + @property + def _failure(self) -> Optional[JobFailureInfo]: + return self._field("_failure") @property def _spec_json(self) -> Optional[str]: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 52212a3de..73e8d58a7 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2165,9 +2165,9 @@ class Table(ABC): Returns once accepted. ``job.wait()`` waits for warming to finish and returns [PrewarmDataResult][lancedb.prewarm.PrewarmDataResult]. - Save ``job.id`` to resume with ``db.open_job(id)``. A wait timeout does - not cancel the operation. After ``job.refresh()``, - ``job.spec["table_version"]`` identifies the pinned source version. + Save ``job.id()`` to resume with ``db.open_job(id)``. A wait timeout does + not cancel the operation. After ``job.checkout_latest()``, + ``job.spec()["table_version"]`` identifies the pinned source version. Examples -------- @@ -3301,7 +3301,7 @@ class Table(ABC): runs report uncommitted rows and ``more_work``; unknown file statistics are None. Servers without a result payload raise an error rather than returning fabricated zero statistics. Wait timeouts do not cancel work. - Save ``job.id`` and reopen with ``db.open_job(id)``. Monitoring and + Save ``job.id()`` and reopen with ``db.open_job(id)``. Monitoring and cancellation use generic HTTP job APIs and their existing permissions. >>> job = table.compact_async( # doctest: +SKIP diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 764d082eb..5656f5203 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -985,7 +985,7 @@ def test_drop_table_async(tmp_db: lancedb.DBConnection): assert tmp_db.table_names() == ["test"] job = tmp_db.drop_table_async("test") - assert job.id is None + assert job.id() is None assert job.status() == "finished" assert job.wait() is None assert tmp_db.table_names() == [] @@ -1001,7 +1001,7 @@ async def test_drop_table_async_connection(tmp_db_async: lancedb.AsyncConnection await tmp_db_async.create_table("test", data=pa.table({"id": [1, 2]})) job = await tmp_db_async.drop_table_async("test") - assert job.id is None + assert job.id() is None assert await job.status() == "finished" assert await job.wait() is None assert await tmp_db_async.table_names() == [] diff --git a/python/python/tests/test_e2e_remote_db.py b/python/python/tests/test_e2e_remote_db.py index 9ef746ce1..2bceb750f 100644 --- a/python/python/tests/test_e2e_remote_db.py +++ b/python/python/tests/test_e2e_remote_db.py @@ -106,7 +106,7 @@ async def test_maintenance_job_result_and_reopen_against_server( filter="id >= 8", concurrency=2, ) - assert job.id + assert job.id() progress = [] result = await call(job.wait, timeout=timeout, progress=progress.append) assert any(snapshot["state"] == "finished" for snapshot in progress) @@ -114,22 +114,22 @@ async def test_maintenance_job_result_and_reopen_against_server( assert await call(job.status) == "finished" if operation == "compact": assert isinstance(result, CompactionResult) - assert job.job_type == "compact" + assert job.job_type() == "compact" assert not result.partial_commit and result.rows_failed == 0 assert result.completion_percentage == 100 assert 0 <= result.rows_succeeded <= len(expected) assert result.files_added is not None and result.files_removed is not None else: assert isinstance(result, PrewarmDataResult) - assert job.job_type == "prewarm_page_cache" - assert result.table_version == version == job.spec["table_version"] - assert job.spec["columns"] == ["payload"] - assert job.spec["concurrency"] == 2 + assert job.job_type() == "prewarm_page_cache" + assert result.table_version == version == job.spec()["table_version"] + assert job.spec()["columns"] == ["payload"] + assert job.spec()["concurrency"] == 2 assert result.fragments_selected > 0 assert result.executors_completed == result.executors_targeted assert result.executors_partial == 0 assert result.bytes_read is None and result.ranges_completed is None - reopened = await call(connection.open_job, job.id) + reopened = await call(connection.open_job, job.id()) assert await call(reopened.wait, timeout=timeout) == result query = table.query() if asynchronous else table.search() actual = await call( diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index d222b3f94..fe90732be 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -92,7 +92,7 @@ async def binary_table(db_async): @pytest.mark.asyncio async def test_create_index_async_returns_done_job(some_table: AsyncTable): job = await some_table.create_index_async("id", config=BTree()) - assert job.id is None + assert job.id() is None assert await job.wait() is None assert len(await some_table.list_indices()) == 1 await job.cancel() @@ -1045,7 +1045,7 @@ async def test_named_index_exist_ok_checks_before_column_validation( method = some_table.create_index_async if background else some_table.create_index result = await method("missing", config=BTree(), name="kept", exist_ok=True) if background: - assert result.id is None + assert result.id() is None await result.wait() assert await some_table.version() == version assert [index.name for index in await some_table.list_indices()] == ["kept"] diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index 809105102..6113277a7 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -16,6 +16,141 @@ from lancedb.job import AsyncJob, Job, _progress_eta from lancedb.remote.errors import HttpError, RetryError +@pytest.mark.parametrize("job_class", [AsyncJob, Job]) +def test_job_handle_data_access_uses_methods(job_class): + assert all( + name.startswith("_") + for name, member in vars(job_class).items() + if isinstance(member, property) + ) + job = job_class(None) + expected = { + "id": None, + "state": "finished", + "job_type": None, + "creation_ms": None, + "spec": None, + "result": None, + "failure": None, + } + for name, value in expected.items(): + assert callable(getattr(job, name)) + assert getattr(job, name)() == value + assert getattr(job, f"_{name}") == value + + +@pytest.fixture(params=[False, True], ids=["async", "sync"]) +def job_snapshot(request): + def create(inner): + job = AsyncJob(inner) + if request.param: + job = Job(job) + + async def call(method="checkout_latest"): + if request.param: + return await asyncio.to_thread(getattr(job, method)) + return await getattr(job, method)() + + return job, call + + return create + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["checkout_latest", "refresh"]) +@pytest.mark.parametrize("state", ["finished", "failed", "cancelled", "future_state"]) +async def test_job_checkout_latest_refreshes_the_complete_snapshot( + job_snapshot, method, state +): + spec = {"column": "vector", "initialization": list(range(1000))} + result = {"rows_assigned": 1000} if state == "finished" else None + failure = SimpleNamespace(message="worker failed") if state == "failed" else None + description = SimpleNamespace( + creation_ms=2000, spec=spec, result=result, failure=failure + ) + inner = SimpleNamespace( + _state=None, _description=None, job_type=None, status=AsyncMock() + ) + + async def observe(): + inner._state = state + inner.job_type = "refresh_column" + inner._description = description + + inner.refresh = AsyncMock(side_effect=observe) + job, call = job_snapshot(inner) + assert job.state() is None + assert job.job_type() is None + assert job.creation_ms() is None + assert job.spec() is None + assert job.result() is None + assert job.failure() is None + inner.refresh.assert_not_called() + + assert await call(method) is None + assert job.state() == state + assert job.job_type() == "refresh_column" + assert job.creation_ms() == 2000 + assert job.spec() is spec + assert job.result() is result + assert job.failure() is failure + inner.refresh.assert_awaited_once_with() + inner.status.assert_not_called() + + +@pytest.mark.asyncio +async def test_job_checkout_latest_keeps_cached_details_on_request_error(job_snapshot): + error = HttpError("not found", "req-job", 404) + description = SimpleNamespace( + creation_ms=2000, spec={"column": "vector"}, result=None, failure=None + ) + inner = SimpleNamespace( + _state="running", + _description=description, + job_type="refresh_column", + refresh=AsyncMock(side_effect=error), + ) + job, call = job_snapshot(inner) + + with pytest.raises(HttpError) as exc: + await call() + assert exc.value is error + assert job.state() == "running" + assert job.spec() is description.spec + assert job.result() is None + assert job.failure() is None + inner.refresh.assert_awaited_once_with() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_job_checkout_latest_preserves_refresh_overrides(sync, monkeypatch): + job = AsyncJob(None) + if sync: + job = Job(job) + refresh = MagicMock() if sync else AsyncMock() + monkeypatch.setattr(job, "refresh", refresh) + + if sync: + assert await asyncio.to_thread(job.checkout_latest) is None + else: + assert await job.checkout_latest() is None + refresh.assert_awaited_once_with() + refresh.assert_called_once_with() + + +@pytest.mark.asyncio +async def test_job_checkout_latest_for_completed_local_jobs(job_snapshot): + job, call = job_snapshot(None) + assert await call() is None + assert job.state() == "finished" + assert job.job_type() is None + assert job.spec() is None + assert job.result() is None + assert job.failure() is None + assert Job(None).checkout_latest() is None + + @pytest.mark.parametrize("sync", [False, True]) def test_job_repr_bounds_large_payloads_without_fetching(sync): spec = {"initialization": list(range(100000)), "source": "x" * 100000} @@ -44,9 +179,9 @@ def test_job_repr_bounds_large_payloads_without_fetching(sync): assert "worker failed" in rendered assert "..." in rendered assert len(repr(job.status)) < 1700 - assert job.spec is spec - assert job.result is result - assert len(job.spec["initialization"]) == 100000 + assert job.spec() is spec + assert job.result() is result + assert len(job.spec()["initialization"]) == 100000 @pytest.mark.parametrize("sync", [False, True]) diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 13950a39c..a006c6529 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -269,21 +269,21 @@ def test_create_and_refresh_jobs(tmp_path): create_job = db.create_materialized_view_async( "adults", "people", where="age >= 18", with_no_data=True ) - assert create_job.id is None - assert create_job.job_type is None + assert create_job.id() is None + assert create_job.job_type() is None assert create_job.wait() is None view = db.open_materialized_view("adults") refresh_job = view.refresh_async() - assert refresh_job.id is None - assert refresh_job.job_type is None + assert refresh_job.id() is None + assert refresh_job.job_type() is None result = refresh_job.wait() assert result.mode == "rebuild" assert result.rows_written == 2 assert view.table.count_rows() == 2 drop_job = db.drop_materialized_view_async("adults") - assert drop_job.id is None + assert drop_job.id() is None assert drop_job.wait() is None assert "adults" not in list(db.list_materialized_views()) @@ -442,20 +442,20 @@ async def test_async_create_and_refresh_jobs(tmp_path): create_job = await db.create_materialized_view_async( "adults", "people", with_no_data=True ) - assert create_job.id is None - assert create_job.job_type is None + assert create_job.id() is None + assert create_job.job_type() is None assert await create_job.wait() is None view = await db.open_materialized_view("adults") refresh_job = await view.refresh_async() - assert refresh_job.id is None - assert refresh_job.job_type is None + assert refresh_job.id() is None + assert refresh_job.job_type() is None result = await refresh_job.wait() assert result.mode == "rebuild" assert result.rows_written == 1 drop_job = await db.drop_materialized_view_async("adults") - assert drop_job.id is None + assert drop_job.id() is None assert await drop_job.wait() is None assert "adults" not in [item async for item in db.list_materialized_views()] @@ -716,8 +716,8 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options db = RemoteDBConnection.__new__(RemoteDBConnection) db._conn = AsyncConnection(native) job = db.create_materialized_view_async("adults", "people", **options) - assert job.id == QueryBackedCreateJob.id - assert job.job_type == "query" + assert job.id() == QueryBackedCreateJob.id + assert job.job_type() == "query" assert not hasattr(job, "query_id") assert job.wait() is None assert job.status() == "finished" @@ -747,8 +747,8 @@ async def test_async_remote_create_keeps_interval_unspecified(): job = await db.create_materialized_view_async( "adults", "people", auto_refresh_enabled=True ) - assert job.id == QueryBackedCreateJob.id - assert job.job_type == "query" + assert job.id() == QueryBackedCreateJob.id + assert job.job_type() == "query" assert not hasattr(job, "query_id") assert await job.wait() is None assert await job.status() == "finished" diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index fed3ae1bf..8bb3a1ce0 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1,5 +1,6 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors +import asyncio from concurrent.futures import ThreadPoolExecutor import contextlib import copy @@ -2331,7 +2332,7 @@ def test_remote_create_index_async_returns_job(): with mock_lancedb_connection(handler) as db: table = db.create_table("test", [{"id": 1}]) job = table.create_index_async("id", config=BTree()) - assert job.id == "job-1" + assert job.id() == "job-1" observed = [] assert job.wait(timeout=timedelta(seconds=30), progress=observed.append) is None assert len(describe_calls) == 2 @@ -2499,13 +2500,13 @@ async def test_remote_refresh_async_returns_typed_terminal_result( async with mock_lancedb_connection_async(handler) as db: table = await db.create_table("test", [{"id": 1}]) job = await table.refresh_column_async("derived", **refresh_kwargs) - assert job.id == "refresh-1" + assert job.id() == "refresh-1" result = await job.wait(timeout=timedelta(seconds=30)) else: with mock_lancedb_connection(handler) as db: table = db.create_table("test", [{"id": 1}]) job = table.refresh_column_async("derived", **refresh_kwargs) - assert job.id == "refresh-1" + assert job.id() == "refresh-1" result = job.wait(timeout=timedelta(seconds=30)) assert isinstance(result, lancedb.RefreshColumnResult) @@ -3032,12 +3033,12 @@ async def test_remote_job_wait_recovers_from_disconnection(sync, failure): with mock_lancedb_connection(handler, **config) as db: job = db.open_job("job-1") assert job.wait(timeout=timedelta(seconds=5)) is None - assert job.state == "finished" + assert job.state() == "finished" else: async with mock_lancedb_connection_async(handler, **config) as db: job = await db.open_job("job-1") assert await job.wait(timeout=timedelta(seconds=5)) is None - assert job.state == "finished" + assert job.state() == "finished" assert polls == 5 @@ -3171,23 +3172,23 @@ async def test_reopened_refresh_job_wait_returns_typed_result( if sync: with mock_lancedb_connection(handler) as db: job = db.open_job("refresh-1") - assert job.id == "refresh-1" - assert job.spec == {"column": "derived"} + assert job.id() == "refresh-1" + assert job.spec() == {"column": "derived"} result = job.wait(timeout=timedelta(seconds=5), progress=observed.append) assert job.wait() == result job.refresh() - assert job.result == terminal_result + assert job.result() == terminal_result else: async with mock_lancedb_connection_async(handler) as db: job = await db.open_job("refresh-1") - assert job.id == "refresh-1" - assert job.spec == {"column": "derived"} + assert job.id() == "refresh-1" + assert job.spec() == {"column": "derived"} result = await job.wait( timeout=timedelta(seconds=5), progress=observed.append ) assert await job.wait() == result await job.refresh() - assert job.result == terminal_result + assert job.result() == terminal_result assert isinstance(result, lancedb.RefreshColumnResult) assert result == lancedb.RefreshColumnResult.model_validate(terminal_result) @@ -3256,12 +3257,12 @@ async def test_reopened_unit_job_ignores_additive_result_payload(sync): with mock_lancedb_connection(handler) as db: job = db.open_job("index-1") assert job.wait() is None - assert job.result == terminal_result + assert job.result() == terminal_result else: async with mock_lancedb_connection_async(handler) as db: job = await db.open_job("index-1") assert await job.wait() is None - assert job.result == terminal_result + assert job.result() == terminal_result @pytest.mark.parametrize("payload", [b"{", b"{}"]) @@ -3399,9 +3400,9 @@ async def test_remote_job_wait_preserves_terminal_build(sync, with_terminal_serv expected += " (in function_refresh_attempt_failed)" assert str(caught.value) == expected assert caught.value.job_id == "job-provenance" - assert job.failure.message == message - assert job.failure.traceback == "Traceback: original user code" - assert job.result == result + assert job.failure().message == message + assert job.failure().traceback == "Traceback: original user code" + assert job.result() == result @pytest.mark.parametrize("server_version", ["0.2.0", "0.6.0"]) @@ -7109,14 +7110,14 @@ def test_remote_connection_jobs_surface(): with pytest.raises(JobNotFoundError, match="missing"): db.open_job("missing") finished = db.open_job("job-2") - assert finished.state == "finished" - assert finished.result == {"rows_assigned": 1000000, "rows_failed": 0} + assert finished.state() == "finished" + assert finished.result() == {"rows_assigned": 1000000, "rows_failed": 0} job = db.open_job("job-1") - assert job.id == "job-1" + assert job.id() == "job-1" # Opening already populated the handle. - assert job.state == "failed" - assert job.spec == {"column": "vec"} + assert job.state() == "failed" + assert job.spec() == {"column": "vec"} progress = job.progress() assert progress["state"] == "failed" assert progress["rows_computed"] == 4 @@ -7125,12 +7126,12 @@ def test_remote_connection_jobs_surface(): assert progress["queue_reason"] == "waiting for capacity" assert progress["waiting_for_job_id"] == "job-maintenance" assert progress["paused_at_millis"] == 1200 - assert job.failure.message == "worker died" - assert job.failure.traceback == ( + assert job.failure().message == "worker died" + assert job.failure().traceback == ( "Traceback (most recent call last):\nRuntimeError: worker died" ) - assert job.failure.sql_job_id == "sql-job-1" - assert repr(job.failure) == ( + assert job.failure().sql_job_id == "sql-job-1" + assert repr(job.failure()) == ( 'JobFailureInfo(phase="execute", message="worker died", retryable=True, ' 'sql_job_id="sql-job-1")' ) @@ -7145,7 +7146,13 @@ def test_remote_connection_jobs_surface(): assert finished.progress()["paused"] is False -def test_remote_job_handle_reports_its_own_detail(): +@pytest.mark.asyncio +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("refresh_method", ["checkout_latest", "refresh"]) +@pytest.mark.parametrize("terminal_state", ["DONE", "FAILED"]) +async def test_remote_job_handle_reports_its_own_detail( + is_async, refresh_method, terminal_state +): schema = pa.schema([("state", pa.string())]) batch = pa.record_batch([pa.array(["claim_complete"])], schema=schema) sink = pa.BufferOutputStream() @@ -7153,27 +7160,25 @@ def test_remote_job_handle_reports_its_own_detail(): writer.write_batch(batch) events_body = sink.getvalue().to_pybytes() event_payloads = [] + descriptions = [] + description = dict( + job_id="job-1", + job_type="refresh_column", + job_state="IN_PROGRESS", + creation_ms=2000, + spec=dict(column="vec"), + ) def handler(request): content_len = int(request.headers.get("Content-Length", 0)) body = request.rfile.read(content_len) if content_len > 0 else b"" payload = json.loads(body) if body else {} if request.path == "/v1/jobs/describe": + descriptions.append(payload) request.send_response(200) request.send_header("Content-Type", "application/json") request.end_headers() - request.wfile.write( - json.dumps( - dict( - job_id="job-1", - job_type="refresh_column", - job_state="DONE", - creation_ms=2000, - spec=dict(column="vec"), - result=dict(rows_assigned=1000000), - ) - ).encode() - ) + request.wfile.write(json.dumps(description).encode()) elif request.path == "/v1/jobs/query_events": event_payloads.append(payload) request.send_response(200) @@ -7184,39 +7189,75 @@ def test_remote_job_handle_reports_its_own_detail(): request.send_response(404) request.end_headers() - with mock_lancedb_connection(handler) as db: - job = db.open_job("job-1") + async def check_job(db): + job = ( + await db.open_job("job-1") + if is_async + else await asyncio.to_thread(db.open_job, "job-1") + ) # Opening populates the handle in the same round trip. - assert job.state == "finished" - job.refresh() - assert job.job_type == "refresh_column" - assert job.creation_ms == 2000 - assert job.spec == {"column": "vec"} - assert job.result == {"rows_assigned": 1000000} - assert job.failure is None + assert job.state() == "running" + assert job.result() is None + assert job.failure() is None + description["job_state"] = terminal_state + expected_result = ( + {"rows_assigned": 1000000} if terminal_state == "DONE" else None + ) + description["result"] = expected_result + if terminal_state == "FAILED": + description["failure"] = {"phase": "execute", "message": "worker failed"} + assert job.state() == "running" + assert job.result() is None + assert job.failure() is None + assert len(descriptions) == 1 + + refresh = getattr(job, refresh_method) + if is_async: + assert await refresh() is None + else: + assert await asyncio.to_thread(refresh) is None + expected_state = "finished" if terminal_state == "DONE" else "failed" + assert job.state() == expected_state + assert job.job_type() == "refresh_column" + assert job.creation_ms() == 2000 + assert job.spec() == {"column": "vec"} + assert job.result() == expected_result + if terminal_state == "FAILED": + assert job.failure().phase == "execute" + assert job.failure().message == "worker failed" + else: + assert job.failure() is None # The JSON payloads stay reachable, but as internal APIs. assert json.loads(job._spec_json) == {"column": "vec"} - assert json.loads(job._result_json) == {"rows_assigned": 1000000} + if expected_result is not None: + assert json.loads(job._result_json) == expected_result + assert repr(job) == "\n".join( + [ + f"{type(job).__name__}(", + " id='job-1',", + " state='finished',", + " job_type='refresh_column',", + " creation_ms=2000,", + " spec={'column': 'vec'},", + " result={'rows_assigned': 1000000},", + ")", + ] + ) + assert "failure" not in repr(job) - assert repr(job) == "\n".join( - [ - "Job(", - " id='job-1',", - " state='finished',", - " job_type='refresh_column',", - " creation_ms=2000,", - " spec={'column': 'vec'},", - " result={'rows_assigned': 1000000},", - ")", - ] + events = ( + await job.events(filter="state = 'claim_complete'", limit=500) + if is_async + else await asyncio.to_thread( + job.events, filter="state = 'claim_complete'", limit=500 + ) ) - # Nothing it does not know shows up. - assert "failure" not in repr(job) - - events = job.events(filter="state = 'claim_complete'", limit=500) assert isinstance(events, pa.Table) assert events.column("state").to_pylist() == ["claim_complete"] + assert len(descriptions) == 2 + assert job.state() == expected_state + assert job.result() == expected_result # The handle supplies job_id; the caller only narrows the query. assert event_payloads[-1] == { "job_id": "job-1", @@ -7224,6 +7265,13 @@ def test_remote_job_handle_reports_its_own_detail(): "filter": "state = 'claim_complete'", } + if is_async: + async with mock_lancedb_connection_async(handler) as db: + await check_job(db) + else: + with mock_lancedb_connection(handler) as db: + await check_job(db) + @pytest.mark.parametrize("is_async", [False, True]) @pytest.mark.parametrize("known_build", [False, True]) @@ -8489,12 +8537,12 @@ async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mod job = await table.prewarm_data_async( ["attrs.score"], filter="id >= 8", concurrency=4 ) - assert job.id == "warming-job" + assert job.id() == "warming-job" assert not polls assert (await job.wait()).table_version == 42 await job.refresh() - assert job.spec["table_version"] == 42 - reopened = await db.open_job(job.id) + assert job.spec()["table_version"] == 42 + reopened = await db.open_job(job.id()) assert (await reopened.wait()).executors_completed == 2 assert (await job.progress())["executors_completed"] == 2 assert (await job.wait()).bytes_read is None @@ -8516,12 +8564,12 @@ async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mod job = table.prewarm_data_async( ["attrs.score"], filter="id >= 8", concurrency=4 ) - assert job.id == "warming-job" + assert job.id() == "warming-job" assert not polls assert job.wait().table_version == 42 job.refresh() - assert job.spec["table_version"] == 42 - assert db.open_job(job.id).wait().executors_completed == 2 + assert job.spec()["table_version"] == 42 + assert db.open_job(job.id()).wait().executors_completed == 2 assert job.progress()["executors_completed"] == 2 assert job.wait().bytes_read is None assert len(server.tickets) == 1 @@ -8647,7 +8695,7 @@ async def test_prewarm_bound_parameters_reach_flight(asynchronous, method, named assert result.table_version == 42 assert result.pruning.selected_fragments == 1 else: - assert result.id == "bound-job" + assert result.id() == "bound-job" ((command, received),) = server.calls assert b"PREWARM" in command and predicate.encode() in command if method == "explain_prewarm_data": @@ -8762,7 +8810,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome): job = await table.compact_async( compaction_options={"target_rows_per_fragment": 100} ) - assert job.id == "compacting-job" and not polls + assert job.id() == "compacting-job" and not polls if outcome in ("missing", "FAILED", "CANCELLED"): with pytest.raises( Exception, @@ -8775,7 +8823,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome): await job.wait() else: stats = await job.wait() - reopened = await db.open_job(job.id) + reopened = await db.open_job(job.id()) assert await reopened.wait() == stats else: db = lancedb.connect(**kwargs) @@ -8783,7 +8831,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome): job = table.compact_async( compaction_options={"target_rows_per_fragment": 100} ) - assert job.id == "compacting-job" and not polls + assert job.id() == "compacting-job" and not polls if outcome in ("missing", "FAILED", "CANCELLED"): with pytest.raises( Exception, @@ -8796,7 +8844,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome): job.wait() else: stats = job.wait() - assert db.open_job(job.id).wait() == stats + assert db.open_job(job.id()).wait() == stats if outcome in ("counts", "legacy", "partial", "bounded", "no_op"): from lancedb.compaction import CompactionResult diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 420a29bd4..2c3ce4a52 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -2312,7 +2312,7 @@ async def test_async_open_table_with_branch_version(tmp_path): def test_create_index_async_returns_done_job(mem_db: DBConnection): table = mem_db.create_table("job_test", [{"id": i} for i in range(10)]) job = table.create_index_async("id", config=BTree()) - assert job.id is None + assert job.id() is None assert job.wait() is None assert len(table.list_indices()) == 1 job.cancel() @@ -6646,7 +6646,7 @@ def test_refresh_column_async_returns_job(tmp_path, batch_size): table.add_columns(computed={"doubled": "x * 2"}) job = table.refresh_column_async("doubled", batch_size=batch_size) - assert job.id is None # in-process jobs have no server id + assert job.id() is None # in-process jobs have no server id result = job.wait() assert isinstance(result, lancedb.RefreshColumnResult) assert result.rows_assigned == 2 From b44807e4db056c33c47878c5e2c83727a101f8bc Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 20 Nov 2026 20:35:59 -0800 Subject: [PATCH 65/78] fix!: preserve job attempt lineage, retries, and lifecycle states BREAKING CHANGE: JobDescription, JobEventsRequest, FunctionErrorsRequest, and FunctionErrors gain optional Rust metadata/cursor fields. Existing struct literals must initialize them; use None when unavailable. Preserve typed attempt state, pinned retry lineage, result decoders and freshness fences, and retained diagnostic paging across SDKs. Keep Python job data access method-only. --- docs/src/js/classes/Job.md | 147 ++++++++++ docs/src/js/globals.md | 1 + docs/src/js/interfaces/CherryPickResult.md | 2 +- .../FunctionColumnAutoRefreshStatus.md | 4 +- docs/src/js/interfaces/FunctionErrors.md | 10 + .../js/interfaces/FunctionErrorsOptions.md | 10 + docs/src/js/interfaces/JobEventsOptions.md | 10 + docs/src/js/type-aliases/JobState.md | 21 ++ docs/src/python/python.md | 49 ++++ docs/web/basics/jobs.mdx | 186 +++++++++++- docs/web/maintenance/cleanup.mdx | 6 +- nodejs/__test__/job.test.ts | 48 ++++ nodejs/__test__/remote.test.ts | 2 + nodejs/lancedb/index.ts | 17 +- nodejs/lancedb/job.ts | 91 +++++- nodejs/src/job.rs | 59 +++- nodejs/src/table.rs | 6 + python/python/lancedb/__init__.py | 3 +- python/python/lancedb/_lancedb.pyi | 32 +++ python/python/lancedb/functions.py | 1 + python/python/lancedb/job.py | 218 +++++++++++++- python/python/lancedb/remote/table.py | 7 +- python/python/lancedb/table.py | 27 +- python/python/tests/test_cleanup.py | 4 +- python/python/tests/test_job.py | 58 +++- python/python/tests/test_remote_db.py | 44 +++ python/src/job.rs | 71 ++++- python/src/table.rs | 6 +- rust/lancedb/src/database.rs | 36 +++ rust/lancedb/src/function.rs | 14 + rust/lancedb/src/job.rs | 247 +++++++++++++++- rust/lancedb/src/job/state.rs | 63 +++++ rust/lancedb/src/lib.rs | 2 +- rust/lancedb/src/remote/job.rs | 266 +++++++++++++++++- rust/lancedb/src/remote/table.rs | 109 ++++++- 35 files changed, 1822 insertions(+), 55 deletions(-) create mode 100644 docs/src/js/type-aliases/JobState.md create mode 100644 nodejs/__test__/job.test.ts create mode 100644 rust/lancedb/src/job/state.rs 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] From 6a7a2c4ec00df459ff9b1f62bf82f7fd6a0b6d82 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 15:43:16 +0800 Subject: [PATCH 66/78] feat(nodejs): add table delta streams (#5149) Adds the Embedded `Table.delta` API to the Node.js bindings, matching the Rust/Python contract from #5135. `Table.delta(fromVersion, toVersion?)` accepts a positive safe-integer number, a positive lossless u64 `bigint`, or a same-branch tag string. `TableDelta` exposes `beginVersion`/`endVersion` as `bigint`, streaming `insertedRows()`, `updatedRows()`, `upsertedRows()`, `deletedRowIds()`, and `listTransactions()` with `readVersion` as `bigint`. Readers reuse the existing native Arrow IPC iterator adapter. They are lazy, single-use, serialize pulls, capture/cache the schema before polling, and release the native stream on completion, break, or error. Row readers retain the Rust contract: equal endpoints return empty streams with schemas, invalid/reversed/missing endpoints and cross-branch tags are rejected, and Restore or incomplete transaction history fail closed with full-rescan and range-end checkpoint guidance. Enterprise tables remain unsupported through the native Rust default. The abstract `Table` keeps a concrete unsupported `delta` default for custom subclasses; `LocalTable` overrides it. TypeDoc API docs and focused Node tests cover pinned targets, typed bigint values, transaction listing, lazy rejected readers, schema/decode failures, aliasing, and early drop. Refs OSS-2860 --- docs/src/js/classes/Table.md | 47 +++ docs/src/js/classes/TableDelta.md | 110 ++++++ docs/src/js/globals.md | 4 + docs/src/js/interfaces/TableDeltaReader.md | 109 ++++++ .../js/interfaces/TableDeltaTransaction.md | 51 +++ docs/src/js/type-aliases/DeltaVersion.md | 17 + docs/web-tests/ts/table_delta_docs.ts | 64 ++++ docs/web/management/table.mdx | 14 +- docs/web/snippets/table_delta_docs.mdx | 2 + nodejs/__test__/remote.test.ts | 3 + nodejs/__test__/table.test.ts | 278 +++++++++++++++ nodejs/lancedb/index.ts | 4 + nodejs/lancedb/table.ts | 324 ++++++++++++++++++ nodejs/src/table.rs | 139 +++++++- 14 files changed, 1160 insertions(+), 6 deletions(-) create mode 100644 docs/src/js/classes/TableDelta.md create mode 100644 docs/src/js/interfaces/TableDeltaReader.md create mode 100644 docs/src/js/interfaces/TableDeltaTransaction.md create mode 100644 docs/src/js/type-aliases/DeltaVersion.md create mode 100644 docs/web-tests/ts/table_delta_docs.ts diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 67962578f..781f7b24a 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -552,6 +552,53 @@ containing the new version number of the table *** +### delta() + +```ts +delta(fromVersion, toVersion?): Promise +``` + +Compare two persisted versions or same-branch tags on an Embedded table. + +`fromVersion` is exclusive and `toVersion` is inclusive. Omitting +`toVersion` uses the version currently visible through this handle, +including a checked-out version. The endpoints are fixed when the delta is +created. + +Row readers require stable row IDs at both endpoints. Create the table with +`storageOptions: { new_table_enable_stable_row_ids: "true" }` to enable +them. `listTransactions()` works without stable row IDs. + +Row readers reject ranges containing a Restore, or ranges whose transaction +history cannot prove they are restore-free. Recompute the checkpoint with a +full rescan and reinitialize it at the range end version. + +LanceDB Enterprise tables reject this operation. + +#### Parameters + +* **fromVersion**: [`DeltaVersion`](../type-aliases/DeltaVersion.md) + +* **toVersion?**: [`DeltaVersion`](../type-aliases/DeltaVersion.md) + +#### Returns + +`Promise`<[`TableDelta`](TableDelta.md)> + +#### Example + +```ts +const delta = await table.delta("baseline"); +const reader = delta.insertedRows(); +console.log((await reader.schema()).fields.map((field) => field.name)); +for await (const batch of reader) { + console.log(batch.getChild("id")?.toJSON()); +} +console.log(await delta.listTransactions()); +``` + +*** + ### disableRTE() ```ts diff --git a/docs/src/js/classes/TableDelta.md b/docs/src/js/classes/TableDelta.md new file mode 100644 index 000000000..9318c324b --- /dev/null +++ b/docs/src/js/classes/TableDelta.md @@ -0,0 +1,110 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / TableDelta + +# Class: TableDelta + +A handle for reading changes between two pinned table versions. + +Created by [Table.delta](Table.md#delta). Endpoints are fixed at creation; later writes +or tag moves do not change this delta. + +## Accessors + +### beginVersion + +```ts +get beginVersion(): bigint +``` + +The exclusive start version, as an exact u64 bigint. + +#### Returns + +`bigint` + +*** + +### endVersion + +```ts +get endVersion(): bigint +``` + +The inclusive end version, as an exact u64 bigint. + +#### Returns + +`bigint` + +## Methods + +### deletedRowIds() + +```ts +deletedRowIds(): TableDeltaReader +``` + +Stream deleted row IDs. Each batch has one `_rowid: uint64` column. + +#### Returns + +[`TableDeltaReader`](../interfaces/TableDeltaReader.md) + +*** + +### insertedRows() + +```ts +insertedRows(): TableDeltaReader +``` + +Stream rows inserted in `(beginVersion, endVersion]`. + +#### Returns + +[`TableDeltaReader`](../interfaces/TableDeltaReader.md) + +*** + +### listTransactions() + +```ts +listTransactions(): Promise +``` + +List readable transactions committed in `(beginVersion, endVersion]`. + +#### Returns + +`Promise`<[`TableDeltaTransaction`](../interfaces/TableDeltaTransaction.md)[]> + +*** + +### updatedRows() + +```ts +updatedRows(): TableDeltaReader +``` + +Stream rows updated in `(beginVersion, endVersion]`. + +#### Returns + +[`TableDeltaReader`](../interfaces/TableDeltaReader.md) + +*** + +### upsertedRows() + +```ts +upsertedRows(): TableDeltaReader +``` + +Stream inserted and updated rows in `(beginVersion, endVersion]`. + +#### Returns + +[`TableDeltaReader`](../interfaces/TableDeltaReader.md) diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 1769c6c1f..7f7518a27 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -49,6 +49,7 @@ - [Session](classes/Session.md) - [StaticHeaderProvider](classes/StaticHeaderProvider.md) - [Table](classes/Table.md) +- [TableDelta](classes/TableDelta.md) - [TagContents](classes/TagContents.md) - [Tags](classes/Tags.md) - [TakeQuery](classes/TakeQuery.md) @@ -158,6 +159,8 @@ - [SplitRandomOptions](interfaces/SplitRandomOptions.md) - [SplitSequentialOptions](interfaces/SplitSequentialOptions.md) - [SsTableStats](interfaces/SsTableStats.md) +- [TableDeltaReader](interfaces/TableDeltaReader.md) +- [TableDeltaTransaction](interfaces/TableDeltaTransaction.md) - [TableNamesOptions](interfaces/TableNamesOptions.md) - [TableShardStats](interfaces/TableShardStats.md) - [TableStatistics](interfaces/TableStatistics.md) @@ -189,6 +192,7 @@ - [Data](type-aliases/Data.md) - [DataLike](type-aliases/DataLike.md) - [DataTypeLike](type-aliases/DataTypeLike.md) +- [DeltaVersion](type-aliases/DeltaVersion.md) - [ExprLike](type-aliases/ExprLike.md) - [FieldLike](type-aliases/FieldLike.md) - [IntoSql](type-aliases/IntoSql.md) diff --git a/docs/src/js/interfaces/TableDeltaReader.md b/docs/src/js/interfaces/TableDeltaReader.md new file mode 100644 index 000000000..f05d56a37 --- /dev/null +++ b/docs/src/js/interfaces/TableDeltaReader.md @@ -0,0 +1,109 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / TableDeltaReader + +# Interface: TableDeltaReader + +A streaming table-delta reader. + +`schema()` is available before consuming the stream, including when the +range is empty. The stream yields Arrow record batches without +materializing the full result. + +A reader owns one native cursor. It is single-use: +`[Symbol.asyncIterator]()` returns the same iterator, concurrent pulls are +serialized, and `return()` releases the native stream on early drop. + +## Extends + +- `AsyncIterable`<`RecordBatch`>.`AsyncIterator`<`RecordBatch`> + +## Methods + +### \[asyncIterator\]() + +```ts +asyncIterator: AsyncIterator, any, undefined> +``` + +#### Returns + +`AsyncIterator`<`RecordBatch`<`any`>, `any`, `undefined`> + +#### Inherited from + +`AsyncIterable.[asyncIterator]` + +*** + +### next() + +```ts +next(...args): Promise, any>> +``` + +#### Parameters + +* ...**args**: [] \| [`undefined`] + +#### Returns + +`Promise`<`IteratorResult`<`RecordBatch`<`any`>, `any`>> + +#### Inherited from + +`AsyncIterator.next` + +*** + +### return()? + +```ts +optional return(value?): Promise, any>> +``` + +#### Parameters + +* **value?**: `any` + +#### Returns + +`Promise`<`IteratorResult`<`RecordBatch`<`any`>, `any`>> + +#### Inherited from + +`AsyncIterator.return` + +*** + +### schema() + +```ts +schema(): Promise> +``` + +#### Returns + +`Promise`<`Schema`<`any`>> + +*** + +### throw()? + +```ts +optional throw(e?): Promise, any>> +``` + +#### Parameters + +* **e?**: `any` + +#### Returns + +`Promise`<`IteratorResult`<`RecordBatch`<`any`>, `any`>> + +#### Inherited from + +`AsyncIterator.throw` diff --git a/docs/src/js/interfaces/TableDeltaTransaction.md b/docs/src/js/interfaces/TableDeltaTransaction.md new file mode 100644 index 000000000..1c2bda71d --- /dev/null +++ b/docs/src/js/interfaces/TableDeltaTransaction.md @@ -0,0 +1,51 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / TableDeltaTransaction + +# Interface: TableDeltaTransaction + +A committed transaction in a table delta range. + +## Properties + +### operation + +```ts +operation: string; +``` + +*** + +### readVersion + +```ts +readVersion: bigint; +``` + +The version the transaction was based on. Exact u64 value. + +*** + +### tag? + +```ts +optional tag: string; +``` + +*** + +### transactionProperties? + +```ts +optional transactionProperties: Record; +``` + +*** + +### uuid + +```ts +uuid: string; +``` diff --git a/docs/src/js/type-aliases/DeltaVersion.md b/docs/src/js/type-aliases/DeltaVersion.md new file mode 100644 index 000000000..263b5614c --- /dev/null +++ b/docs/src/js/type-aliases/DeltaVersion.md @@ -0,0 +1,17 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / DeltaVersion + +# Type Alias: DeltaVersion + +```ts +type DeltaVersion: number | bigint | string; +``` + +One endpoint of a table delta: a positive version number/bigint or a tag on +the table handle's current branch. + +Use a `bigint` when the version may exceed `Number.MAX_SAFE_INTEGER`. +Strings are always tags. diff --git a/docs/web-tests/ts/table_delta_docs.ts b/docs/web-tests/ts/table_delta_docs.ts new file mode 100644 index 000000000..8182ca88e --- /dev/null +++ b/docs/web-tests/ts/table_delta_docs.ts @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import type { Connection } from "@lancedb/lancedb"; + +/** + * Draft checkpoint-delta example for the Versioning guide. + * + * This file is snippet source only. The published documentation test package is + * pinned to an older npm release, so it is not part of the Jest test glob. + */ +export async function versioningCheckpointDeltaExample( + db: Connection, +): Promise { + // --8<-- [start:versioning_checkpoint_delta] + const table = await db.createTable( + "checkpoint_delta_example", + [ + { id: 1, author: "Richard", quote: "Wubba Lubba Dub Dub!" }, + { id: 2, author: "Morty", quote: "Rick, what's going on?" }, + ], + { + mode: "overwrite", + storageOptions: { new_table_enable_stable_row_ids: "true" }, + }, + ); + const tags = await table.tags(); + await tags.create("baseline", await table.version()); + await table.add([ + { id: 3, author: "Summer", quote: "Whatever, Grandpa" }, + ]); + await table.update({ + where: "id = 2", + values: { quote: "Aww geez, Rick!" }, + }); + await table.delete("id = 1"); + + const delta = await table.delta("baseline"); + console.log(delta.beginVersion, delta.endVersion); + + const inserted = delta.insertedRows(); + console.log((await inserted.schema()).fields.map((field) => field.name)); + for await (const batch of inserted) { + console.log("inserted:", batch.getChild("id")?.toJSON()); + } + + const updated = delta.updatedRows(); + for await (const batch of updated) { + console.log("updated:", batch.getChild("id")?.toJSON()); + } + + const deleted = delta.deletedRowIds(); + for await (const batch of deleted) { + console.log("deleted row ids:", batch.getChild("_rowid")?.toJSON()); + } + + console.log( + "transactions:", + (await delta.listTransactions()).map( + (transaction) => transaction.operation, + ), + ); + // --8<-- [end:versioning_checkpoint_delta] +} diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index e09369dbd..0beb9836b 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -89,6 +89,7 @@ import { } from '/snippets/tables.mdx'; import { PyVersioningCheckpointDelta as VersioningCheckpointDelta, + TsVersioningCheckpointDelta as TsVersioningCheckpointDelta, RsVersioningCheckpointDelta as RsVersioningCheckpointDelta, } from '/snippets/table_delta_docs.mdx'; import { @@ -1786,10 +1787,11 @@ with stable row IDs enabled, as shown below. If a table does not have them, the row-level readers explain how to recreate it with the option. `list_transactions()` reports the transactions in the range and works without stable row IDs. -This preview supports Python and Rust for LanceDB Embedded. TypeScript support -is a follow-up. The API accepts versions and tags on the current branch only, -and rejects tags that belong to another branch. LanceDB Enterprise tables do -not support row-level deltas. +This preview supports Python, TypeScript, and Rust for LanceDB Embedded. The +API accepts versions and tags on the current branch only, and rejects tags that +belong to another branch. TypeScript exposes endpoint and transaction +`readVersion` values as `bigint`, and reader schemas are available before +streaming. LanceDB Enterprise tables do not support row-level deltas. A `Restore` can reintroduce rows with older row-version metadata that the delta readers do not report as changed. For that reason, the row-level readers reject @@ -1804,6 +1806,10 @@ range. Branch-vs-main summaries remain a separate `branches.diff()` API. {VersioningCheckpointDelta} + + {TsVersioningCheckpointDelta} + + {RsVersioningCheckpointDelta} diff --git a/docs/web/snippets/table_delta_docs.mdx b/docs/web/snippets/table_delta_docs.mdx index a1beb901b..89f5b8305 100644 --- a/docs/web/snippets/table_delta_docs.mdx +++ b/docs/web/snippets/table_delta_docs.mdx @@ -2,4 +2,6 @@ export const PyVersioningCheckpointDelta = "table = db.create_table(\n \"checkpoint_delta_example\",\n [\n {\"id\": 1, \"author\": \"Richard\", \"quote\": \"Wubba Lubba Dub Dub!\"},\n {\"id\": 2, \"author\": \"Morty\", \"quote\": \"Rick, what's going on?\"},\n ],\n storage_options={\"new_table_enable_stable_row_ids\": \"true\"},\n mode=\"overwrite\",\n)\ntable.tags.create(\"baseline\", table.version)\ntable.add([{\"id\": 3, \"author\": \"Summer\", \"quote\": \"Whatever, Grandpa\"}])\ntable.update(where=\"id = 2\", values={\"quote\": \"Aww geez, Rick!\"})\ntable.delete(\"id = 1\")\n\ndelta = table.delta(\"baseline\")\nprint(\"inserted:\", delta.inserted_rows().read_all()[\"id\"].to_pylist())\nprint(\"updated:\", delta.updated_rows().read_all()[\"id\"].to_pylist())\nprint(\"deleted:\", delta.deleted_row_ids().read_all()[\"_rowid\"].to_pylist())\nprint(\n \"transactions:\",\n [transaction[\"operation\"] for transaction in delta.list_transactions()],\n)\n"; +export const TsVersioningCheckpointDelta = "const table = await db.createTable(\n \"checkpoint_delta_example\",\n [\n { id: 1, author: \"Richard\", quote: \"Wubba Lubba Dub Dub!\" },\n { id: 2, author: \"Morty\", quote: \"Rick, what's going on?\" },\n ],\n {\n mode: \"overwrite\",\n storageOptions: { new_table_enable_stable_row_ids: \"true\" },\n },\n);\nconst tags = await table.tags();\nawait tags.create(\"baseline\", await table.version());\nawait table.add([\n { id: 3, author: \"Summer\", quote: \"Whatever, Grandpa\" },\n]);\nawait table.update({\n where: \"id = 2\",\n values: { quote: \"Aww geez, Rick!\" },\n});\nawait table.delete(\"id = 1\");\n\nconst delta = await table.delta(\"baseline\");\nconsole.log(delta.beginVersion, delta.endVersion);\n\nconst inserted = delta.insertedRows();\nconsole.log((await inserted.schema()).fields.map((field) => field.name));\nfor await (const batch of inserted) {\n console.log(\"inserted:\", batch.getChild(\"id\")?.toJSON());\n}\n\nconst updated = delta.updatedRows();\nfor await (const batch of updated) {\n console.log(\"updated:\", batch.getChild(\"id\")?.toJSON());\n}\n\nconst deleted = delta.deletedRowIds();\nfor await (const batch of deleted) {\n console.log(\"deleted row ids:\", batch.getChild(\"_rowid\")?.toJSON());\n}\n\nconsole.log(\n \"transactions:\",\n (await delta.listTransactions()).map(\n (transaction) => transaction.operation,\n ),\n);\n"; + export const RsVersioningCheckpointDelta = "use futures::TryStreamExt;\n\nlet table = db\n .create_table(\n \"checkpoint_delta_example\",\n make_quotes_reader(vec![\n (1, \"Richard\", \"Wubba Lubba Dub Dub!\"),\n (2, \"Morty\", \"Rick, what's going on?\"),\n ]),\n )\n .storage_option(\"new_table_enable_stable_row_ids\", \"true\")\n .execute()\n .await?;\n\nlet mut tags = table.tags().await?;\ntags.create(\"baseline\", table.version().await?).await?;\ntable\n .add(make_quotes_reader(vec![(3, \"Summer\", \"Whatever, Grandpa\")]))\n .execute()\n .await?;\ntable\n .update()\n .only_if(\"id = 2\")\n .column(\"quote\", \"'Aww geez, Rick!'\")\n .execute()\n .await?;\ntable.delete(\"id = 1\").await?;\n\nlet delta = table.delta(\"baseline\", None).await?;\nlet mut inserted = delta.inserted_rows().await?;\nwhile let Some(batch) = inserted.try_next().await? {\n println!(\"inserted: {:?}\", batch.column_by_name(\"id\"));\n}\nlet mut deleted = delta.deleted_row_ids().await?;\nwhile let Some(batch) = deleted.try_next().await? {\n println!(\"deleted row ids: {batch:?}\");\n}\nfor transaction in delta.list_transactions().await? {\n println!(\"{}\", transaction.operation.name());\n}\n"; diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index a77795a56..602239544 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -309,6 +309,9 @@ describe("remote connection", () => { }, async (db) => { const table = (await db.openTable("test")) as LocalTable; + await expect(table.delta(1)).rejects.toThrow( + "table.delta is only supported on LanceDB Embedded tables", + ); const cases: [() => Promise, string][] = [ [() => table.usesV2ManifestPaths(), "uses_v2_manifest_paths"], [() => table.migrateManifestPathsV2(), "migrate_manifest_paths_v2"], diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index a8bec5c98..970f2f7ca 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -17,6 +17,8 @@ import { PhraseQuery, Query, Table, + TableDelta, + TableDeltaReader, VectorQuery, blob, connect, @@ -4139,6 +4141,279 @@ describe("when dealing with branches", () => { }); }); +describe("when dealing with table delta", () => { + let tmpDir: tmp.DirResult; + // biome-ignore lint/style/useNamingConvention: storage option wire format + const stableRowIds = { new_table_enable_stable_row_ids: "true" }; + + beforeEach(() => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + }); + afterEach(() => { + tmpDir.removeCallback(); + }); + + async function readDelta( + reader: TableDeltaReader, + ): Promise { + const batches: arrow.RecordBatch[] = []; + for await (const batch of reader) { + batches.push(batch); + } + return batches; + } + + function deltaColumn(batches: arrow.RecordBatch[], name: string): unknown[] { + return batches.flatMap((batch) => batch.getChild(name)?.toJSON() ?? []); + } + + it("streams rows, transactions, and empty schemas", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable( + "delta_rows", + [ + { id: 1, value: 0 }, + { id: 2, value: 0 }, + ], + { mode: "overwrite", storageOptions: stableRowIds }, + ); + const tags = await table.tags(); + await tags.create("baseline", await table.version()); + await table.add([{ id: 3, value: 0 }]); + await table.update({ where: "id = 1", values: { value: 10 } }); + await table.delete("id = 2"); + + const delta = await table.delta("baseline", 4n); + expect(delta.beginVersion).toBe(1n); + expect(delta.endVersion).toBe(4n); + + const insertedReader = delta.insertedRows(); + expect( + (await insertedReader.schema()).fields.map((field) => field.name), + ).toEqual([ + "id", + "value", + "_rowid", + "_row_created_at_version", + "_row_last_updated_at_version", + ]); + const inserted = await readDelta(insertedReader); + expect(deltaColumn(inserted, "id")).toEqual([3]); + + const updated = await readDelta(delta.updatedRows()); + expect(deltaColumn(updated, "id")).toEqual([1]); + const upserted = await readDelta(delta.upsertedRows()); + expect((deltaColumn(upserted, "id") as number[]).sort()).toEqual([1, 3]); + + const deleted = await readDelta(delta.deletedRowIds()); + expect(deleted).toHaveLength(1); + expect(deleted[0].schema.fields.map((field) => field.name)).toEqual([ + "_rowid", + ]); + const deletedIds = deltaColumn(deleted, "_rowid"); + expect(deletedIds).toHaveLength(1); + expect(typeof deletedIds[0]).toBe("bigint"); + + const transactions = await delta.listTransactions(); + expect(transactions.map((tx) => tx.operation)).toEqual([ + "Append", + "Update", + "Delete", + ]); + expect(transactions.map((tx) => tx.readVersion)).toEqual([1n, 2n, 3n]); + expect(transactions.every((tx) => typeof tx.readVersion === "bigint")).toBe( + true, + ); + + // Early drop after the first batch must not throw or force the rest of the + // stream to materialize. + let batchesSeen = 0; + for await (const _batch of delta.upsertedRows()) { + batchesSeen += 1; + break; + } + expect(batchesSeen).toBe(1); + + const equal = await table.delta(2, 2); + const equalReader = equal.insertedRows(); + expect( + (await equalReader.schema()).fields.map((field) => field.name), + ).toEqual([ + "id", + "value", + "_rowid", + "_row_created_at_version", + "_row_last_updated_at_version", + ]); + expect(await readDelta(equalReader)).toEqual([]); + expect( + (await equal.deletedRowIds().schema()).fields.map((field) => field.name), + ).toEqual(["_rowid"]); + expect(await equal.listTransactions()).toEqual([]); + }); + + it("pins the visible target without moving checkout state", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("delta_pinned", [{ id: 1 }], { + storageOptions: stableRowIds, + }); + await table.add([{ id: 2 }]); + await table.update({ where: "id = 1", values: { id: 10 } }); + + await table.checkout(2); + const pinned = await table.delta(1n); + expect(pinned.beginVersion).toBe(1n); + expect(pinned.endVersion).toBe(2n); + expect(deltaColumn(await readDelta(pinned.insertedRows()), "id")).toEqual([ + 2, + ]); + expect(await table.version()).toBe(2); + + const explicit = await table.delta(1n, 3n); + expect(deltaColumn(await readDelta(explicit.updatedRows()), "id")).toEqual([ + 10, + ]); + expect(await table.version()).toBe(2); + await table.checkoutLatest(); + }); + + it("does not start a rejected reader until it is used", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("delta_lazy", [{ id: 1 }]); + await table.add([{ id: 2 }]); + + const delta = await table.delta(1); + const reader = delta.insertedRows(); + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", onUnhandled); + try { + await new Promise((resolve) => setTimeout(resolve, 25)); + expect(unhandled).toEqual([]); + await expect(reader.schema()).rejects.toThrow(/stable row ids/); + await expect(reader.next()).rejects.toThrow(/stable row ids/); + } finally { + process.off("unhandledRejection", onUnhandled); + } + }); + + it("routes schema and Arrow decode failures through terminal cleanup", async () => { + let schemaOpens = 0; + const schemaFailure = new TableDelta({ + insertedRows: async () => { + schemaOpens += 1; + return { + schema: async () => { + throw new Error("schema export failed"); + }, + next: async () => { + throw new Error("reader must not poll after schema failure"); + }, + }; + }, + } as never); + + const schemaReader = schemaFailure.insertedRows(); + await expect(schemaReader.schema()).rejects.toThrow("schema export failed"); + await expect(schemaReader.next()).rejects.toThrow("schema export failed"); + expect(schemaOpens).toBe(1); + + const nextReader = schemaFailure.insertedRows(); + await expect(nextReader.next()).rejects.toThrow("schema export failed"); + expect(schemaOpens).toBe(2); + + let decodeOpens = 0; + const decodeFailure = new TableDelta({ + insertedRows: async () => { + decodeOpens += 1; + return { + schema: async () => Buffer.from("not an Arrow IPC schema"), + next: async () => { + throw new Error("reader must not poll after decode failure"); + }, + }; + }, + } as never); + + const decodeReader = decodeFailure.insertedRows(); + await expect(decodeReader.schema()).rejects.toThrow(); + await expect(decodeReader.next()).rejects.toThrow(); + expect(decodeOpens).toBe(1); + }); + + it("uses one reader cursor and releases it on early drop", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("delta_reader", [{ id: 1 }], { + storageOptions: stableRowIds, + }); + await table.add([{ id: 2 }]); + const delta = await table.delta(1); + + const reader = delta.insertedRows(); + expect(reader[Symbol.asyncIterator]()).toBe(reader); + const first = await reader.next(); + expect(first.done).toBe(false); + const [second, third] = await Promise.all([reader.next(), reader.next()]); + expect(second.done).toBe(true); + expect(third.done).toBe(true); + expect((await reader.schema()).fields.map((field) => field.name)).toEqual([ + "id", + "_rowid", + "_row_created_at_version", + "_row_last_updated_at_version", + ]); + + const dropped = delta.insertedRows(); + for await (const _batch of dropped) { + break; + } + expect(await dropped.next()).toEqual({ done: true, value: undefined }); + expect((await dropped.schema()).fields.map((field) => field.name)).toEqual([ + "id", + "_rowid", + "_row_created_at_version", + "_row_last_updated_at_version", + ]); + }); + + it("rejects invalid endpoints and cross-branch tags", async () => { + const conn = await connect(tmpDir.name, { readConsistencyInterval: 0 }); + const table = await conn.createTable("delta_errors", [{ id: 0 }], { + storageOptions: stableRowIds, + }); + await table.add([{ id: 1 }]); + const forkVersion = await table.version(); + + await expect(table.delta(0)).rejects.toThrow(/positive/); + await expect(table.delta(0n)).rejects.toThrow(/positive u64/); + await expect(table.delta(1n << 64n)).rejects.toThrow(/u64 bigint/); + await expect(table.delta(-1)).rejects.toThrow(/positive/); + await expect(table.delta("")).rejects.toThrow(/non-empty/); + await expect(table.delta(1.5)).rejects.toThrow(/safe integer/); + await expect(table.delta(Number.MAX_SAFE_INTEGER + 1)).rejects.toThrow( + /safe integer/, + ); + await expect(table.delta(2, 1)).rejects.toThrow(/newer than/); + await expect(table.delta(999)).rejects.toThrow(/does not exist/); + await expect(table.delta("missing-tag")).rejects.toThrow(/does not exist/); + + const branch = await (await table.branches()).create("exp"); + await branch.add([{ id: 2 }]); + await table.add([{ id: 100 }]); + expect(await branch.version()).toBe(await table.version()); + await (await table.tags()).create("main-tag", await table.version()); + await (await branch.tags()).create("exp-tag", await branch.version()); + + const sameBranch = await branch.delta(BigInt(forkVersion), "exp-tag"); + expect(sameBranch.endVersion).toBe(3n); + expect( + deltaColumn(await readDelta(sameBranch.insertedRows()), "id"), + ).toEqual([2]); + await expect(branch.delta("main-tag")).rejects.toThrow(/branch/i); + await expect(table.delta("exp-tag")).rejects.toThrow(/branch/i); + }); +}); + /** Returns a Date strictly later than every instant observed before the call. */ async function nextMillisecond(): Promise { const start = Date.now(); @@ -6142,6 +6417,9 @@ describe("Enterprise table overrides", () => { class LegacyTable extends Table {} const table = new LegacyTable(); + await expect(table.delta(1)).rejects.toThrow( + "table.delta is only supported on LanceDB Embedded tables", + ); await expect(table.getTableOverrides()).rejects.toThrow( "getTableOverrides is not supported on this table type", ); diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index cbdfe2c18..516a3cd2d 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -164,6 +164,10 @@ export { export { Table, + TableDelta, + TableDeltaReader, + TableDeltaTransaction, + DeltaVersion, FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index e56711731..30fb60d23 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -24,6 +24,7 @@ import { Field, IntoVector, MultiVector, + RecordBatch, Schema, dataTypeToJson, fromDataToBuffer, @@ -57,7 +58,10 @@ import { IndexConfig, IndexStatistics, JobFailureInfo, + RecordBatchIterator as NativeBatchIterator, Branches as NativeBranches, + DeltaRef as NativeDeltaRef, + TableDelta as NativeTableDelta, OptimizeStats, RTEStats, RefreshColumnOptions, @@ -73,6 +77,7 @@ import { AutoQuery, FullTextQuery, Query, + RecordBatchIterator, TakeQuery, VectorQuery, createAutoQuery, @@ -253,6 +258,42 @@ export interface Version { metadata: Record; } +/** + * One endpoint of a table delta: a positive version number/bigint or a tag on + * the table handle's current branch. + * + * Use a `bigint` when the version may exceed `Number.MAX_SAFE_INTEGER`. + * Strings are always tags. + */ +export type DeltaVersion = number | bigint | string; + +/** A committed transaction in a table delta range. */ +export interface TableDeltaTransaction { + /** The version the transaction was based on. Exact u64 value. */ + readVersion: bigint; + uuid: string; + operation: string; + tag?: string; + transactionProperties?: Record; +} + +/** + * A streaming table-delta reader. + * + * `schema()` is available before consuming the stream, including when the + * range is empty. The stream yields Arrow record batches without + * materializing the full result. + * + * A reader owns one native cursor. It is single-use: + * `[Symbol.asyncIterator]()` returns the same iterator, concurrent pulls are + * serialized, and `return()` releases the native stream on early drop. + */ +export interface TableDeltaReader + extends AsyncIterable, + AsyncIterator { + schema(): Promise; +} + /** Token produced by the tokenizer configured on a full-text search index. */ export interface FtsToken { /** Token text after tokenizer filters have been applied. */ @@ -1349,6 +1390,43 @@ export abstract class Table { * out state and the read_consistency_interval, if any, will apply. */ abstract restore(): Promise; + + /** + * Compare two persisted versions or same-branch tags on an Embedded table. + * + * `fromVersion` is exclusive and `toVersion` is inclusive. Omitting + * `toVersion` uses the version currently visible through this handle, + * including a checked-out version. The endpoints are fixed when the delta is + * created. + * + * Row readers require stable row IDs at both endpoints. Create the table with + * `storageOptions: { new_table_enable_stable_row_ids: "true" }` to enable + * them. `listTransactions()` works without stable row IDs. + * + * Row readers reject ranges containing a Restore, or ranges whose transaction + * history cannot prove they are restore-free. Recompute the checkpoint with a + * full rescan and reinitialize it at the range end version. + * + * LanceDB Enterprise tables reject this operation. + * + * @example + * const delta = await table.delta("baseline"); + * const reader = delta.insertedRows(); + * console.log((await reader.schema()).fields.map((field) => field.name)); + * for await (const batch of reader) { + * console.log(batch.getChild("id")?.toJSON()); + * } + * console.log(await delta.listTransactions()); + */ + async delta( + // biome-ignore lint/correctness/noUnusedVariables: retain the public parameter name in generated docs + fromVersion: DeltaVersion, + // biome-ignore lint/correctness/noUnusedVariables: retain the public parameter name in generated docs + toVersion?: DeltaVersion, + ): Promise { + throw new Error("table.delta is only supported on LanceDB Embedded tables"); + } + /** * Submit durable remote cleanup through SQL VACUUM and return after acceptance. * Requires table Ownership and parent Usage. Retention inherits from the table @@ -2087,6 +2165,18 @@ export class LocalTable extends Table { await this.inner.checkoutLatest(); } + async delta( + fromVersion: DeltaVersion, + toVersion?: DeltaVersion, + ): Promise { + return new TableDelta( + await this.inner.delta( + toNativeDeltaRef(fromVersion), + toVersion === undefined ? undefined : toNativeDeltaRef(toVersion), + ), + ); + } + async listVersions(): Promise { return (await this.inner.listVersions()).map((version) => ({ version: version.version, @@ -2353,6 +2443,240 @@ export interface CreateBranchOptions { fromTag: string; } +/** + * A handle for reading changes between two pinned table versions. + * + * Created by {@link Table.delta}. Endpoints are fixed at creation; later writes + * or tag moves do not change this delta. + */ +export class TableDelta { + readonly #inner: NativeTableDelta; + + /** + * Construct a table-delta handle. Internal use only. + * @hidden + */ + constructor(inner: NativeTableDelta) { + this.#inner = inner; + } + + /** The exclusive start version, as an exact u64 bigint. */ + get beginVersion(): bigint { + return this.#inner.beginVersion(); + } + + /** The inclusive end version, as an exact u64 bigint. */ + get endVersion(): bigint { + return this.#inner.endVersion(); + } + + /** Stream rows inserted in `(beginVersion, endVersion]`. */ + insertedRows(): TableDeltaReader { + return tableDeltaReader(() => this.#inner.insertedRows()); + } + + /** Stream rows updated in `(beginVersion, endVersion]`. */ + updatedRows(): TableDeltaReader { + return tableDeltaReader(() => this.#inner.updatedRows()); + } + + /** Stream inserted and updated rows in `(beginVersion, endVersion]`. */ + upsertedRows(): TableDeltaReader { + return tableDeltaReader(() => this.#inner.upsertedRows()); + } + + /** Stream deleted row IDs. Each batch has one `_rowid: uint64` column. */ + deletedRowIds(): TableDeltaReader { + return tableDeltaReader(() => this.#inner.deletedRowIds()); + } + + /** List readable transactions committed in `(beginVersion, endVersion]`. */ + async listTransactions(): Promise { + const transactions = await this.#inner.listTransactions(); + return transactions.map((transaction) => ({ + readVersion: transaction.readVersion, + uuid: transaction.uuid, + operation: transaction.operation, + tag: transaction.tag ?? undefined, + transactionProperties: transaction.transactionProperties ?? undefined, + })); + } +} + +function toNativeDeltaRef(value: DeltaVersion): NativeDeltaRef { + if (typeof value === "string") { + if (value.length === 0) { + throw new Error("delta tag must be a non-empty string"); + } + return { tag: value }; + } + if (typeof value === "bigint") { + if (value <= 0n) { + throw new Error("delta version must be a positive u64 bigint"); + } + return { version: value }; + } + if (!Number.isSafeInteger(value) || value <= 0) { + throw new Error( + "delta version must be a positive safe integer; use bigint for larger versions", + ); + } + return { version: BigInt(value) }; +} + +function tableDeltaReader( + open: () => Promise, +): TableDeltaReader { + return new TableDeltaReaderImpl(open); +} + +class TableDeltaReaderImpl implements TableDeltaReader { + readonly #open: () => Promise; + #setup?: Promise; + #schema?: Schema; + #schemaSetup?: Promise; + #iterator?: AsyncIterator; + #error?: unknown; + #done = false; + #pullQueue: Promise = Promise.resolve(); + + constructor(open: () => Promise) { + this.#open = open; + } + + [Symbol.asyncIterator](): AsyncIterator { + return this; + } + + async schema(): Promise { + if (this.#schema !== undefined) { + return this.#schema; + } + if (this.#error !== undefined) { + throw this.#error; + } + if (this.#schemaSetup === undefined) { + this.#schemaSetup = this.#loadSchema(); + } + return this.#schemaSetup; + } + + async #loadSchema(): Promise { + try { + const native = await this.#getNative(); + const schema = tableFromIPC(await native.schema()).schema; + this.#schema = schema; + return schema; + } catch (error) { + return this.#fail(error); + } + } + + next(): Promise> { + return this.#serialize(() => this.#pull()); + } + + async return(): Promise> { + await this.#serialize(async () => { + this.#done = true; + await this.#release(); + }); + return { done: true, value: undefined }; + } + + async throw(error?: unknown): Promise> { + await this.#serialize(async () => { + this.#done = true; + await this.#release(); + }); + throw error; + } + + async #pull(): Promise> { + if (this.#error !== undefined) { + throw this.#error; + } + if (this.#done) { + return { done: true, value: undefined }; + } + + // Capture the schema before polling the reader's shared native iterator. + await this.schema(); + try { + const result = await this.#getIterator().next(); + if (result.done) { + this.#done = true; + await this.#release(); + } + return result; + } catch (error) { + return this.#fail(error); + } + } + + #getIterator(): AsyncIterator { + if (this.#iterator === undefined) { + this.#iterator = RecordBatchIterator(this.#getNative())[ + Symbol.asyncIterator + ](); + } + return this.#iterator; + } + + async #getNative(): Promise { + if (this.#error !== undefined) { + throw this.#error; + } + if (this.#done) { + throw new Error("table delta reader is already consumed"); + } + if (this.#setup === undefined) { + try { + this.#setup = this.#open(); + } catch (error) { + return this.#fail(error); + } + } + try { + return await this.#setup; + } catch (error) { + return this.#fail(error); + } + } + + async #fail(error: unknown): Promise { + if (this.#error === undefined) { + this.#done = true; + this.#error = error; + await this.#release(); + } + throw this.#error; + } + + async #release(): Promise { + const iterator = this.#iterator; + this.#iterator = undefined; + this.#setup = undefined; + if (iterator?.return !== undefined) { + try { + await iterator.return(); + } catch { + // The native stream already failed or completed; releasing the + // reference is enough. + } + } + } + + #serialize(operation: () => Promise): Promise { + const next = this.#pullQueue.then(operation, operation); + this.#pullQueue = next.then( + () => undefined, + () => undefined, + ); + return next; + } +} + /** * Branch manager for a {@link Table}. * diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 3075a7696..728240cf8 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -2,17 +2,18 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use std::collections::HashMap; +use std::sync::Arc; use chrono::{DateTime, Utc}; use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema}; use lancedb::table::{ - AddDataMode, ColumnAlteration as LanceColumnAlteration, + AddDataMode, ColumnAlteration as LanceColumnAlteration, DeltaRef as LanceDbDeltaRef, FieldMetadataUpdate as LanceFieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig as LanceFunctionRefreshPlanningConfig, FunctionRefreshPodResources as LanceFunctionRefreshPodResources, FunctionWorkerResourceBudget as LanceFunctionWorkerResourceBudget, NewColumnTransform, Ref, - Table as LanceDbTable, + Table as LanceDbTable, TableDelta as LanceDbTableDelta, }; use napi::Env; use napi::bindgen_prelude::*; @@ -22,6 +23,7 @@ use napi_derive::napi; use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable}; use crate::error::{NapiErrorExt, convert_error}; use crate::index::Index; +use crate::iterator::RecordBatchIterator; use crate::job::JobFailureInfo; use crate::merge::NativeMergeInsertBuilder; use crate::query::{Query, TakeQuery, VectorQuery}; @@ -126,6 +128,57 @@ impl CompactionOptions { } } +/// One endpoint of a table delta: a positive version or a same-branch tag. +#[napi(object)] +pub struct DeltaRef { + /// A persisted version, expressed as a positive lossless u64 bigint. + pub version: Option, + /// A tag on the table handle's current branch. + pub tag: Option, +} + +impl DeltaRef { + fn into_delta_ref(self) -> napi::Result { + match (self.version, self.tag) { + (Some(version), None) => { + let (negative, value, lossless) = version.get_u64(); + if negative || !lossless { + return Err(napi::Error::from_reason( + "delta version must be a positive lossless u64 bigint", + )); + } + if value == 0 { + return Err(napi::Error::from_reason( + "delta version must be greater than zero", + )); + } + Ok(LanceDbDeltaRef::Version(value)) + } + (None, Some(tag)) => { + if tag.is_empty() { + return Err(napi::Error::from_reason( + "delta tag must be a non-empty string", + )); + } + Ok(LanceDbDeltaRef::Tag(tag)) + } + _ => Err(napi::Error::from_reason( + "delta reference must contain exactly one of version or tag", + )), + } + } +} + +/// A committed transaction in a table delta range. +#[napi(object)] +pub struct TableDeltaTransaction { + pub read_version: BigInt, + pub uuid: String, + pub operation: String, + pub tag: Option, + pub transaction_properties: Option>, +} + #[napi] pub struct Table { // We keep a duplicate of the table name so we can use it for error @@ -955,6 +1008,19 @@ impl Table { self.inner_ref()?.checkout_latest().await.default_error() } + /// Compare two persisted versions or same-branch tags. + #[napi(catch_unwind)] + pub async fn delta( + &self, + from_version: DeltaRef, + to_version: Option, + ) -> napi::Result { + let from = from_version.into_delta_ref()?; + let to = to_version.map(DeltaRef::into_delta_ref).transpose()?; + let delta = self.inner_ref()?.delta(from, to).await.default_error()?; + Ok(TableDelta::new(delta)) + } + #[napi(catch_unwind)] pub async fn list_versions(&self) -> napi::Result> { self.inner_ref()? @@ -2434,6 +2500,75 @@ fn from_tag_hint(name: &str, tag: &str) -> String { ) } +/// A pinned version range with streaming row changes. +#[napi] +pub struct TableDelta { + inner: Arc, +} + +impl TableDelta { + fn new(inner: LanceDbTableDelta) -> Self { + Self { + inner: Arc::new(inner), + } + } +} + +#[napi] +impl TableDelta { + #[napi] + pub fn begin_version(&self) -> BigInt { + BigInt::from(self.inner.begin_version()) + } + + #[napi] + pub fn end_version(&self) -> BigInt { + BigInt::from(self.inner.end_version()) + } + + #[napi(catch_unwind)] + pub async fn inserted_rows(&self) -> napi::Result { + let stream = self.inner.inserted_rows().await.default_error()?; + Ok(RecordBatchIterator::new(stream.into())) + } + + #[napi(catch_unwind)] + pub async fn updated_rows(&self) -> napi::Result { + let stream = self.inner.updated_rows().await.default_error()?; + Ok(RecordBatchIterator::new(stream.into())) + } + + #[napi(catch_unwind)] + pub async fn upserted_rows(&self) -> napi::Result { + let stream = self.inner.upserted_rows().await.default_error()?; + Ok(RecordBatchIterator::new(stream.into())) + } + + #[napi(catch_unwind)] + pub async fn deleted_row_ids(&self) -> napi::Result { + let stream = self.inner.deleted_row_ids().await.default_error()?; + Ok(RecordBatchIterator::new(stream.into())) + } + + #[napi(catch_unwind)] + pub async fn list_transactions(&self) -> napi::Result> { + let transactions = self.inner.list_transactions().await.default_error()?; + Ok(transactions + .into_iter() + .map(|transaction| TableDeltaTransaction { + read_version: BigInt::from(transaction.read_version), + uuid: transaction.uuid, + operation: transaction.operation.name().to_string(), + tag: transaction.tag, + transaction_properties: transaction + .transaction_properties + .as_ref() + .map(|properties| (**properties).clone()), + }) + .collect()) + } +} + /// Tags label table versions with human-readable names. #[napi] pub struct Tags { From 49dedd4329cb6acac39038a99b20e335837cf602 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sat, 21 Nov 2026 00:18:29 -0800 Subject: [PATCH 67/78] fix: expose Function metadata in SDK job listings (#5096) Expose affected columns, pinned Function name/version, completion time, duration and failure summaries on `JobInfo` in the Rust, Python and TypeScript SDKs. Values come from the listing response, so callers can inspect recent computed column refreshes without opening every job. Older servers keep optional values absent; measured zero durations stay zero. ```python latest = next((info for info in db.list_jobs(table="events", job_type="function_refresh") if "embedding" in info.columns), None) if latest is not None: print(latest.function_name, latest.function_version, latest.duration_millis) if latest.failure is not None: print(latest.failure.message) ``` Duration is creation-to-completion wall time, including queueing and pauses. Adds listing response coverage across SDKs and documents the metadata contract, including SQL `SHOW JOBS EXTENDED` for the expanded listing. Plain `SHOW JOBS` preserves its original columns. Local builds and tests were skipped as requested. The dependency advisory check also fails on current main because `libsais-rs 0.2.0` is yanked ([main job](https://github.com/lancedb/lancedb/actions/runs/44470513618/job/135378545456)); this PR does not change dependencies. This changes the public shape of Rust and TypeScript `JobInfo`: callers constructing summaries must supply the added fields (including TypeScript `columns`). TypeScript table filtering remains a separate concern; the guide now shows its client-side selection and namespace limitation alongside Python and Rust server-side filters. Refs ENT-3903. --- docs/src/js/interfaces/JobInfo.md | 60 +++++++++++++++++++ docs/web/basics/jobs.mdx | 84 +++++++++++++++++++++++++++ docs/web/sql/ddl/job.mdx | 17 ++++++ nodejs/__test__/remote.test.ts | 32 +++++++++- nodejs/src/job.rs | 18 ++++++ python/python/lancedb/_lancedb.pyi | 12 ++++ python/python/tests/test_remote_db.py | 43 +++++++++++++- python/src/job.rs | 18 ++++++ rust/lancedb/src/database.rs | 14 +++++ rust/lancedb/src/remote/db.rs | 35 ++++++++++- 10 files changed, 327 insertions(+), 6 deletions(-) diff --git a/docs/src/js/interfaces/JobInfo.md b/docs/src/js/interfaces/JobInfo.md index 5de1d5e55..510fd7f28 100644 --- a/docs/src/js/interfaces/JobInfo.md +++ b/docs/src/js/interfaces/JobInfo.md @@ -10,6 +10,26 @@ A row from `Connection.listJobs`: one server-side job. ## Properties +### columns + +```ts +columns: string[]; +``` + +Affected columns; empty when unavailable or not column-scoped. + +*** + +### completedAtMillis? + +```ts +optional completedAtMillis: number; +``` + +Terminal timestamp in milliseconds since the epoch, when known. + +*** + ### createdAtMillis ```ts @@ -20,6 +40,46 @@ When the job was created, in milliseconds since the epoch. *** +### durationMillis? + +```ts +optional durationMillis: number; +``` + +Creation-to-completion wall time, including queueing and pauses. + +*** + +### failure? + +```ts +optional failure: JobFailureInfo; +``` + +Durable failure summary, when available. + +*** + +### functionName? + +```ts +optional functionName: string; +``` + +Pinned Function catalog name, with namespace segments joined by `$`. + +*** + +### functionVersion? + +```ts +optional functionVersion: string; +``` + +Pinned Function version, when known. + +*** + ### jobId ```ts diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 69801dc10..890c5d504 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -243,6 +243,90 @@ listing. It is a lazy iterator: iteration performs requests and can raise request errors. Use `list(db.list_jobs(...))` to collect all remaining results; there is no `.to_list()` method. +{/* Draft for the SDK and Enterprise releases that provide job listing metadata. + +With a server and SDK that provide listing metadata, `JobInfo` also exposes +`columns`, `function_name`, `function_version`, `completed_at_millis`, +`duration_millis`, and `failure`. Function names include their namespace, joined +by `$`, and the version is pinned to the computed column refresh. Duration is +creation-to-completion wall time, including queueing and pauses; running jobs +have no completed duration. Unknown scalar values and failure summaries stay +absent (`None` in Python/Rust, `undefined` in TypeScript), and unavailable or +non-column-scoped `columns` are empty. A zero duration is a measured value. +Failure summaries include phase, message, and retryability; open the job for +full diagnostics. + + +```python Python icon="python" +latest = next( + ( + info + for info in db.list_jobs(table="events", job_type="function_refresh") + if "embedding" in info.columns + ), + None, +) +if latest is not None: + print(latest.function_name, latest.function_version, latest.duration_millis) + if latest.failure is not None: + print(latest.failure.message) +``` + +```rust Rust icon="rust" +use futures::TryStreamExt; +use lancedb::{database::JobListFilter, listing::ListingOptions, Connection, Result}; + +async fn print_latest_refresh(db: &Connection) -> Result<()> { + let mut filter = JobListFilter::default(); + filter.table = Some("events".into()); + filter.job_types = vec!["function_refresh".into()]; + let mut jobs = db.list_jobs_filtered(filter, ListingOptions::default()); + while let Some(info) = jobs.try_next().await? { + if info.columns.iter().any(|column| column == "embedding") { + println!( + "{:?} {:?} {:?}", + info.function_name, info.function_version, info.duration_millis + ); + if let Some(failure) = info.failure { + println!("{:?}", failure.message); + } + break; + } + } + Ok(()) +} +``` + +```typescript TypeScript icon="js" +for await (const info of db.listJobs({ pageLimit: 50 })) { + if ( + info.jobType === "function_refresh" && + info.table === "events" && + info.columns.includes("embedding") + ) { + console.log(info.functionName, info.functionVersion, info.durationMillis); + if (info.failure !== undefined) { + console.log(info.failure.message); + } + break; + } +} +``` + + +Python and Rust support server-side table filtering. TypeScript `listJobs` +currently accepts only pagination options, so its example filters rows on the +client and may read more pages. The displayed table name has no namespace; +use a table name unique within the listed database for this TypeScript example. +Use Python, Rust, or SQL for an exact namespaced table listing. + +SQL `SHOW JOBS EXTENDED` and `SHOW JOBS EXTENDED FOR TABLE events` expose the +same metadata. Plain `SHOW JOBS` keeps its existing result columns. +The extended result returns `columns` as a list and `failure` as nullable JSON +text. + +*/} + Job filters and synchronous `Listing` indexing, slicing, and `len()` require a Python SDK release that includes these APIs. Older SDKs expose only diff --git a/docs/web/sql/ddl/job.mdx b/docs/web/sql/ddl/job.mdx index 8b507e6bc..914d2944b 100644 --- a/docs/web/sql/ddl/job.mdx +++ b/docs/web/sql/ddl/job.mdx @@ -34,6 +34,23 @@ values remain NULL. Children are read-only diagnostic identities. following backend continuation pages up to that limit. Child history can be `available`, `not_yet_recorded`, or `unavailable` after archival. +{/* Draft for the Enterprise release that provides extended job listing metadata. + +```sql +SHOW JOBS EXTENDED; +SHOW JOBS EXTENDED FOR TABLE documents; +``` + +`EXTENDED` adds `completed_at_millis`, `duration_millis`, `columns`, +`function_name`, `function_version`, and `failure` to database and table +listings. Plain `SHOW JOBS` keeps its existing result columns. `columns` is a +list, Function identity is pinned to the computed column refresh, and +`failure` is nullable JSON text with phase, message, and retryability. Duration +is creation-to-completion wall time, including queueing and pauses; it is +NULL when unfinished or unavailable. `EXTENDED` does not apply to `FOR JOB`. + +*/} + A job you completed weeks ago eventually stops appearing here -- it was archived, not deleted. Two deployment-scheduled jobs sweep the registry on a diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 602239544..14b581a2c 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -2287,7 +2287,13 @@ describe("remote connection jobs surface", () => { .end( '{"jobs": [{"job_id": "job-2", "table": "t2", ' + '"job_type": "create_index", "state": "succeeded", ' + - '"created_at_millis": 2000}]}', + '"created_at_millis": 2000, "completed_at_millis": 2000, ' + + '"duration_millis": 0, "columns": ["embedding"], ' + + '"function_name": "features$embed", "function_version": "7"}, ' + + '{"job_id": "job-3", "table": "t2", "job_type": "function_refresh", ' + + '"state": "failed", "created_at_millis": 3000, "duration_millis": 200, ' + + '"completed_at_millis": 3200, "failure": {"phase": "execute", ' + + '"message": "worker failed", "retryable": false}}]}', ); } } else if (req.url === "/v1/jobs/describe") { @@ -2356,9 +2362,31 @@ describe("remote connection jobs surface", () => { }, async (db) => { const jobs = await collect(db.listJobs()); - expect(jobs.map((job) => job.jobId)).toEqual(["job-1", "job-2"]); + expect(jobs.map((job) => job.jobId)).toEqual([ + "job-1", + "job-2", + "job-3", + ]); expect(jobs[0].state).toEqual("running"); expect(jobs[1].state).toEqual("finished"); + expect(jobs[0].completedAtMillis).toBeUndefined(); + expect(jobs[0].durationMillis).toBeUndefined(); + expect(jobs[0].columns).toEqual([]); + expect(jobs[0].functionName).toBeUndefined(); + expect(jobs[0].functionVersion).toBeUndefined(); + expect(jobs[0].failure).toBeUndefined(); + expect(jobs[1].completedAtMillis).toBe(2000); + expect(jobs[1].durationMillis).toBe(0); + expect(jobs[1].columns).toEqual(["embedding"]); + expect(jobs[1].functionName).toBe("features$embed"); + expect(jobs[1].functionVersion).toBe("7"); + expect(jobs[1].failure).toBeUndefined(); + expect(jobs[2].state).toBe("failed"); + expect(jobs[2].durationMillis).toBe(200); + expect(jobs[2].failure?.phase).toBe("execute"); + expect(jobs[2].failure?.message).toBe("worker failed"); + expect(jobs[2].failure?.retryable).toBe(false); + expect(jobs[2].failure?.traceback).toBeUndefined(); expect(jobs[0].progress).toEqual({ // biome-ignore lint/style/useNamingConvention: server wire format job_type: "create_index", diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index cd7c6a469..211420ce9 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -288,6 +288,18 @@ pub struct JobInfo { pub state: String, /// When the job was created, in milliseconds since the epoch. pub created_at_millis: i64, + /// Terminal timestamp in milliseconds since the epoch, when known. + pub completed_at_millis: Option, + /// Creation-to-completion wall time, including queueing and pauses. + pub duration_millis: Option, + /// Affected columns; empty when unavailable or not column-scoped. + pub columns: Vec, + /// Pinned Function catalog name, with namespace segments joined by `$`. + pub function_name: Option, + /// Pinned Function version, when known. + pub function_version: Option, + /// Durable failure summary, when available. + pub failure: Option, /// Structured lifecycle, queue, pause, and job-type-specific progress. #[napi(ts_type = "Record")] pub progress: serde_json::Value, @@ -304,6 +316,12 @@ impl From for JobInfo { job_type: info.job_type, state: info.state, created_at_millis: info.created_at_millis, + completed_at_millis: info.completed_at_millis, + duration_millis: info.duration_millis, + columns: info.columns, + function_name: info.function_name, + function_version: info.function_version, + failure: info.failure.map(Into::into), progress, paused: info.paused, } diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a930728d7..5fdeb56b2 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -492,6 +492,18 @@ class JobInfo: @property def created_at_millis(self) -> int: ... @property + def completed_at_millis(self) -> Optional[int]: ... + @property + def duration_millis(self) -> Optional[int]: ... + @property + def columns(self) -> list[str]: ... + @property + def function_name(self) -> Optional[str]: ... + @property + def function_version(self) -> Optional[str]: ... + @property + def failure(self) -> Optional[JobFailureInfo]: ... + @property def progress(self) -> Optional[dict[str, Any]]: ... @property def paused(self) -> bool: ... diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 4e531262d..162522a83 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -6984,10 +6984,29 @@ def test_remote_connection_jobs_surface(): dict( job_id="job-2", table="t2", - job_type="create_index", + job_type="function_refresh", state="succeeded", created_at_millis=2000, - ) + completed_at_millis=2000, + duration_millis=0, + columns=["embedding"], + function_name="features$embed", + function_version="7", + ), + dict( + job_id="job-3", + table="t2", + job_type="function_refresh", + state="failed", + created_at_millis=3000, + completed_at_millis=3200, + duration_millis=200, + failure=dict( + phase="execute", + message="worker failed", + retryable=False, + ), + ), ] ) request.send_response(200) @@ -7085,7 +7104,7 @@ def test_remote_connection_jobs_surface(): with mock_lancedb_connection(handler) as db: jobs = list(db.list_jobs()) - assert [job.job_id for job in jobs] == ["job-1", "job-2"] + assert [job.job_id for job in jobs] == ["job-1", "job-2", "job-3"] assert jobs[0].state == "running" assert jobs[0].table == "t1" assert jobs[0].progress == { @@ -7099,6 +7118,24 @@ def test_remote_connection_jobs_surface(): } assert jobs[0].paused is True assert jobs[1].state == "finished" + assert jobs[0].completed_at_millis is None + assert jobs[0].duration_millis is None + assert jobs[0].columns == [] + assert jobs[0].function_name is None + assert jobs[0].function_version is None + assert jobs[0].failure is None + assert jobs[1].completed_at_millis == 2000 + assert jobs[1].duration_millis == 0 + assert jobs[1].columns == ["embedding"] + assert jobs[1].function_name == "features$embed" + assert jobs[1].function_version == "7" + assert jobs[1].failure is None + assert jobs[2].state == "failed" + assert jobs[2].duration_millis == 200 + assert jobs[2].failure.phase == "execute" + assert jobs[2].failure.message == "worker failed" + assert jobs[2].failure.retryable is False + assert jobs[2].failure.traceback is None assert db.cancel_job("job-1") is True assert db.cancel_job("missing") is False diff --git a/python/src/job.rs b/python/src/job.rs index fdaa67ba6..54c22a8e1 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -254,6 +254,18 @@ pub struct JobInfo { job_type: String, state: String, created_at_millis: i64, + /// Terminal timestamp in milliseconds since the epoch, when known. + completed_at_millis: Option, + /// Creation-to-completion wall time, including queueing and pauses. + duration_millis: Option, + /// Affected columns; empty when unavailable or not column-scoped. + columns: Vec, + /// Pinned Function catalog name, with namespace segments joined by `$`. + function_name: Option, + /// Pinned Function version, when known. + function_version: Option, + /// Durable failure summary, when available. + failure: Option, _progress_json: Option, paused: bool, } @@ -290,6 +302,12 @@ impl From for JobInfo { job_type: info.job_type, state: info.state, created_at_millis: info.created_at_millis, + completed_at_millis: info.completed_at_millis, + duration_millis: info.duration_millis, + columns: info.columns, + function_name: info.function_name, + function_version: info.function_version, + failure: info.failure.map(Into::into), _progress_json: Some(progress), paused: info.paused, } diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index d53383ce5..b89c9f95e 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -291,6 +291,20 @@ pub struct JobInfo { pub state: String, /// When the job was created, in milliseconds since the epoch. pub created_at_millis: i64, + /// Terminal timestamp, in milliseconds since the epoch; unknown on older servers. + pub completed_at_millis: Option, + /// Creation-to-completion wall time, including queueing and pauses. + /// Absent for unfinished jobs or when the server cannot establish the duration. + pub duration_millis: Option, + /// Columns affected by this job. Empty when unavailable or not column-scoped. + pub columns: Vec, + /// Pinned Function catalog name, with namespace segments joined by `$`. + /// Present for computed column refreshes when supplied by the server. + pub function_name: Option, + /// Pinned Function version, when supplied by the server. + pub function_version: Option, + /// Durable failure summary; absent when unavailable or the job did not fail. + pub failure: Option, /// Latest progress sample for a job type that reports structured progress. pub progress: Option, /// Coarse server-derived phase, including phases introduced by newer diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index def3c85fd..2e91fc15d 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -742,6 +742,18 @@ struct RemoteListJobRow { #[serde(default)] created_at_millis: i64, #[serde(default)] + completed_at_millis: Option, + #[serde(default)] + duration_millis: Option, + #[serde(default)] + columns: Vec, + #[serde(default)] + function_name: Option, + #[serde(default)] + function_version: Option, + #[serde(default)] + failure: Option, + #[serde(default)] progress: Option, #[serde(default)] phase: Option, @@ -1371,6 +1383,12 @@ impl Database for RemoteDatabase { job_type: row.job_type, state: job_state_to_client(&row.state), created_at_millis: row.created_at_millis, + completed_at_millis: row.completed_at_millis, + duration_millis: row.duration_millis, + columns: row.columns, + function_name: row.function_name, + function_version: row.function_version, + failure: row.failure, progress: row.progress, phase: row.phase, paused: row.paused, @@ -4628,7 +4646,7 @@ mod tests { http::Response::builder() .status(200) .body( - r#"{"jobs": [{"job_id": "job-2", "table": "t2", "job_type": "create_index", "state": "succeeded", "created_at_millis": 2000}, {"job_id": "job-3", "table": "t3", "job_type": "create_index", "state": "timed_out", "created_at_millis": 3000}]}"#, + r#"{"jobs": [{"job_id": "job-2", "table": "t2", "job_type": "create_index", "state": "succeeded", "created_at_millis": 2000}, {"job_id": "job-3", "table": "t3", "job_type": "create_index", "state": "timed_out", "created_at_millis": 3000, "completed_at_millis": 3000, "duration_millis": 0, "columns": ["embedding"], "function_name": "features$embed", "function_version": "7", "failure": {"phase": "execute", "message": "worker failed", "retryable": false}}]}"#, ) .unwrap() } @@ -4646,11 +4664,26 @@ mod tests { assert_eq!(jobs[0].progress.as_ref().unwrap()["rows_computed"], 4); assert_eq!(jobs[0].phase.as_deref(), Some("running")); assert!(jobs[0].paused); + assert_eq!(jobs[0].completed_at_millis, None); + assert_eq!(jobs[0].duration_millis, None); + assert!(jobs[0].columns.is_empty()); + assert_eq!(jobs[0].function_name, None); + assert_eq!(jobs[0].function_version, None); + assert_eq!(jobs[0].failure, None); assert_eq!(jobs[1].job_id, "job-2"); assert_eq!(jobs[1].state, "finished"); assert_eq!(jobs[1].created_at_millis, 2000); assert_eq!(jobs[2].job_id, "job-3"); assert_eq!(jobs[2].state, "failed"); + assert_eq!(jobs[2].completed_at_millis, Some(3000)); + assert_eq!(jobs[2].duration_millis, Some(0)); + assert_eq!(jobs[2].columns, ["embedding"]); + assert_eq!(jobs[2].function_name.as_deref(), Some("features$embed")); + assert_eq!(jobs[2].function_version.as_deref(), Some("7")); + let failure = jobs[2].failure.as_ref().unwrap(); + assert_eq!(failure.message.as_deref(), Some("worker failed")); + assert_eq!(failure.retryable, Some(false)); + assert_eq!(failure.traceback, None); } #[tokio::test] From 0511aed6e9cf731a7730f4d5c74fbcf13f1f84a2 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sat, 21 Nov 2026 00:51:08 -0800 Subject: [PATCH 68/78] feat: profile Enterprise Function workers from official clients --- docs/src/js/classes/Job.md | 125 +++++ docs/src/js/globals.md | 5 + docs/src/js/interfaces/FunctionProfile.md | 126 +++++ .../js/interfaces/FunctionProfileOptions.md | 39 ++ .../interfaces/FunctionProfileWaitOptions.md | 29 ++ .../js/type-aliases/FunctionProfileKind.md | 13 + .../js/type-aliases/FunctionProfileStatus.md | 13 + docs/src/python/python.md | 6 + docs/web/basics/jobs.mdx | 112 +++++ nodejs/__test__/profiling.test.ts | 334 ++++++++++++ nodejs/lancedb/index.ts | 7 + nodejs/lancedb/job.ts | 97 ++++ nodejs/lancedb/profiling.ts | 88 ++++ nodejs/src/job.rs | 96 +++- python/python/lancedb/_lancedb.pyi | 17 + python/python/lancedb/job.py | 215 ++++++++ python/python/lancedb/profiling.py | 49 ++ python/python/tests/test_job.py | 63 +++ python/python/tests/test_remote_db.py | 139 +++++ python/src/job.rs | 86 +++- rust/lancedb/src/job.rs | 195 +++++++ rust/lancedb/src/job/profile.rs | 223 ++++++++ rust/lancedb/src/remote/job.rs | 23 +- rust/lancedb/src/remote/job/profile.rs | 476 ++++++++++++++++++ rust/lancedb/src/remote/table.rs | 36 +- .../lancedb/src/remote/table/profile_tests.rs | 86 ++++ 26 files changed, 2692 insertions(+), 6 deletions(-) create mode 100644 docs/src/js/interfaces/FunctionProfile.md create mode 100644 docs/src/js/interfaces/FunctionProfileOptions.md create mode 100644 docs/src/js/interfaces/FunctionProfileWaitOptions.md create mode 100644 docs/src/js/type-aliases/FunctionProfileKind.md create mode 100644 docs/src/js/type-aliases/FunctionProfileStatus.md create mode 100644 nodejs/__test__/profiling.test.ts create mode 100644 nodejs/lancedb/profiling.ts create mode 100644 python/python/lancedb/profiling.py create mode 100644 rust/lancedb/src/job/profile.rs create mode 100644 rust/lancedb/src/remote/job/profile.rs create mode 100644 rust/lancedb/src/remote/table/profile_tests.rs diff --git a/docs/src/js/classes/Job.md b/docs/src/js/classes/Job.md index 01f4a1f50..6d30996d2 100644 --- a/docs/src/js/classes/Job.md +++ b/docs/src/js/classes/Job.md @@ -247,6 +247,43 @@ Request cancellation. Cancelling a finished operation is a no-op. *** +### captureProfile() + +```ts +captureProfile(workerId, options): Promise +``` + +Request a profile of a running Enterprise Function worker session. +Returns the accepted identity without waiting for recording to finish. +Requires System Operate permission and server profiling support. The server +pins the worker, Python session and execution epoch. One capture per job +can be active. Captures add workload-dependent overhead. + +GPU tracing requires initialized PyTorch CUDA/CUPTI. CPU sampling requires +readable per-thread procfs and is unavailable in dedicated sandboxes. + +#### Parameters + +* **workerId**: `string` + +* **options**: [`FunctionProfileOptions`](../interfaces/FunctionProfileOptions.md) = `{}` + +#### Returns + +`Promise`<[`FunctionProfile`](../interfaces/FunctionProfile.md)> + +#### Example + +```ts +const profile = await job.captureProfile("worker-id", { + kind: "gpu", durationSeconds: 2, +}); +await job.waitForProfile(profile.profileId, { timeoutMs: 60_000 }); +await job.exportProfile(profile.profileId, "gpu.trace.json"); +``` + +*** + ### events() ```ts @@ -276,6 +313,29 @@ per fragment. `filter` is a SQL-like expression over the `state`, *** +### exportProfile() + +```ts +exportProfile(profileId, path): Promise +``` + +Write a completed capture's JSON after successful retrieval. Open CPU +exports in speedscope and GPU exports in Perfetto. GPU activity durations +can overlap and are not utilization; Python operator attribution and GPU +allocation stacks are excluded. Filesystem errors propagate to the caller. + +#### Parameters + +* **profileId**: `string` + +* **path**: `string` + +#### Returns + +`Promise`<`void`> + +*** + ### history() ```ts @@ -294,6 +354,48 @@ Walk retained history one page at a time using the server's continuation. *** +### profileArtifact() + +```ts +profileArtifact(profileId): Promise> +``` + +Retrieve a completed capture's actual JSON: speedscope for CPU, +tracemalloc for Python allocations, or Chrome Trace Event JSON for GPU. +Truncation flags are preserved. Retention is at most one hour and eight +captures per job, until earlier scratch reclamation or archival. +Permission, expired-artifact and unsupported-server errors propagate. + +#### Parameters + +* **profileId**: `string` + +#### Returns + +`Promise`<`Record`<`string`, `unknown`>> + +*** + +### profileStatus() + +```ts +profileStatus(profileId): Promise +``` + +Fetch capture identity and status, including retained lookup after refresh. +Failed captures return status "failed" with the server's error reason. +This never changes the parent job's cached state. + +#### Parameters + +* **profileId**: `string` + +#### Returns + +`Promise`<[`FunctionProfile`](../interfaces/FunctionProfile.md)> + +*** + ### progress() ```ts @@ -422,3 +524,26 @@ can also be reopened with `Connection.openJob`; query IDs cannot. ```ts const result = await job.wait({ timeoutMs: 60_000, onProgress: console.log }); ``` + +*** + +### waitForProfile() + +```ts +waitForProfile(profileId, options): Promise +``` + +Wait for a capture with a configurable timeout and polling cadence. +Defaults to 60 seconds with two seconds between requests. A timeout stops +only this wait; the capture and Function refresh continue. A failed capture +rejects with its server-reported reason. Keep its ID to wait again. + +#### Parameters + +* **profileId**: `string` + +* **options**: [`FunctionProfileWaitOptions`](../interfaces/FunctionProfileWaitOptions.md) = `{}` + +#### Returns + +`Promise`<[`FunctionProfile`](../interfaces/FunctionProfile.md)> diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 7f7518a27..9f7ed53e4 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -109,6 +109,9 @@ - [FunctionErrorRecord](interfaces/FunctionErrorRecord.md) - [FunctionErrors](interfaces/FunctionErrors.md) - [FunctionErrorsOptions](interfaces/FunctionErrorsOptions.md) +- [FunctionProfile](interfaces/FunctionProfile.md) +- [FunctionProfileOptions](interfaces/FunctionProfileOptions.md) +- [FunctionProfileWaitOptions](interfaces/FunctionProfileWaitOptions.md) - [FunctionRefreshPlanningConfig](interfaces/FunctionRefreshPlanningConfig.md) - [FunctionRefreshPodResources](interfaces/FunctionRefreshPodResources.md) - [FunctionRetryPolicy](interfaces/FunctionRetryPolicy.md) @@ -195,6 +198,8 @@ - [DeltaVersion](type-aliases/DeltaVersion.md) - [ExprLike](type-aliases/ExprLike.md) - [FieldLike](type-aliases/FieldLike.md) +- [FunctionProfileKind](type-aliases/FunctionProfileKind.md) +- [FunctionProfileStatus](type-aliases/FunctionProfileStatus.md) - [IntoSql](type-aliases/IntoSql.md) - [IntoVector](type-aliases/IntoVector.md) - [JobProgressCallback](type-aliases/JobProgressCallback.md) diff --git a/docs/src/js/interfaces/FunctionProfile.md b/docs/src/js/interfaces/FunctionProfile.md new file mode 100644 index 000000000..f33f33e49 --- /dev/null +++ b/docs/src/js/interfaces/FunctionProfile.md @@ -0,0 +1,126 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionProfile + +# Interface: FunctionProfile + +A capture identity and status snapshot. Keep profileId for retained lookup +after the Function refresh completes. Timestamp fields are epoch milliseconds. + +## Properties + +### artifactId + +```ts +readonly artifactId: null | string; +``` + +*** + +### completedAtMillis + +```ts +readonly completedAtMillis: null | number; +``` + +*** + +### deadlineAtMillis + +```ts +readonly deadlineAtMillis: number; +``` + +*** + +### durationSeconds + +```ts +readonly durationSeconds: number; +``` + +*** + +### error + +```ts +readonly error: null | string; +``` + +The server's capture failure reason; this is not a refresh job failure. + +*** + +### executionEpoch + +```ts +readonly executionEpoch: number; +``` + +*** + +### expiresAtMillis + +```ts +readonly expiresAtMillis: number; +``` + +Upper retention bound; job scratch reclamation can remove artifacts sooner. + +*** + +### jobId + +```ts +readonly jobId: string; +``` + +*** + +### kind + +```ts +readonly kind: FunctionProfileKind; +``` + +*** + +### profileId + +```ts +readonly profileId: string; +``` + +*** + +### requestedAtMillis + +```ts +readonly requestedAtMillis: number; +``` + +*** + +### sessionSlot + +```ts +readonly sessionSlot: number; +``` + +*** + +### status + +```ts +readonly status: FunctionProfileStatus; +``` + +*** + +### workerId + +```ts +readonly workerId: string; +``` diff --git a/docs/src/js/interfaces/FunctionProfileOptions.md b/docs/src/js/interfaces/FunctionProfileOptions.md new file mode 100644 index 000000000..2115fd027 --- /dev/null +++ b/docs/src/js/interfaces/FunctionProfileOptions.md @@ -0,0 +1,39 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionProfileOptions + +# Interface: FunctionProfileOptions + +Options for requesting a Function worker capture. + +## Properties + +### durationSeconds? + +```ts +optional durationSeconds: number; +``` + +1–30 seconds for CPU/memory, default 10; 1–5 for GPU, default 5. + +*** + +### kind? + +```ts +optional kind: FunctionProfileKind; +``` + +CPU samples, retained Python allocations, or PyTorch CUDA activities. + +*** + +### sessionSlot? + +```ts +optional sessionSlot: number; +``` + +Python execution session within the worker; default zero. diff --git a/docs/src/js/interfaces/FunctionProfileWaitOptions.md b/docs/src/js/interfaces/FunctionProfileWaitOptions.md new file mode 100644 index 000000000..1a579a5af --- /dev/null +++ b/docs/src/js/interfaces/FunctionProfileWaitOptions.md @@ -0,0 +1,29 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionProfileWaitOptions + +# Interface: FunctionProfileWaitOptions + +Client-side controls while waiting for a Function worker capture. + +## Properties + +### pollIntervalMs? + +```ts +optional pollIntervalMs: number; +``` + +Delay between status requests; defaults to 2,000 ms and must be positive. + +*** + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Maximum wait including HTTP requests and sleeps; defaults to 60,000 ms. diff --git a/docs/src/js/type-aliases/FunctionProfileKind.md b/docs/src/js/type-aliases/FunctionProfileKind.md new file mode 100644 index 000000000..e7fe3bf59 --- /dev/null +++ b/docs/src/js/type-aliases/FunctionProfileKind.md @@ -0,0 +1,13 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionProfileKind + +# Type Alias: FunctionProfileKind + +```ts +type FunctionProfileKind: "cpu" | "gpu" | "memory"; +``` + +Evidence collected from one Function worker's Python execution session. diff --git a/docs/src/js/type-aliases/FunctionProfileStatus.md b/docs/src/js/type-aliases/FunctionProfileStatus.md new file mode 100644 index 000000000..5a1304aa5 --- /dev/null +++ b/docs/src/js/type-aliases/FunctionProfileStatus.md @@ -0,0 +1,13 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionProfileStatus + +# Type Alias: FunctionProfileStatus + +```ts +type FunctionProfileStatus: "pending" | "capturing" | "complete" | "failed"; +``` + +A capture's lifecycle, independent of its parent refresh job. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index fdcb0d483..32afe3d77 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -755,6 +755,12 @@ with BlobReader(read_range, len(payload)) as reader: ::: lancedb.job.JobFailureInfo +::: lancedb.profiling.FunctionProfile + +::: lancedb.profiling.FunctionProfileKind + +::: lancedb.profiling.FunctionProfileStatus + ::: lancedb.sql.Query ::: lancedb.sql.AsyncQuery diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 890c5d504..cdff84339 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -691,6 +691,118 @@ support stack inspection. For a worker that already timed out, inspect the recorded failure events for retained traceback evidence. */} +## Profile a Function worker {#profiling} + +On a supporting Enterprise server, request a CPU profile, retained Python +allocation profile, or PyTorch CUDA activity trace through the existing Job +handle. A capture is a diagnostic operation on that refresh job. It records +one selected worker's Python execution session and pins its execution epoch. +Choose a worker ID from the job's recorded events or the Console. + + +```python Synchronous Python icon="python" +from datetime import timedelta + +job = db.open_job(refresh_job_id) +profile = job.capture_profile( + worker_id, + kind="cpu", + duration=timedelta(seconds=10), + session_slot=0, +) +print(profile.profile_id, profile.status) +job.wait_for_profile( + profile.profile_id, + timeout=timedelta(seconds=60), + poll_interval=timedelta(seconds=5), +) +job.export_profile(profile.profile_id, "cpu.speedscope.json") +``` + +```python Asynchronous Python icon="python" +from datetime import timedelta + +job = await async_db.open_job(refresh_job_id) +profile = await job.capture_profile( + worker_id, kind="gpu", duration=timedelta(seconds=2) +) +await job.wait_for_profile(profile.profile_id, timeout=timedelta(seconds=60)) +await job.export_profile(profile.profile_id, "gpu.trace.json") +``` + +```typescript TypeScript icon="js" +const job = await db.openJob(refreshJobId); +const profile = await job.captureProfile(workerId, { + kind: "gpu", + durationSeconds: 2, + sessionSlot: 0, +}); +console.log(profile.profileId, profile.status); +await job.waitForProfile(profile.profileId, { + timeoutMs: 60_000, + pollIntervalMs: 5_000, +}); +await job.exportProfile(profile.profileId, "gpu.trace.json"); +``` + +```rust Rust icon="rust" +use std::time::Duration; +use lancedb::job::{ + FunctionProfileKind, FunctionProfileOptions, FunctionProfileWaitOptions, +}; + +let job = db.open_job(refresh_job_id).await?; +let profile = job.capture_profile( + worker_id, + FunctionProfileOptions::new(FunctionProfileKind::Cpu) + .duration(Duration::from_secs(10)), +).await?; +job.wait_for_profile( + &profile.profile_id, + FunctionProfileWaitOptions::new() + .timeout(Duration::from_secs(60)) + .poll_interval(Duration::from_secs(5)), +).await?; +let artifact = job.profile_artifact(&profile.profile_id).await?; +std::fs::write("cpu.speedscope.json", serde_json::to_vec(&artifact)?)?; +``` + + +| Kind | Evidence and export | Recording window | +| --- | --- | --- | +| `cpu` | Python stack samples weighted by thread CPU time; speedscope JSON | 1–30 seconds, default 10 | +| `memory` | Python allocations made during capture and retained at its end; tracemalloc JSON | 1–30 seconds, default 10 | +| `gpu` | PyTorch CUDA kernels, copies, memset and available CUDA host APIs; Chrome Trace Event JSON | 1–5 seconds, default 5 | + +Captures require System Operate permission and a running Function refresh with +an available worker session. Slot zero selects the first Python session. +Only one capture per job can be active. The capture window excludes supervisor +dispatch delay. CPU sampling needs readable per-thread procfs and is unavailable +in dedicated sandboxes. GPU tracing needs already initialized PyTorch CUDA with +CUPTI support. Captures add workload-dependent time and memory overhead. + +`wait_for_profile` / `waitForProfile` defaults to a 60-second timeout and two +seconds between status requests. Both are configurable. A timeout stops only +that client's wait; the capture and parent refresh keep running. Keep the +profile ID to wait again. A failed capture raises an error with the server's +reason. Use `profile_status` / `profileStatus` to inspect its typed status and +failure details independently of the refresh job's status. + +Retrieve a completed capture with `profile_artifact` / `profileArtifact` to get +the actual JSON in memory, or export it to a file as above. Files are overwritten +only after retrieval succeeds. Retained lookup works after refresh completion: +reopen the parent job, then use the saved profile ID. Retention is at most one +hour and eight captures per job, until earlier scratch reclamation or archival. +Permission, unsupported-session, expired-artifact and unsupported-server errors +are surfaced by the normal client error handling. + +Open CPU exports in speedscope and GPU exports in Perfetto. Truncation flags +remain in the downloaded JSON. CUDA durations can overlap across streams, so +their sum is not elapsed time or GPU utilization. Python operator attribution, +GPU allocation stacks, native CPU frames and native allocations are outside +these capture formats. Concurrent CUDA profilers in the same Python session +are unsupported. + ## Embedded and Enterprise execution {#in-process} The following table describes LanceDB Embedded operations and registry jobs on diff --git a/nodejs/__test__/profiling.test.ts b/nodejs/__test__/profiling.test.ts new file mode 100644 index 000000000..5c4394025 --- /dev/null +++ b/nodejs/__test__/profiling.test.ts @@ -0,0 +1,334 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { type IncomingHttpHeaders, createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { type Connection, type FunctionProfileKind, connect } from "../lancedb"; + +type Response = { body: unknown; status?: number }; + +function metadata(kind: FunctionProfileKind, status: string) { + return { + ["profile_id"]: "profile-1", + ["job_id"]: "job-1", + ["worker_id"]: "worker-1", + ["execution_epoch"]: 3, + ["session_slot"]: 0, + kind, + ["duration_seconds"]: 2, + status, + ["requested_at_millis"]: 1000, + ["deadline_at_millis"]: 46000, + ["expires_at_millis"]: 3601000, + ["completed_at_millis"]: null, + error: status === "failed" ? "gpu_unavailable" : null, + ["artifact_id"]: status === "complete" ? "profile-1" : null, + }; +} + +const artifacts: Record> = { + cpu: { + $schema: "https://www.speedscope.app/file-format-schema.json", + shared: { frames: [{ name: "work" }] }, + profiles: [], + futureField: 7, + }, + memory: { + format: "lancedb.tracemalloc.v1", + allocations: [{ ["size_bytes"]: 4096 }], + truncated: false, + }, + gpu: { + format: "lancedb.cuda.v1", + traceEvents: [{ name: "compute", cat: "kernel", ph: "X", ts: 10, dur: 2 }], + truncated: true, + }, +}; + +async function withProfileServer( + handler: ( + path: string, + body: Record, + headers: IncomingHttpHeaders, + ) => Response, + run: (db: Connection) => Promise, +) { + let serverError: unknown; + const server = createServer(async (request, response) => { + try { + const chunks: Buffer[] = []; + for await (const chunk of request) chunks.push(chunk); + const bytes = Buffer.concat(chunks); + const body = bytes.length === 0 ? {} : JSON.parse(bytes.toString()); + const result = handler(request.url ?? "", body, request.headers); + response.writeHead(result.status ?? 200, { + "Content-Type": "application/json", + }); + response.end(JSON.stringify(result.body)); + } catch (error) { + serverError = error; + response.writeHead(500); + response.end("test request handler failed"); + } + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const port = (server.address() as AddressInfo).port; + try { + const db = await connect("db://dev", { + apiKey: "fake", + hostOverride: `http://127.0.0.1:${port}`, + }); + try { + await run(db); + } catch (error) { + throw serverError ?? error; + } + if (serverError) throw serverError; + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +describe("Function worker profiles", () => { + it.each( + (["cpu", "memory", "gpu"] as FunctionProfileKind[]).flatMap((kind) => + [false, true].map((submitted) => [kind, submitted] as const), + ), + )( + "captures and exports retained %s evidence (submitted handle: %s)", + async (kind, submitted) => { + let polls = 0; + let finished = false; + const paths: string[] = []; + const directory = await mkdtemp(join(tmpdir(), "lancedb-profile-")); + try { + await withProfileServer( + (path, body, headers) => { + paths.push(path); + expect(headers["x-api-key"]).toBe("fake"); + expect(headers["x-lancedb-database"]).toBe("dev"); + if (path === "/v1/table/test/describe/") + return { body: { version: 1, schema: { fields: [] } } }; + if (path === "/v1/table/test/backfill_column") { + expect(body.column).toBe("result"); + return { status: 202, body: { ["job_id"]: "job-1" } }; + } + if (path === "/v1/jobs/describe") + return { + body: { + ["job_id"]: "job-1", + ["job_type"]: "function_refresh", + ["job_state"]: finished ? "DONE" : "IN_PROGRESS", + }, + }; + if (path === "/v1/jobs/profile/capture") { + expect(body).toEqual({ + ["job_id"]: "job-1", + ["worker_id"]: "worker-1", + ["session_slot"]: 0, + kind, + ["duration_seconds"]: 2, + }); + return { status: 202, body: metadata(kind, "pending") }; + } + expect(body).toEqual({ + ["job_id"]: "job-1", + ["profile_id"]: "profile-1", + }); + if (path === "/v1/jobs/profile/status") + return { + body: metadata(kind, ++polls > 1 ? "complete" : "capturing"), + }; + expect(path).toBe("/v1/jobs/profile/artifact"); + return { body: artifacts[kind] }; + }, + async (db) => { + const job = submitted + ? await (await db.openTable("test")).refreshColumnAsync("result") + : await db.openJob("job-1"); + if (submitted) await job.refresh(); + const capture = await job.captureProfile("worker-1", { + kind, + durationSeconds: 2, + }); + expect(capture).toMatchObject({ + profileId: "profile-1", + workerId: "worker-1", + executionEpoch: 3, + sessionSlot: 0, + status: "pending", + }); + const complete = await job.waitForProfile(capture.profileId, { + timeoutMs: 2000, + pollIntervalMs: 10, + }); + expect(complete.status).toBe("complete"); + expect(job.state).toBe("running"); + finished = true; + await job.refresh(); + expect(job.state).toBe("finished"); + expect(await job.profileArtifact(capture.profileId)).toEqual( + artifacts[kind], + ); + const path = join(directory, "capture.json"); + await job.exportProfile(capture.profileId, path); + expect(JSON.parse(await readFile(path, "utf8"))).toEqual( + artifacts[kind], + ); + expect( + paths.filter((path) => path === "/v1/jobs/describe"), + ).toHaveLength(2); + expect(paths.some((path) => path.endsWith("/cancel"))).toBe(false); + }, + ); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }, + ); + + it("can resume after a wait timeout without cancelling the refresh", async () => { + let complete = false; + const paths: string[] = []; + await withProfileServer( + (path) => { + paths.push(path); + if (path === "/v1/jobs/describe") + return { + body: { + ["job_id"]: "job-1", + ["job_type"]: "function_refresh", + ["job_state"]: "IN_PROGRESS", + }, + }; + expect(path).toBe("/v1/jobs/profile/status"); + return { body: metadata("gpu", complete ? "complete" : "pending") }; + }, + async (db) => { + const job = await db.openJob("job-1"); + await expect( + job.waitForProfile("profile-1", { + timeoutMs: 50, + pollIntervalMs: 10, + }), + ).rejects.toThrow(/waiting for Function worker profile/); + expect(await job.status()).toBe("running"); + complete = true; + expect( + (await job.waitForProfile("profile-1", { timeoutMs: 2000 })).status, + ).toBe("complete"); + expect(paths.some((path) => path.endsWith("/cancel"))).toBe(false); + }, + ); + }); + + it("reports failed captures independently of the parent", async () => { + await withProfileServer( + (path) => ({ + body: + path === "/v1/jobs/describe" + ? { + ["job_id"]: "job-1", + ["job_type"]: "function_refresh", + ["job_state"]: "IN_PROGRESS", + } + : metadata("gpu", "failed"), + }), + async (db) => { + const job = await db.openJob("job-1"); + expect(await job.profileStatus("profile-1")).toMatchObject({ + status: "failed", + error: "gpu_unavailable", + }); + await expect(job.waitForProfile("profile-1")).rejects.toThrow( + "gpu_unavailable", + ); + expect(job.state).toBe("running"); + }, + ); + }); + + it("preserves permission errors and existing export files", async () => { + const directory = await mkdtemp(join(tmpdir(), "lancedb-profile-")); + const path = join(directory, "capture.json"); + await writeFile(path, "previous capture"); + try { + await withProfileServer( + (path) => { + if (path === "/v1/jobs/describe") + return { + body: { + ["job_id"]: "job-1", + ["job_type"]: "function_refresh", + ["job_state"]: "DONE", + }, + }; + if (path.endsWith("/status")) + return { body: metadata("gpu", "complete") }; + return { status: 403, body: { error: "System Operate required" } }; + }, + async (db) => { + const job = await db.openJob("job-1"); + await expect(job.exportProfile("profile-1", path)).rejects.toThrow( + "403", + ); + expect(await readFile(path, "utf8")).toBe("previous capture"); + }, + ); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + + it("rejects invalid options before submitting a capture", async () => { + await withProfileServer( + (path) => { + expect(path).toBe("/v1/jobs/describe"); + return { + body: { + ["job_id"]: "job-1", + ["job_type"]: "function_refresh", + ["job_state"]: "IN_PROGRESS", + }, + }; + }, + async (db) => { + const job = await db.openJob("job-1"); + for (const durationSeconds of [ + Number.NaN, + Number.POSITIVE_INFINITY, + -1, + 0, + 6, + ]) { + await expect( + job.captureProfile("worker-1", { kind: "gpu", durationSeconds }), + ).rejects.toThrow(/duration/); + } + for (const sessionSlot of [ + -1, + 0.5, + Number.NaN, + Number.MAX_SAFE_INTEGER + 1, + ]) { + await expect( + job.captureProfile("worker-1", { sessionSlot }), + ).rejects.toThrow("sessionSlot"); + } + await expect( + job.captureProfile("worker-1", { duration: 10 } as never), + ).rejects.toThrow("Unknown profiling option"); + await expect( + job.waitForProfile("profile-1", { timeoutMs: -1 }), + ).rejects.toThrow("timeoutMs"); + await expect( + job.waitForProfile("profile-1", { pollIntervalMs: 0 }), + ).rejects.toThrow("poll interval"); + }, + ); + }); +}); diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 516a3cd2d..67c385186 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -124,6 +124,13 @@ export type { JobState, JobWaitOptions, } from "./job"; +export type { + FunctionProfile, + FunctionProfileKind, + FunctionProfileOptions, + FunctionProfileStatus, + FunctionProfileWaitOptions, +} from "./profiling"; export { AutoQuery, diff --git a/nodejs/lancedb/job.ts b/nodejs/lancedb/job.ts index c9d9beddd..49b83477c 100644 --- a/nodejs/lancedb/job.ts +++ b/nodejs/lancedb/job.ts @@ -1,11 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +import { writeFile } from "node:fs/promises"; import { Table as ArrowTable, tableFromIPC } from "apache-arrow"; import { decodeCleanupResult } from "./cleanup"; import { decodeCompactionResult } from "./compaction"; import type { JobFailureInfo, Job as NativeJob } from "./native"; import { decodePrewarmDataResult } from "./prewarm"; +import { + type FunctionProfile, + type FunctionProfileOptions, + type FunctionProfileWaitOptions, + decodeFunctionProfile, + validateProfileOptions, +} from "./profiling"; /** Which of a job's events {@link Job.events} returns. */ export interface JobEventsOptions { @@ -394,6 +402,95 @@ export class Job { } } + /** + * Request a profile of a running Enterprise Function worker session. + * Returns the accepted identity without waiting for recording to finish. + * Requires System Operate permission and server profiling support. The server + * pins the worker, Python session and execution epoch. One capture per job + * can be active. Captures add workload-dependent overhead. + * + * GPU tracing requires initialized PyTorch CUDA/CUPTI. CPU sampling requires + * readable per-thread procfs and is unavailable in dedicated sandboxes. + * + * @example + * ```ts + * const profile = await job.captureProfile("worker-id", { + * kind: "gpu", durationSeconds: 2, + * }); + * await job.waitForProfile(profile.profileId, { timeoutMs: 60_000 }); + * await job.exportProfile(profile.profileId, "gpu.trace.json"); + * ``` + */ + async captureProfile( + workerId: string, + options: FunctionProfileOptions = {}, + ): Promise { + validateProfileOptions(options, ["kind", "durationSeconds", "sessionSlot"]); + const kind = options.kind ?? "cpu"; + if (!["cpu", "gpu", "memory"].includes(kind)) { + throw new TypeError("kind must be cpu, memory or gpu"); + } + return decodeFunctionProfile( + await this.inner.captureProfile( + workerId, + kind, + options.durationSeconds, + options.sessionSlot, + ), + ); + } + + /** + * Fetch capture identity and status, including retained lookup after refresh. + * Failed captures return status "failed" with the server's error reason. + * This never changes the parent job's cached state. + */ + async profileStatus(profileId: string): Promise { + return decodeFunctionProfile(await this.inner.profileStatus(profileId)); + } + + /** + * Wait for a capture with a configurable timeout and polling cadence. + * Defaults to 60 seconds with two seconds between requests. A timeout stops + * only this wait; the capture and Function refresh continue. A failed capture + * rejects with its server-reported reason. Keep its ID to wait again. + */ + async waitForProfile( + profileId: string, + options: FunctionProfileWaitOptions = {}, + ): Promise { + validateProfileOptions(options, ["timeoutMs", "pollIntervalMs"]); + return decodeFunctionProfile( + await this.inner.waitForProfile( + profileId, + options.timeoutMs, + options.pollIntervalMs, + ), + ); + } + + /** + * Retrieve a completed capture's actual JSON: speedscope for CPU, + * tracemalloc for Python allocations, or Chrome Trace Event JSON for GPU. + * Truncation flags are preserved. Retention is at most one hour and eight + * captures per job, until earlier scratch reclamation or archival. + * Permission, expired-artifact and unsupported-server errors propagate. + */ + async profileArtifact(profileId: string): Promise> { + return JSON.parse(await this.inner.profileArtifact(profileId)); + } + + /** + * Write a completed capture's JSON after successful retrieval. Open CPU + * exports in speedscope and GPU exports in Perfetto. GPU activity durations + * can overlap and are not utilization; Python operator attribution and GPU + * allocation stacks are excluded. Filesystem errors propagate to the caller. + */ + async exportProfile(profileId: string, path: string): Promise { + const artifact = await this.inner.profileArtifact(profileId); + await writeFile(path, artifact, "utf8"); + } + private lastProgress: JobProgress | null = null; private enrichProgress(progress: Record): JobProgress { diff --git a/nodejs/lancedb/profiling.ts b/nodejs/lancedb/profiling.ts new file mode 100644 index 000000000..772c84d9d --- /dev/null +++ b/nodejs/lancedb/profiling.ts @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/** Evidence collected from one Function worker's Python execution session. */ +export type FunctionProfileKind = "cpu" | "gpu" | "memory"; + +/** A capture's lifecycle, independent of its parent refresh job. */ +export type FunctionProfileStatus = + | "pending" + | "capturing" + | "complete" + | "failed"; + +/** Options for requesting a Function worker capture. */ +export interface FunctionProfileOptions { + /** CPU samples, retained Python allocations, or PyTorch CUDA activities. */ + kind?: FunctionProfileKind; + /** 1–30 seconds for CPU/memory, default 10; 1–5 for GPU, default 5. */ + durationSeconds?: number; + /** Python execution session within the worker; default zero. */ + sessionSlot?: number; +} + +/** Client-side controls while waiting for a Function worker capture. */ +export interface FunctionProfileWaitOptions { + /** Maximum wait including HTTP requests and sleeps; defaults to 60,000 ms. */ + timeoutMs?: number; + /** Delay between status requests; defaults to 2,000 ms and must be positive. */ + pollIntervalMs?: number; +} + +/** + * A capture identity and status snapshot. Keep profileId for retained lookup + * after the Function refresh completes. Timestamp fields are epoch milliseconds. + */ +export interface FunctionProfile { + readonly profileId: string; + readonly jobId: string; + readonly workerId: string; + readonly executionEpoch: number; + readonly sessionSlot: number; + readonly kind: FunctionProfileKind; + readonly durationSeconds: number; + readonly status: FunctionProfileStatus; + readonly requestedAtMillis: number; + readonly deadlineAtMillis: number; + /** Upper retention bound; job scratch reclamation can remove artifacts sooner. */ + readonly expiresAtMillis: number; + readonly completedAtMillis: number | null; + /** The server's capture failure reason; this is not a refresh job failure. */ + readonly error: string | null; + readonly artifactId: string | null; +} + +export function decodeFunctionProfile(value: string): FunctionProfile { + const data = JSON.parse(value); + return { + profileId: data.profile_id, + jobId: data.job_id, + workerId: data.worker_id, + executionEpoch: data.execution_epoch, + sessionSlot: data.session_slot, + kind: data.kind, + durationSeconds: data.duration_seconds, + status: data.status, + requestedAtMillis: data.requested_at_millis, + deadlineAtMillis: data.deadline_at_millis, + expiresAtMillis: data.expires_at_millis, + completedAtMillis: data.completed_at_millis, + error: data.error, + artifactId: data.artifact_id, + }; +} + +export function validateProfileOptions(options: object, names: string[]): void { + if ( + typeof options !== "object" || + options === null || + Array.isArray(options) + ) { + throw new TypeError("profiling expects an options object"); + } + for (const key of Object.keys(options)) { + if (!names.includes(key)) { + throw new TypeError(`Unknown profiling option: ${key}`); + } + } +} diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 211420ce9..0ff4b916b 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -4,7 +4,10 @@ use std::{sync::Arc, time::Duration}; use arrow_array::RecordBatch; -use lancedb::job::{JobEventsRequest, JobWaitOptions}; +use lancedb::job::{ + FunctionProfileKind, FunctionProfileOptions, FunctionProfileWaitOptions, JobEventsRequest, + JobWaitOptions, +}; use napi::bindgen_prelude::Buffer; use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; @@ -14,6 +17,18 @@ use crate::error::NapiErrorExt; type JobProgressFn = ThreadsafeFunction; +const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; + +fn profile_integer(value: f64, name: &str) -> napi::Result { + if !value.is_finite() || value.fract() != 0.0 || !(0.0..=MAX_SAFE_INTEGER).contains(&value) { + return Err(napi::Error::new( + napi::Status::InvalidArg, + format!("{name} must be a nonnegative safe integer"), + )); + } + Ok(value as u64) +} + /// A handle to an operation that may still be running. #[napi] pub struct Job { @@ -142,7 +157,6 @@ impl Job { ) -> napi::Result> { let mut options = JobWaitOptions::new(); if let Some(timeout_ms) = timeout_ms { - const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; if !timeout_ms.is_finite() || timeout_ms.fract() != 0.0 || !(0.0..=MAX_SAFE_INTEGER).contains(&timeout_ms) @@ -233,6 +247,84 @@ impl Job { self.inner.failure().map(Into::into) } + #[napi(catch_unwind)] + pub async fn capture_profile( + &self, + worker_id: String, + kind: String, + duration_seconds: Option, + session_slot: Option, + ) -> napi::Result { + let kind: FunctionProfileKind = + serde_json::from_value(serde_json::json!(kind)).map_err(|_| { + napi::Error::new(napi::Status::InvalidArg, "kind must be cpu, memory or gpu") + })?; + let mut options = FunctionProfileOptions::new(kind); + if let Some(slot) = session_slot { + options = options.session_slot(profile_integer(slot, "sessionSlot")? as usize); + } + if let Some(seconds) = duration_seconds { + let duration = Duration::try_from_secs_f64(seconds).map_err(|_| { + napi::Error::new( + napi::Status::InvalidArg, + "durationSeconds must be finite and nonnegative", + ) + })?; + options = options.duration(duration); + } + let profile = self + .inner + .capture_profile(worker_id, options) + .await + .default_error()?; + serde_json::to_string(&profile).map_err(|error| napi::Error::from_reason(error.to_string())) + } + + #[napi(catch_unwind)] + pub async fn profile_status(&self, profile_id: String) -> napi::Result { + let profile = self + .inner + .profile_status(profile_id) + .await + .default_error()?; + serde_json::to_string(&profile).map_err(|error| napi::Error::from_reason(error.to_string())) + } + + #[napi(catch_unwind)] + pub async fn wait_for_profile( + &self, + profile_id: String, + timeout_ms: Option, + poll_interval_ms: Option, + ) -> napi::Result { + let mut options = FunctionProfileWaitOptions::new(); + if let Some(ms) = timeout_ms { + options = options.timeout(Duration::from_millis(profile_integer(ms, "timeoutMs")?)); + } + if let Some(ms) = poll_interval_ms { + options = options.poll_interval(Duration::from_millis(profile_integer( + ms, + "pollIntervalMs", + )?)); + } + let profile = self + .inner + .wait_for_profile(profile_id, options) + .await + .default_error()?; + serde_json::to_string(&profile).map_err(|error| napi::Error::from_reason(error.to_string())) + } + + #[napi(catch_unwind)] + pub async fn profile_artifact(&self, profile_id: String) -> napi::Result { + Ok(self + .inner + .profile_artifact(profile_id) + .await + .default_error()? + .to_string()) + } + /// This job's recorded lifecycle events, as an Arrow IPC stream buffer. /// The TypeScript wrapper turns it into an Arrow table. #[napi(catch_unwind)] diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 5fdeb56b2..6632b2acf 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -471,6 +471,23 @@ class Job: async def refresh(self) -> None: ... async def timeline(self) -> str: ... async def stack(self, worker_id: str) -> str: ... + async def capture_profile( + self, + worker_id: str, + *, + kind: str = "cpu", + duration_seconds: Optional[float] = None, + session_slot: int = 0, + ) -> str: ... + async def profile_status(self, profile_id: str) -> str: ... + async def wait_for_profile( + self, + profile_id: str, + *, + timeout_seconds: Optional[float] = None, + poll_interval_seconds: Optional[float] = None, + ) -> str: ... + async def profile_artifact(self, profile_id: str) -> str: ... async def stats(self) -> Optional[str]: ... async def events( self, diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 7ea2151b6..6bdb026f7 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -35,6 +35,7 @@ from .functions import RefreshColumnResult from .compaction import CompactionResult from .cleanup import CleanupResult from .prewarm import PrewarmDataResult +from .profiling import FunctionProfile, FunctionProfileKind, FunctionProfileStatus from .remote.errors import HttpError, RetryError T = TypeVar("T") @@ -46,6 +47,9 @@ __all__ = [ "JobFailureInfo", "JobInfo", "JobState", + "FunctionProfile", + "FunctionProfileKind", + "FunctionProfileStatus", ] @@ -88,6 +92,14 @@ class JobState(str, Enum): return self.value +def _profile_seconds(value: Optional[timedelta], name: str) -> Optional[float]: + if value is None: + return None + if not isinstance(value, timedelta): + raise TypeError(f"{name} must be a datetime.timedelta") + return value.total_seconds() + + def _timeout_message( job_id: Optional[str], timeout: timedelta, job_type: Optional[str] ) -> str: @@ -700,6 +712,122 @@ class AsyncJob(Generic[T]): ) return json.loads(await self._inner.stack(worker_id)) + async def capture_profile( + self, + worker_id: str, + *, + kind: FunctionProfileKind = "cpu", + duration: Optional[timedelta] = None, + session_slot: int = 0, + ) -> FunctionProfile: + """Request a profile of one running Enterprise Function worker session. + + Return an accepted capture identity without waiting for recording to + finish. The capture belongs to this existing refresh job. The server + pins its worker, Python session and execution epoch. System Operate + permission and server profiling support are required. + + ``kind`` is ``"cpu"`` for Python CPU samples, ``"memory"`` for Python + allocations retained at the end of capture, or ``"gpu"`` for PyTorch + CUDA activities. CPU and memory allow 1–30 seconds, defaulting to 10; + GPU allows 1–5 seconds, defaulting to 5. Slot zero is the first Python + session. GPU tracing requires initialized PyTorch CUDA/CUPTI. CPU + sampling requires readable per-thread procfs and is unavailable in + dedicated sandboxes. Captures add workload-dependent overhead. + + Examples + -------- + >>> from datetime import timedelta + >>> profile = await job.capture_profile( # doctest: +SKIP + ... "worker-id", kind="gpu", duration=timedelta(seconds=2) + ... ) + >>> print(profile.profile_id) # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "Function profiling requires an Enterprise Function refresh job" + ) + return FunctionProfile._from_json( + await self._inner.capture_profile( + worker_id, + kind=kind, + duration_seconds=_profile_seconds(duration, "duration"), + session_slot=session_slot, + ) + ) + + async def profile_status(self, profile_id: str) -> FunctionProfile: + """Fetch capture status and identity without waiting. + + A failed capture returns ``status="failed"`` and the server's ``error``. + This does not change the parent job's status. Keep the profile ID to + retrieve retained evidence after the refresh finishes. + """ + if self._inner is None: + raise NotImplementedError( + "Function profiling requires an Enterprise Function refresh job" + ) + return FunctionProfile._from_json(await self._inner.profile_status(profile_id)) + + async def wait_for_profile( + self, + profile_id: str, + *, + timeout: Optional[timedelta] = None, + poll_interval: Optional[timedelta] = None, + ) -> FunctionProfile: + """Wait for a capture independently of the parent Function refresh. + + Defaults to a 60-second timeout and two seconds between status requests. + Set ``poll_interval`` to change the polling cadence. The timeout includes + HTTP requests and sleeps. It raises ``TimeoutError`` without cancelling + either the capture or the refresh; keep the ID to wait again. A failed + capture raises ``RuntimeError`` with the server's reason. Use + ``profile_status`` to inspect a failed capture's typed metadata. + """ + if self._inner is None: + raise NotImplementedError( + "Function profiling requires an Enterprise Function refresh job" + ) + return FunctionProfile._from_json( + await self._inner.wait_for_profile( + profile_id, + timeout_seconds=_profile_seconds(timeout, "timeout"), + poll_interval_seconds=_profile_seconds(poll_interval, "poll_interval"), + ) + ) + + async def profile_artifact(self, profile_id: str) -> dict[str, Any]: + """Retrieve the actual JSON for a completed capture. + + CPU artifacts use speedscope, Python allocations use tracemalloc, and + GPU artifacts use Chrome Trace Event JSON. Truncation metadata is + preserved. The server retains up to eight captures per job for at most + an hour, or until job scratch is reclaimed or archived. Permission, + expired-artifact and unsupported-server errors propagate to the caller. + """ + if self._inner is None: + raise NotImplementedError( + "Function profiling requires an Enterprise Function refresh job" + ) + return json.loads(await self._inner.profile_artifact(profile_id)) + + async def export_profile(self, profile_id: str, path: str | PathLike[str]) -> None: + """Write a completed capture's actual JSON to a file. + + The destination is overwritten only after retrieval succeeds. Export a + CPU capture to a speedscope file, or a GPU capture to a trace file for + Perfetto. GPU kernel/transfer durations may overlap and are not GPU + utilization. Python operator attribution and GPU allocation stacks are + outside the GPU trace format. + """ + if self._inner is None: + raise NotImplementedError( + "Function profiling requires an Enterprise Function refresh job" + ) + artifact = await self._inner.profile_artifact(profile_id) + await asyncio.to_thread(Path(path).write_text, artifact, encoding="utf-8") + async def stats(self) -> Optional[str]: """Return a printable run report for this Function job. @@ -1112,6 +1240,93 @@ class Job(Generic[T]): ) return LOOP.run(self._inner.stack(worker_id)) + def capture_profile( + self, + worker_id: str, + *, + kind: FunctionProfileKind = "cpu", + duration: Optional[timedelta] = None, + session_slot: int = 0, + ) -> FunctionProfile: + """Request a profile of a running Enterprise Function worker session. + + See [AsyncJob.capture_profile][lancedb.job.AsyncJob.capture_profile] for + kinds, recording windows, permissions and runtime requirements. + + >>> from datetime import timedelta + >>> profile = job.capture_profile( # doctest: +SKIP + ... "worker-id", kind="cpu", duration=timedelta(seconds=10) + ... ) + >>> job.wait_for_profile(profile.profile_id) # doctest: +SKIP + >>> job.export_profile( # doctest: +SKIP + ... profile.profile_id, "cpu.speedscope.json" + ... ) + """ + if self._inner is None: + raise NotImplementedError( + "Function profiling requires an Enterprise Function refresh job" + ) + return LOOP.run( + self._inner.capture_profile( + worker_id, kind=kind, duration=duration, session_slot=session_slot + ) + ) + + def profile_status(self, profile_id: str) -> FunctionProfile: + """Fetch capture status, including retained captures after refresh. + + See [AsyncJob.profile_status][lancedb.job.AsyncJob.profile_status]. + """ + if self._inner is None: + raise NotImplementedError( + "Function profiling requires an Enterprise Function refresh job" + ) + return LOOP.run(self._inner.profile_status(profile_id)) + + def wait_for_profile( + self, + profile_id: str, + *, + timeout: Optional[timedelta] = None, + poll_interval: Optional[timedelta] = None, + ) -> FunctionProfile: + """Wait for a capture with a configurable timeout and polling cadence. + + See [AsyncJob.wait_for_profile][lancedb.job.AsyncJob.wait_for_profile]. + A client timeout never cancels the capture or parent refresh job. + """ + if self._inner is None: + raise NotImplementedError( + "Function profiling requires an Enterprise Function refresh job" + ) + return LOOP.run( + self._inner.wait_for_profile( + profile_id, timeout=timeout, poll_interval=poll_interval + ) + ) + + def profile_artifact(self, profile_id: str) -> dict[str, Any]: + """Retrieve a completed capture's actual JSON, preserving its format. + + See [AsyncJob.profile_artifact][lancedb.job.AsyncJob.profile_artifact]. + """ + if self._inner is None: + raise NotImplementedError( + "Function profiling requires an Enterprise Function refresh job" + ) + return LOOP.run(self._inner.profile_artifact(profile_id)) + + def export_profile(self, profile_id: str, path: str | PathLike[str]) -> None: + """Write a retained capture's JSON after successful retrieval. + + See [AsyncJob.export_profile][lancedb.job.AsyncJob.export_profile]. + """ + if self._inner is None: + raise NotImplementedError( + "Function profiling requires an Enterprise Function refresh job" + ) + return LOOP.run(self._inner.export_profile(profile_id, path)) + def stats(self) -> Optional[str]: """Return a printable Function job run report. diff --git a/python/python/lancedb/profiling.py b/python/python/lancedb/profiling.py new file mode 100644 index 000000000..5534f9e53 --- /dev/null +++ b/python/python/lancedb/profiling.py @@ -0,0 +1,49 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Typed snapshots of on-demand Enterprise Function worker captures.""" + +import json +from dataclasses import dataclass +from typing import Literal, Optional + +FunctionProfileKind = Literal["cpu", "gpu", "memory"] +FunctionProfileStatus = Literal["pending", "capturing", "complete", "failed"] + +__all__ = ["FunctionProfile", "FunctionProfileKind", "FunctionProfileStatus"] + + +@dataclass(frozen=True) +class FunctionProfile: + """A capture's identity, current status and artifact retention bounds. + + Retain ``profile_id`` to retrieve the capture through the parent Job, + including after its refresh completes. ``status`` and ``error`` describe + the capture independently of the parent refresh job. Timestamp fields are + milliseconds since the Unix epoch. ``expires_at_millis`` is an upper bound: + the server may reclaim job scratch or evict an older capture sooner. + + CPU evidence contains Python stacks weighted by thread CPU time. Memory + evidence contains Python allocations made during capture and retained at + its end. GPU evidence contains PyTorch CUDA activities; it excludes Python + operator attribution and GPU allocation stacks. + """ + + profile_id: str + job_id: str + worker_id: str + execution_epoch: int + session_slot: int + kind: FunctionProfileKind + duration_seconds: float + status: FunctionProfileStatus + requested_at_millis: int + deadline_at_millis: int + expires_at_millis: int + completed_at_millis: Optional[int] = None + error: Optional[str] = None + artifact_id: Optional[str] = None + + @classmethod + def _from_json(cls, value: str) -> "FunctionProfile": + return cls(**json.loads(value)) diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index 611d9b72b..ed223e7db 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -1353,3 +1353,66 @@ async def test_prewarm_progress_bar_preserves_unknown_and_zero_totals( assert bar.n == 0 assert bar.total == (0 if known_empty else None) assert bar.unit == " executors" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_profile_wait_preserves_timeout_and_never_waits_or_cancels_parent(sync): + error = TimeoutError("capture and refresh continue") + inner = SimpleNamespace( + wait_for_profile=AsyncMock(side_effect=error), + wait=AsyncMock(), + cancel=AsyncMock(), + ) + job = AsyncJob(inner) + kwargs = { + "timeout": timedelta(milliseconds=50), + "poll_interval": timedelta(seconds=5), + } + with pytest.raises(TimeoutError) as caught: + if sync: + await asyncio.to_thread(Job(job).wait_for_profile, "profile-1", **kwargs) + else: + await job.wait_for_profile("profile-1", **kwargs) + assert caught.value is error + inner.wait_for_profile.assert_awaited_once_with( + "profile-1", timeout_seconds=0.05, poll_interval_seconds=5.0 + ) + inner.wait.assert_not_awaited() + inner.cancel.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_profile_export_failure_preserves_destination_and_server_error( + sync, tmp_path +): + error = HttpError("403: System Operate required", "request-1", 403) + inner = SimpleNamespace(profile_artifact=AsyncMock(side_effect=error)) + job = AsyncJob(inner) + path = tmp_path / "profile.json" + path.write_text("previous capture") + with pytest.raises(HttpError) as caught: + if sync: + await asyncio.to_thread(Job(job).export_profile, "profile-1", path) + else: + await job.export_profile("profile-1", path) + assert caught.value is error + assert path.read_text() == "previous capture" + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "method,args", + [ + ("capture_profile", ("worker-1",)), + ("profile_status", ("profile-1",)), + ("wait_for_profile", ("profile-1",)), + ("profile_artifact", ("profile-1",)), + ], +) +async def test_function_profiles_reject_embedded_handles(method, args): + with pytest.raises(NotImplementedError, match="Enterprise Function refresh job"): + await getattr(AsyncJob(None), method)(*args) + with pytest.raises(NotImplementedError, match="Enterprise Function refresh job"): + getattr(Job(None), method)(*args) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 162522a83..a1d811ec9 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -9115,3 +9115,142 @@ async def test_paged_function_errors_retain_history_and_expose_continuation( with pytest.raises(ValueError, match="current failures"): errors.rows() assert received == [{"job_id": "attempt-1", "page_token": "", "history": True}] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync_api", [False, True]) +@pytest.mark.parametrize("kind", ["cpu", "memory", "gpu"]) +@pytest.mark.parametrize("submitted_job", [False, True]) +async def test_function_profile_capture_wait_and_retained_export( + sync_api, kind, submitted_job, tmp_path +): + state = {"polls": 0, "finished": False} + paths = [] + profile = { + "profile_id": "profile-1", + "job_id": "job-1", + "worker_id": "worker-1", + "execution_epoch": 3, + "session_slot": 2, + "kind": kind, + "duration_seconds": 2, + "status": "pending", + "requested_at_millis": 1000, + "deadline_at_millis": 46000, + "expires_at_millis": 3601000, + "completed_at_millis": None, + "error": None, + "artifact_id": None, + } + artifacts = { + "cpu": { + "$schema": "https://www.speedscope.app/file-format-schema.json", + "shared": {"frames": [{"name": "work"}]}, + "profiles": [], + }, + "memory": { + "format": "lancedb.tracemalloc.v1", + "allocations": [{"size_bytes": 4096}], + "truncated": False, + }, + "gpu": { + "format": "lancedb.cuda.v1", + "traceEvents": [{"name": "compute", "ph": "X", "ts": 10, "dur": 2}], + "truncated": True, + }, + } + + def handler(request): + paths.append(request.path) + assert request.headers["x-api-key"] == "fake" + assert request.headers["x-lancedb-database"] == "dev" + 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/": + result = {"version": 1, "schema": {"fields": []}} + elif request.path == "/v1/table/test/backfill_column": + assert body["column"] == "result" + result = {"job_id": "job-1"} + elif request.path == "/v1/jobs/describe": + result = { + "job_id": "job-1", + "job_type": "function_refresh", + "job_state": "DONE" if state["finished"] else "IN_PROGRESS", + } + elif request.path == "/v1/jobs/profile/capture": + assert body == { + "job_id": "job-1", + "worker_id": "worker-1", + "session_slot": 2, + "kind": kind, + "duration_seconds": 2.0, + } + result = profile + elif request.path == "/v1/jobs/profile/status": + assert body == {"job_id": "job-1", "profile_id": "profile-1"} + state["polls"] += 1 + result = dict( + profile, + status="complete" if state["polls"] > 1 else "capturing", + artifact_id="profile-1" if state["polls"] > 1 else None, + ) + elif request.path == "/v1/jobs/profile/artifact": + assert body == {"job_id": "job-1", "profile_id": "profile-1"} + result = artifacts[kind] + else: + raise AssertionError(f"Unexpected request: {request.path}") + request.send_response( + 200 if request.path != "/v1/jobs/profile/capture" else 202 + ) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(result).encode()) + + async def exercise(db): + async def invoke(function, *args, **kwargs): + if sync_api: + return await asyncio.to_thread(function, *args, **kwargs) + return await function(*args, **kwargs) + + if submitted_job: + table = await invoke(db.open_table, "test") + job = await invoke(table.refresh_column_async, "result") + await invoke(job.refresh) + else: + job = await invoke(db.open_job, "job-1") + capture = await invoke( + job.capture_profile, + "worker-1", + kind=kind, + duration=timedelta(seconds=2), + session_slot=2, + ) + assert capture.profile_id == "profile-1" + assert capture.worker_id == "worker-1" + assert capture.session_slot == 2 + assert capture.execution_epoch == 3 + assert capture.status == "pending" + completed = await invoke( + job.wait_for_profile, + capture.profile_id, + timeout=timedelta(seconds=2), + poll_interval=timedelta(milliseconds=10), + ) + assert completed.status == "complete" + assert job.state() == "running" + state["finished"] = True + await invoke(job.refresh) + assert job.state() == "finished" + assert await invoke(job.profile_artifact, capture.profile_id) == artifacts[kind] + path = tmp_path / "profile.json" + await invoke(job.export_profile, capture.profile_id, path) + assert json.loads(path.read_text()) == artifacts[kind] + assert paths.count("/v1/jobs/describe") == 2 + assert not any(path.endswith("/cancel") for path in paths) + + if sync_api: + with mock_lancedb_connection(handler) as db: + await exercise(db) + else: + async with mock_lancedb_connection_async(handler) as db: + await exercise(db) diff --git a/python/src/job.rs b/python/src/job.rs index 54c22a8e1..ec1f55d32 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -2,16 +2,20 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use std::sync::Arc; +use std::time::Duration; use crate::runtime::future_into_py; use arrow::{ datatypes::Schema, pyarrow::{IntoPyArrow, Table as PyArrowTable}, }; -use lancedb::job::JobEventsRequest; +use lancedb::job::{ + FunctionProfile, FunctionProfileKind, FunctionProfileOptions, FunctionProfileWaitOptions, + JobEventsRequest, +}; use pyo3::{ Bound, Py, PyAny, PyRef, PyResult, Python, - exceptions::PyValueError, + exceptions::{PyTimeoutError, PyValueError}, pyclass, pymethods, types::{PyAnyMethods, PyDict, PyDictMethods}, }; @@ -21,6 +25,17 @@ use crate::error::PythonErrorExt; const REPR_INDENT: &str = " "; +fn profile_json(result: lancedb::Result) -> PyResult { + let profile = result.infer_error()?; + serde_json::to_string(&profile) + .map_err(|error| PyValueError::new_err(format!("invalid profile metadata: {error}"))) +} + +fn profile_duration(seconds: f64) -> PyResult { + Duration::try_from_secs_f64(seconds) + .map_err(|_| PyValueError::new_err("profile durations must be finite and nonnegative")) +} + /// Parse a stored JSON payload into Python data. The bindings carry these as /// strings because that is what crosses the boundary cheaply; the public /// Python surface is the parsed form. @@ -212,6 +227,73 @@ impl Job { }) } + #[pyo3(signature = (worker_id, *, kind="cpu", duration_seconds=None, session_slot=0))] + pub fn capture_profile<'py>( + self_: PyRef<'py, Self>, + worker_id: String, + kind: &str, + duration_seconds: Option, + session_slot: usize, + ) -> PyResult> { + let kind: FunctionProfileKind = serde_json::from_value(serde_json::json!(kind)) + .map_err(|_| PyValueError::new_err("kind must be 'cpu', 'memory' or 'gpu'"))?; + let mut options = FunctionProfileOptions::new(kind).session_slot(session_slot); + if let Some(seconds) = duration_seconds { + options = options.duration(profile_duration(seconds)?); + } + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + profile_json(inner.capture_profile(worker_id, options).await) + }) + } + + pub fn profile_status( + self_: PyRef<'_, Self>, + profile_id: String, + ) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + profile_json(inner.profile_status(profile_id).await) + }) + } + + #[pyo3(signature = (profile_id, *, timeout_seconds=None, poll_interval_seconds=None))] + pub fn wait_for_profile( + self_: PyRef<'_, Self>, + profile_id: String, + timeout_seconds: Option, + poll_interval_seconds: Option, + ) -> PyResult> { + let mut options = FunctionProfileWaitOptions::new(); + if let Some(seconds) = timeout_seconds { + options = options.timeout(profile_duration(seconds)?); + } + if let Some(seconds) = poll_interval_seconds { + options = options.poll_interval(profile_duration(seconds)?); + } + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + match inner.wait_for_profile(profile_id, options).await { + Err(lancedb::Error::Timeout { message }) => Err(PyTimeoutError::new_err(message)), + result => profile_json(result), + } + }) + } + + pub fn profile_artifact( + self_: PyRef<'_, Self>, + profile_id: String, + ) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + Ok(inner + .profile_artifact(profile_id) + .await + .infer_error()? + .to_string()) + }) + } + pub fn stats(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { inner.stats().await.infer_error() }) diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index fef2431d9..44928eca7 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -3,6 +3,13 @@ //! Handles to operations a server may run asynchronously. +mod profile; + +pub use profile::{ + FunctionProfile, FunctionProfileKind, FunctionProfileOptions, FunctionProfileStatus, + FunctionProfileWaitOptions, +}; + use std::future::Future; use std::pin::Pin; use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard}; @@ -14,6 +21,7 @@ use serde::{Serialize, de::DeserializeOwned}; use serde_json::Value; use tokio::sync::watch; use tokio::task::{AbortHandle, JoinHandle}; +use tokio::time::{Instant, sleep_until, timeout_at}; use uuid::Uuid; use crate::database::JobDescription; @@ -164,6 +172,22 @@ pub(crate) trait JobHandle: Send + Sync { job_detail_not_supported("worker stack capture") } + async fn capture_profile( + &self, + _worker_id: &str, + _options: FunctionProfileOptions, + ) -> Result { + job_detail_not_supported("Function worker profiling") + } + + async fn profile_status(&self, _profile_id: &str) -> Result { + job_detail_not_supported("Function worker profiling") + } + + async fn profile_artifact(&self, _profile_id: &str) -> Result { + job_detail_not_supported("Function worker profiling") + } + /// A printable report of recorded Function job metrics. async fn stats(&self) -> Result> { job_detail_not_supported("job statistics") @@ -753,6 +777,135 @@ where } } + /// Request an on-demand profile from a running Enterprise Function worker. + /// + /// Returns the accepted capture identity without waiting for recording to + /// finish. The server pins the worker, Python session and execution epoch. + /// Requires System Operate permission and a supporting Enterprise server. + /// Only one capture per job can be active. GPU traces require initialized + /// PyTorch CUDA/CUPTI; CPU sampling requires readable per-thread procfs. + /// Captures add workload-dependent overhead. + /// + /// ```no_run + /// # async fn capture(job: &lancedb::job::Job) -> Result<(), Box> { + /// use std::time::Duration; + /// use lancedb::job::{FunctionProfileKind, FunctionProfileOptions, FunctionProfileWaitOptions}; + /// let profile = job.capture_profile("worker-id", + /// FunctionProfileOptions::new(FunctionProfileKind::Gpu) + /// .duration(Duration::from_secs(2))).await?; + /// job.wait_for_profile(&profile.profile_id, FunctionProfileWaitOptions::new()).await?; + /// let artifact = job.profile_artifact(&profile.profile_id).await?; + /// std::fs::write("gpu.trace.json", serde_json::to_vec(&artifact)?)?; + /// # Ok(()) + /// # } + /// ``` + pub async fn capture_profile( + &self, + worker_id: impl AsRef, + options: FunctionProfileOptions, + ) -> Result { + let worker_id = worker_id.as_ref(); + options.validate(worker_id)?; + match &self.inner { + JobInner::Handle { handle, .. } => handle.capture_profile(worker_id, options).await, + JobInner::Completed(_) => job_detail_not_supported("Function worker profiling"), + } + } + + /// Fetch the capture's current identity and status without waiting. + /// + /// Capture failures are returned as [`FunctionProfileStatus::Failed`] with + /// the server's reason. This does not change the parent job's cached state. + /// Retained captures can be looked up after the refresh job completes. + pub async fn profile_status(&self, profile_id: impl AsRef) -> Result { + let profile_id = profile_id.as_ref(); + profile::validate_profile_id(profile_id)?; + match &self.inner { + JobInner::Handle { handle, .. } => handle.profile_status(profile_id).await, + JobInner::Completed(_) => job_detail_not_supported("Function worker profiling"), + } + } + + /// Wait for a capture to finish, independently of the Function refresh job. + /// + /// Returns [`Error::Timeout`] when the client deadline elapses and + /// [`Error::Runtime`] when capture fails. Neither cancels the capture or + /// refresh job. Keep the profile ID to wait again or retrieve it later. + pub async fn wait_for_profile( + &self, + profile_id: impl AsRef, + options: FunctionProfileWaitOptions, + ) -> Result { + let profile_id = profile_id.as_ref(); + profile::validate_profile_id(profile_id)?; + if options.poll_interval.is_zero() { + return Err(Error::InvalidInput { + message: "profile poll interval must be greater than zero".into(), + }); + } + let deadline = + Instant::now() + .checked_add(options.timeout) + .ok_or_else(|| Error::InvalidInput { + message: "profile wait timeout is too large".into(), + })?; + let wait = async { + let mut previous: Option = None; + loop { + let profile = self.profile_status(profile_id).await?; + if previous + .as_ref() + .is_some_and(|old| !old.same_capture(&profile)) + { + return Err(Error::Runtime { + message: "profile response changed the capture's execution identity".into(), + }); + } + match profile.status { + FunctionProfileStatus::Complete => return Ok(profile), + FunctionProfileStatus::Failed => { + return Err(Error::Runtime { + message: format!( + "Function worker profile {} failed: {}", + profile.profile_id, + profile.error.as_deref().unwrap_or("no reason reported") + ), + }); + } + FunctionProfileStatus::Pending | FunctionProfileStatus::Capturing => {} + } + previous = Some(profile); + let next_poll = Instant::now() + .checked_add(options.poll_interval) + .unwrap_or(deadline) + .min(deadline); + sleep_until(next_poll).await; + } + }; + timeout_at(deadline, wait) + .await + .map_err(|_| Error::Timeout { + message: format!( + "waiting for Function worker profile {profile_id}; capture and refresh job continue on the server" + ), + })? + } + + /// Retrieve the actual profile JSON, including a retained capture after refresh. + /// + /// CPU artifacts use speedscope, Python memory artifacts use tracemalloc, + /// and GPU artifacts use Chrome Trace Event JSON. GPU truncation flags are + /// preserved. Artifacts expire after at most one hour and eight captures + /// per job, or earlier when job scratch is reclaimed or archived. + pub async fn profile_artifact(&self, profile_id: impl AsRef) -> Result { + let profile_id = profile_id.as_ref(); + profile::validate_profile_id(profile_id)?; + match &self.inner { + JobInner::Handle { handle, .. } => handle.profile_artifact(profile_id).await, + JobInner::Completed(_) => job_detail_not_supported("Function worker profiling"), + } + } + /// Fetch a printable run report for a server-side Function job. /// /// The server report includes recorded phase timings, finishing-supervisor @@ -1112,6 +1265,48 @@ mod tests { use super::*; + struct PendingProfileStatus; + + #[async_trait] + impl JobHandle for PendingProfileStatus { + async fn status(&self) -> Result { + panic!("profile wait fetched parent status") + } + async fn wait(&self) -> Result { + panic!("profile wait waited for parent completion") + } + async fn cancel(&self) -> Result<()> { + panic!("profile wait cancelled parent job") + } + async fn profile_status(&self, _profile_id: &str) -> Result { + pending().await + } + } + + #[tokio::test(start_paused = true)] + async fn profile_timeout_bounds_pending_requests_and_rejects_deadline_overflow() { + let job = Job::new(Box::new(PendingProfileStatus)); + let started = Instant::now(); + assert!(matches!( + job.wait_for_profile( + "profile-1", + FunctionProfileWaitOptions::new().timeout(Duration::from_millis(50)) + ) + .await, + Err(Error::Timeout { .. }) + )); + assert_eq!(started.elapsed(), Duration::from_millis(50)); + assert_eq!(job.state(), None); + assert!(matches!( + job.wait_for_profile( + "profile-1", + FunctionProfileWaitOptions::new().timeout(Duration::MAX) + ) + .await, + Err(Error::InvalidInput { .. }) + )); + } + #[tokio::test(start_paused = true)] async fn wait_timeout_preserves_local_task_and_typed_result() { let job = Job::spawned(tokio::spawn(async { diff --git a/rust/lancedb/src/job/profile.rs b/rust/lancedb/src/job/profile.rs new file mode 100644 index 000000000..d8e409948 --- /dev/null +++ b/rust/lancedb/src/job/profile.rs @@ -0,0 +1,223 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! On-demand profiling of a Function worker's Python execution session. + +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +use crate::error::{Error, Result}; + +pub(crate) fn validate_profile_id(profile_id: &str) -> Result<()> { + if profile_id.is_empty() || profile_id.len() > 256 { + return Err(Error::InvalidInput { + message: "profile_id must contain between 1 and 256 bytes".into(), + }); + } + Ok(()) +} + +/// What to record in one Function worker process. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +#[non_exhaustive] +pub enum FunctionProfileKind { + /// Python stack samples weighted by thread CPU time, exported as speedscope JSON. + Cpu, + /// PyTorch CUDA kernels, transfers and available CUDA host API activities. + Gpu, + /// Python allocations made during the capture and retained at its end. + Memory, +} + +impl FunctionProfileKind { + fn maximum_duration(self) -> Duration { + Duration::from_secs(if self == Self::Gpu { 5 } else { 30 }) + } +} + +/// Server-reported state of a profile capture, independent of its parent job. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +#[non_exhaustive] +pub enum FunctionProfileStatus { + /// Waiting for the Function supervisor to dispatch the capture. + Pending, + /// Recording the selected execution session. + Capturing, + /// The artifact can be retrieved until expiry or scratch reclamation. + Complete, + /// Capture failed; inspect [`FunctionProfile::error`] for the server's reason. + Failed, +} + +/// A snapshot of a capture's identity, status and retention information. +/// +/// It describes a diagnostic capture on an existing Function refresh job, not +/// another job. Use its profile ID with [`super::Job::profile_status`] or +/// [`super::Job::profile_artifact`], including after the refresh finishes. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct FunctionProfile { + /// Retain this ID to retrieve the capture later. + pub profile_id: String, + /// The parent Function refresh job. + pub job_id: String, + /// The selected Function worker. + pub worker_id: String, + /// Execution epoch pinned by the server when accepting the capture. + pub execution_epoch: i64, + /// Python session slot; zero is the first session. + pub session_slot: usize, + /// The kind of evidence collected. + pub kind: FunctionProfileKind, + /// Requested recording window, excluding dispatch delay. + pub duration_seconds: f64, + /// Current capture state. + pub status: FunctionProfileStatus, + /// Acceptance time, in milliseconds since the Unix epoch. + pub requested_at_millis: i64, + /// Server deadline for an unfinished capture, in epoch milliseconds. + pub deadline_at_millis: i64, + /// Retention bound in epoch milliseconds; scratch reclamation may remove it sooner. + pub expires_at_millis: i64, + /// Completion time, when reported. + pub completed_at_millis: Option, + /// Server-reported failure reason, including unsupported-session errors. + pub error: Option, + /// Server artifact identity, when the capture completes. + pub artifact_id: Option, +} + +impl FunctionProfile { + pub(crate) fn same_capture(&self, other: &Self) -> bool { + self.profile_id == other.profile_id + && self.job_id == other.job_id + && self.worker_id == other.worker_id + && self.execution_epoch == other.execution_epoch + && self.session_slot == other.session_slot + && self.kind == other.kind + && self.duration_seconds == other.duration_seconds + } + + pub(crate) fn valid_for(&self, job_id: &str, profile_id: Option<&str>) -> bool { + self.job_id == job_id + && !self.profile_id.is_empty() + && self.profile_id.len() <= 256 + && profile_id.is_none_or(|id| id == self.profile_id) + && !self.worker_id.is_empty() + && self.worker_id.len() <= 256 + && self.duration_seconds.is_finite() + && (1.0..=self.kind.maximum_duration().as_secs_f64()).contains(&self.duration_seconds) + && (self.status != FunctionProfileStatus::Complete + || self.artifact_id.as_ref().is_some_and(|id| !id.is_empty())) + } +} + +/// Options for [`super::Job::capture_profile`]. +/// +/// CPU and memory captures allow 1–30 seconds; GPU captures allow 1–5. +/// Omitting the duration selects 10 seconds for CPU/memory and 5 for GPU. +#[derive(Debug, Clone)] +pub struct FunctionProfileOptions { + pub(crate) kind: FunctionProfileKind, + pub(crate) duration: Option, + pub(crate) session_slot: usize, +} + +impl Default for FunctionProfileOptions { + fn default() -> Self { + Self::new(FunctionProfileKind::Cpu) + } +} + +impl FunctionProfileOptions { + /// Select the kind of capture, using its default duration and session zero. + pub fn new(kind: FunctionProfileKind) -> Self { + Self { + kind, + duration: None, + session_slot: 0, + } + } + + /// Set the recording window. Dispatch time is additional. + pub fn duration(mut self, duration: Duration) -> Self { + self.duration = Some(duration); + self + } + + /// Select the Python session within the worker. + pub fn session_slot(mut self, slot: usize) -> Self { + self.session_slot = slot; + self + } + + pub(crate) fn duration_seconds(&self) -> f64 { + self.duration + .unwrap_or_else(|| { + Duration::from_secs(if self.kind == FunctionProfileKind::Gpu { + 5 + } else { + 10 + }) + }) + .as_secs_f64() + } + + pub(crate) fn validate(&self, worker_id: &str) -> Result<()> { + if worker_id.is_empty() || worker_id.len() > 256 { + return Err(Error::InvalidInput { + message: "worker_id must contain between 1 and 256 bytes".into(), + }); + } + if !(1.0..=self.kind.maximum_duration().as_secs_f64()).contains(&self.duration_seconds()) { + return Err(Error::InvalidInput { + message: format!( + "profile duration must be between 1 and {} seconds", + self.kind.maximum_duration().as_secs() + ), + }); + } + Ok(()) + } +} + +/// Client controls for [`super::Job::wait_for_profile`]. +/// +/// Defaults to a 60-second timeout and two seconds between status requests. +/// The timeout includes requests and sleeps, and never cancels the capture or job. +#[derive(Debug, Clone)] +pub struct FunctionProfileWaitOptions { + pub(crate) timeout: Duration, + pub(crate) poll_interval: Duration, +} + +impl Default for FunctionProfileWaitOptions { + fn default() -> Self { + Self { + timeout: Duration::from_secs(60), + poll_interval: Duration::from_secs(2), + } + } +} + +impl FunctionProfileWaitOptions { + /// Use the default timeout and polling interval. + pub fn new() -> Self { + Self::default() + } + + /// Bound this wait without cancelling server-side work. + pub fn timeout(mut self, timeout: Duration) -> Self { + self.timeout = timeout; + self + } + + /// Delay between status requests; must be greater than zero. + pub fn poll_interval(mut self, interval: Duration) -> Self { + self.poll_interval = interval; + self + } +} diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 1c3678031..7385a74d5 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -3,6 +3,8 @@ //! Tracking for server-side jobs through the `/v1/jobs` API. +mod profile; + use std::time::Duration; use arrow_array::RecordBatch; @@ -13,7 +15,10 @@ use serde::Deserialize; use crate::database::JobDescription; use crate::error::{Error, JobFailure, Result}; -use crate::job::{JobEventsRequest, JobHandle, JobProgressCallback, TerminalResult}; +use crate::job::{ + FunctionProfile, FunctionProfileOptions, JobEventsRequest, JobHandle, JobProgressCallback, + TerminalResult, +}; use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; /// Delay before the second job-state poll; doubles up to [`MAX_POLL_INTERVAL`]. @@ -356,6 +361,22 @@ impl JobHandle for RemoteJob { Ok(evidence) } + async fn capture_profile( + &self, + worker_id: &str, + options: FunctionProfileOptions, + ) -> Result { + self.capture_profile_inner(worker_id, options).await + } + + async fn profile_status(&self, profile_id: &str) -> Result { + self.profile_status_inner(profile_id).await + } + + async fn profile_artifact(&self, profile_id: &str) -> Result { + self.profile_artifact_inner(profile_id).await + } + async fn stats(&self) -> Result> { let request = self .client diff --git a/rust/lancedb/src/remote/job/profile.rs b/rust/lancedb/src/remote/job/profile.rs new file mode 100644 index 000000000..3142d3e34 --- /dev/null +++ b/rust/lancedb/src/remote/job/profile.rs @@ -0,0 +1,476 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use serde::de::DeserializeOwned; +use serde_json::{Value, json}; + +use super::RemoteJob; +use crate::error::{Error, Result}; +use crate::job::{ + FunctionProfile, FunctionProfileKind, FunctionProfileOptions, FunctionProfileStatus, +}; +use crate::remote::client::{HttpSend, RequestResultExt}; + +impl RemoteJob { + async fn profile_request( + &self, + action: &str, + body: Value, + ) -> Result<(String, T)> { + let request = self + .client + .post(&format!("/v1/jobs/profile/{action}")) + .json(&body); + 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 value = serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("invalid Function profile {action} response: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + Ok((request_id, value)) + } + + pub(super) async fn capture_profile_inner( + &self, + worker_id: &str, + options: FunctionProfileOptions, + ) -> Result { + let duration = options.duration_seconds(); + let (request_id, profile): (_, FunctionProfile) = self + .profile_request( + "capture", + json!({ + "job_id": self.job_id, + "worker_id": worker_id, + "session_slot": options.session_slot, + "kind": options.kind, + "duration_seconds": duration, + }), + ) + .await?; + if !profile.valid_for(&self.job_id, None) + || profile.worker_id != worker_id + || profile.session_slot != options.session_slot + || profile.kind != options.kind + || profile.duration_seconds != duration + { + return Err(Error::Http { + source: "Function profile response does not match the requested capture".into(), + request_id, + status_code: None, + }); + } + Ok(profile) + } + + pub(super) async fn profile_status_inner(&self, profile_id: &str) -> Result { + let (request_id, profile): (_, FunctionProfile) = self + .profile_request( + "status", + json!({"job_id": self.job_id, "profile_id": profile_id}), + ) + .await?; + if !profile.valid_for(&self.job_id, Some(profile_id)) { + return Err(Error::Http { + source: "Function profile response does not match the requested identity".into(), + request_id, + status_code: None, + }); + } + Ok(profile) + } + + pub(super) async fn profile_artifact_inner(&self, profile_id: &str) -> Result { + let profile = self.profile_status_inner(profile_id).await?; + if profile.status != FunctionProfileStatus::Complete { + return Err(Error::Runtime { + message: format!( + "Function worker profile {profile_id} is not complete ({:?}): {}", + profile.status, + profile + .error + .as_deref() + .unwrap_or("artifact is not available") + ), + }); + } + let (request_id, artifact): (_, Value) = self + .profile_request( + "artifact", + json!({"job_id": self.job_id, "profile_id": profile_id}), + ) + .await?; + let valid = match profile.kind { + FunctionProfileKind::Cpu => { + artifact.get("$schema").and_then(Value::as_str) + == Some("https://www.speedscope.app/file-format-schema.json") + && artifact + .pointer("/shared/frames") + .is_some_and(Value::is_array) + && artifact.get("profiles").is_some_and(Value::is_array) + } + FunctionProfileKind::Memory => { + artifact.get("format").and_then(Value::as_str) == Some("lancedb.tracemalloc.v1") + && artifact.get("allocations").is_some_and(Value::is_array) + } + FunctionProfileKind::Gpu => { + artifact.get("format").and_then(Value::as_str) == Some("lancedb.cuda.v1") + && artifact.get("traceEvents").is_some_and(Value::is_array) + && artifact.get("truncated").is_some_and(Value::is_boolean) + } + }; + if !valid { + return Err(Error::Http { + source: "Function profile artifact does not match its declared format".into(), + request_id, + status_code: None, + }); + } + Ok(artifact) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::time::Duration; + + use serde_json::{Value, json}; + + use crate::error::Error; + use crate::job::{ + FunctionProfileKind, FunctionProfileOptions, FunctionProfileStatus, + FunctionProfileWaitOptions, Job, + }; + use crate::remote::client::test_utils::client_with_handler; + use crate::remote::job::RemoteJob; + + fn metadata(kind: &str, status: &str) -> Value { + json!({ + "profile_id": "profile-1", "job_id": "job-1", "worker_id": "worker-1", + "execution_epoch": 3, "session_slot": 0, "kind": kind, + "duration_seconds": 2.0, "status": status, + "requested_at_millis": 1000, "deadline_at_millis": 46000, + "expires_at_millis": 3601000, "completed_at_millis": null, + "error": if status == "failed" { Some("gpu_unavailable") } else { None }, + "artifact_id": if status == "complete" { Some("profile-1") } else { None }, + }) + } + + #[tokio::test] + async fn capture_sends_selected_identity_and_kind_specific_defaults() { + for (kind, name, duration) in [ + (FunctionProfileKind::Cpu, "cpu", 10.0), + (FunctionProfileKind::Memory, "memory", 10.0), + (FunctionProfileKind::Gpu, "gpu", 5.0), + ] { + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/profile/capture"); + let body: Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!( + body, + json!({ + "job_id":"job-1", "worker_id":"worker-1", "kind":name, + "session_slot":2, "duration_seconds":duration, + }) + ); + let mut value = metadata(name, "pending"); + value["session_slot"] = json!(2); + value["duration_seconds"] = json!(duration); + http::Response::builder() + .status(202) + .body(value.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + let profile = job + .capture_profile( + "worker-1", + FunctionProfileOptions::new(kind).session_slot(2), + ) + .await + .unwrap(); + assert_eq!(profile.kind, kind); + assert_eq!(profile.execution_epoch, 3); + assert_eq!(profile.status, FunctionProfileStatus::Pending); + assert_eq!(job.state(), None); + } + } + + #[tokio::test] + async fn invalid_capture_options_never_send_a_request() { + let client = + client_with_handler::(|_| panic!("invalid capture sent an HTTP request")); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + for (kind, duration) in [ + (FunctionProfileKind::Cpu, Duration::from_millis(999)), + (FunctionProfileKind::Memory, Duration::from_secs(31)), + (FunctionProfileKind::Gpu, Duration::from_millis(5001)), + ] { + assert!(matches!( + job.capture_profile( + "worker-1", + FunctionProfileOptions::new(kind).duration(duration) + ) + .await, + Err(Error::InvalidInput { .. }) + )); + } + assert!( + job.capture_profile("", FunctionProfileOptions::default()) + .await + .is_err() + ); + assert!( + job.capture_profile("é".repeat(129), FunctionProfileOptions::default()) + .await + .is_err() + ); + assert!(job.profile_status("").await.is_err()); + assert!(job.profile_artifact("p".repeat(257)).await.is_err()); + } + + #[tokio::test] + async fn response_identity_and_unsupported_servers_are_not_accepted_as_captures() { + for mutation in [ + "profile_id", + "job_id", + "worker_id", + "kind", + "session_slot", + "duration_seconds", + ] { + let client = client_with_handler(move |_| { + let mut value = metadata("gpu", "pending"); + value[mutation] = match mutation { + "profile_id" => json!(""), + "session_slot" => json!(1), + "duration_seconds" => json!(3), + "kind" => json!("cpu"), + _ => json!("other"), + }; + http::Response::builder() + .status(200) + .body(value.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + assert!(matches!( + job.capture_profile( + "worker-1", + FunctionProfileOptions::new(FunctionProfileKind::Gpu) + .duration(Duration::from_secs(2)) + ) + .await, + Err(Error::Http { .. }) + )); + } + let client = + client_with_handler(|_| http::Response::builder().status(200).body("{}").unwrap()); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + assert!(matches!( + job.profile_status("profile-1").await, + Err(Error::Http { .. }) + )); + } + + #[tokio::test(start_paused = true)] + async fn wait_timeout_is_resumable_and_does_not_cancel_or_refresh_the_job() { + let complete = Arc::new(AtomicBool::new(false)); + let status = complete.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/profile/status"); + let value = metadata( + "gpu", + if status.load(Ordering::SeqCst) { + "complete" + } else { + "pending" + }, + ); + http::Response::builder() + .status(200) + .body(value.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + let error = job + .wait_for_profile( + "profile-1", + FunctionProfileWaitOptions::new().timeout(Duration::from_millis(50)), + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout { .. })); + assert_eq!(job.state(), None); + complete.store(true, Ordering::SeqCst); + assert_eq!( + job.wait_for_profile("profile-1", FunctionProfileWaitOptions::new()) + .await + .unwrap() + .status, + FunctionProfileStatus::Complete + ); + } + + #[tokio::test(start_paused = true)] + async fn waiting_honors_poll_interval_and_rejects_execution_changes() { + let calls = Arc::new(AtomicUsize::new(0)); + let count = calls.clone(); + let client = client_with_handler(move |_| { + let next = count.fetch_add(1, Ordering::SeqCst); + let mut value = metadata("gpu", if next == 0 { "pending" } else { "complete" }); + if next > 0 { + value["execution_epoch"] = json!(4); + } + http::Response::builder() + .status(200) + .body(value.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + let started = tokio::time::Instant::now(); + let error = job + .wait_for_profile( + "profile-1", + FunctionProfileWaitOptions::new().poll_interval(Duration::from_secs(5)), + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("execution identity")); + assert_eq!(calls.load(Ordering::SeqCst), 2); + assert!(started.elapsed() >= Duration::from_secs(5)); + } + + #[tokio::test] + async fn failed_capture_keeps_its_reason_and_is_not_a_failed_refresh() { + let client = client_with_handler(|request| { + assert_eq!(request.url().path(), "/v1/jobs/profile/status"); + http::Response::builder() + .status(200) + .body(metadata("gpu", "failed").to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + let profile = job.profile_status("profile-1").await.unwrap(); + assert_eq!(profile.status, FunctionProfileStatus::Failed); + assert_eq!(profile.error.as_deref(), Some("gpu_unavailable")); + let error = job + .wait_for_profile("profile-1", FunctionProfileWaitOptions::new()) + .await + .unwrap_err(); + assert!(matches!(error, Error::Runtime { .. })); + assert!(error.to_string().contains("gpu_unavailable")); + assert_eq!(job.state(), None); + } + + #[tokio::test] + async fn artifacts_preserve_all_supported_formats_and_truncation_after_refresh() { + for (kind, artifact) in [ + ( + "cpu", + json!({"$schema":"https://www.speedscope.app/file-format-schema.json","shared":{"frames":[{"name":"work"}]},"profiles":[],"future_field":7}), + ), + ( + "memory", + json!({"format":"lancedb.tracemalloc.v1","allocations":[{"size_bytes":4096,"frames":[]}],"truncated":false}), + ), + ( + "gpu", + json!({"format":"lancedb.cuda.v1","traceEvents":[{"cat":"kernel","name":"compute","ph":"X","ts":10,"dur":2}],"truncated":true}), + ), + ] { + let output = artifact.clone(); + let client = client_with_handler(move |request| { + let body: Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body, json!({"job_id":"job-1","profile_id":"profile-1"})); + let response = match request.url().path() { + "/v1/jobs/profile/status" => metadata(kind, "complete"), + "/v1/jobs/profile/artifact" => output.clone(), + other => panic!("retrieval must not describe or restart refresh: {other}"), + }; + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + assert_eq!(job.profile_artifact("profile-1").await.unwrap(), artifact); + } + } + + #[tokio::test] + async fn permission_missing_and_expired_errors_are_preserved_without_retry() { + for code in [403, 404, 500] { + for operation in ["capture", "status", "artifact"] { + let calls = Arc::new(AtomicUsize::new(0)); + let seen = calls.clone(); + let client = client_with_handler(move |request| { + let path = request.url().path(); + if operation == "artifact" && path.ends_with("/status") { + return http::Response::builder() + .status(200) + .body(metadata("gpu", "complete").to_string()) + .unwrap(); + } + assert_eq!(path, format!("/v1/jobs/profile/{operation}")); + seen.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(code) + .body("profile is unavailable".to_owned()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + let error = match operation { + "capture" => job + .capture_profile("worker-1", FunctionProfileOptions::default()) + .await + .unwrap_err(), + "status" => job.profile_status("profile-1").await.unwrap_err(), + _ => job.profile_artifact("profile-1").await.unwrap_err(), + }; + assert!( + matches!(error, Error::Http { status_code: Some(status), .. } if status.as_u16() == code) + ); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + } + } + + #[tokio::test] + async fn unrelated_or_incomplete_artifacts_are_not_exported_as_profiles() { + let client = client_with_handler(|request| { + let value = if request.url().path().ends_with("/status") { + metadata("gpu", "complete") + } else { + json!({"traceEvents":[]}) + }; + http::Response::builder() + .status(200) + .body(value.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + assert!(matches!( + job.profile_artifact("profile-1").await, + Err(Error::Http { .. }) + )); + let client = client_with_handler(|request| { + assert!(request.url().path().ends_with("/status")); + http::Response::builder() + .status(200) + .body(metadata("gpu", "capturing").to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + assert!(matches!( + job.profile_artifact("profile-1").await, + Err(Error::Runtime { .. }) + )); + } +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index ed2c7a70b..8dbf75aea 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -8,6 +8,8 @@ mod ipc_stream; mod optimize; mod prewarm; #[cfg(test)] +mod profile_tests; +#[cfg(test)] mod write_tests; use self::insert::{RemoteWriteExec, WriteOp}; @@ -24,7 +26,7 @@ use crate::index::Index; use crate::index::IndexStatistics; use crate::index::scalar::{FtsQuery, Operator}; use crate::index::waiter::{MAX_WAIT, wait_for_index}; -use crate::job::Job; +use crate::job::{FunctionProfile, FunctionProfileOptions, Job}; use crate::materialized_view::{MaterializedViewInfo, RefreshMaterializedViewResult}; use crate::query::wal_fusion::PkFusionMemory; // WAL-PK-FUSION: delete. use crate::query::{QueryFilter, QueryRequest, Select, VectorQueryRequest}; @@ -330,6 +332,22 @@ impl crate::job::JobHandle for FreshnessJob { crate::job::JobHandle::stack(&self.inner, worker_id).await } + async fn capture_profile( + &self, + worker_id: &str, + options: FunctionProfileOptions, + ) -> Result { + crate::job::JobHandle::capture_profile(&self.inner, worker_id, options).await + } + + async fn profile_status(&self, profile_id: &str) -> Result { + crate::job::JobHandle::profile_status(&self.inner, profile_id).await + } + + async fn profile_artifact(&self, profile_id: &str) -> Result { + crate::job::JobHandle::profile_artifact(&self.inner, profile_id).await + } + async fn events( &self, request: crate::job::JobEventsRequest, @@ -433,6 +451,22 @@ impl crate::job::JobHandle for MaterializedViewRefreshJob { crate::job::JobHandle::stack(&self.inner, worker_id).await } + async fn capture_profile( + &self, + worker_id: &str, + options: FunctionProfileOptions, + ) -> Result { + crate::job::JobHandle::capture_profile(&self.inner, worker_id, options).await + } + + async fn profile_status(&self, profile_id: &str) -> Result { + crate::job::JobHandle::profile_status(&self.inner, profile_id).await + } + + async fn profile_artifact(&self, profile_id: &str) -> Result { + crate::job::JobHandle::profile_artifact(&self.inner, profile_id).await + } + async fn events( &self, request: crate::job::JobEventsRequest, diff --git a/rust/lancedb/src/remote/table/profile_tests.rs b/rust/lancedb/src/remote/table/profile_tests.rs new file mode 100644 index 000000000..ca599402e --- /dev/null +++ b/rust/lancedb/src/remote/table/profile_tests.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde_json::json; + +use super::{FreshnessHeaders, FreshnessState, MaterializedViewRefreshJob}; +use crate::job::{ + FunctionProfileKind, FunctionProfileOptions, FunctionProfileStatus, FunctionProfileWaitOptions, + Job, +}; +use crate::materialized_view::RefreshMaterializedViewResult; +use crate::remote::client::test_utils::client_with_handler; +use crate::remote::job::RemoteJob; + +#[tokio::test] +async fn materialized_view_refresh_handles_forward_profile_operations_without_finishing_refresh() { + let client = client_with_handler(|request| { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["job_id"], "job-1"); + let action = request.url().path(); + let value = if action == "/v1/jobs/profile/artifact" { + json!({"format":"lancedb.cuda.v1", "traceEvents":[], "truncated":true}) + } else { + assert!(matches!( + action, + "/v1/jobs/profile/capture" | "/v1/jobs/profile/status" + )); + if action.ends_with("/capture") { + assert_eq!(body["worker_id"], "worker-1"); + assert_eq!(body["kind"], "gpu"); + } else { + assert_eq!(body["profile_id"], "profile-1"); + } + json!({ + "profile_id":"profile-1", "job_id":"job-1", "worker_id":"worker-1", + "execution_epoch":1, "session_slot":0, "kind":"gpu", "duration_seconds":2, + "status":if action.ends_with("/capture") { "pending" } else { "complete" }, + "requested_at_millis":1000, "deadline_at_millis":46000, + "expires_at_millis":3601000, "artifact_id":"profile-1" + }) + }; + http::Response::builder() + .status(200) + .body(value.to_string()) + .unwrap() + }); + let freshness = Arc::new(Mutex::new(FreshnessState::default())); + let job: Job = + Job::new_typed(Box::new(MaterializedViewRefreshJob { + inner: RemoteJob::new(client.clone(), "job-1".into()), + client, + db_name: "analytics".into(), + name: "view".into(), + namespace: vec![], + identifier: "view".into(), + server_version: Default::default(), + sql_client: None, + freshness: freshness.clone(), + freshness_request: FreshnessHeaders::default(), + })); + let capture = job + .capture_profile( + "worker-1", + FunctionProfileOptions::new(FunctionProfileKind::Gpu).duration(Duration::from_secs(2)), + ) + .await + .unwrap(); + assert_eq!(capture.status, FunctionProfileStatus::Pending); + assert_eq!( + job.wait_for_profile(&capture.profile_id, FunctionProfileWaitOptions::new()) + .await + .unwrap() + .status, + FunctionProfileStatus::Complete + ); + assert_eq!( + job.profile_artifact(&capture.profile_id).await.unwrap()["truncated"], + true + ); + assert_eq!(job.state(), None); + assert!(freshness.lock().unwrap().checkout_baseline.is_none()); +} From b35cce60d66e5ae58e7ef470af7bd268d22c0396 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sat, 21 Nov 2026 08:53:14 +0000 Subject: [PATCH 69/78] =?UTF-8?q?Bump=20version:=200.42.0-beta.20=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.21?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 15 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index ba0d4ebaf..1f88ee40e 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.20" +current_version = "0.42.0-beta.21" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 59cbf509e..8fb71f02a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6005,7 +6005,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.20" +version = "0.42.0-beta.21" dependencies = [ "ahash", "anyhow", @@ -6116,7 +6116,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.20" +version = "0.42.0-beta.21" dependencies = [ "anyhow", "arrow-array", @@ -6159,7 +6159,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.20" +version = "0.42.0-beta.21" dependencies = [ "arrow-array", "arrow-buffer", @@ -6185,7 +6185,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.20" +version = "0.42.0-beta.21" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index bf733dd23..237f00cde 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.20 + 0.42.0-beta.21 ``` diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 540d53c04..1c5033c73 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.20" +version = "0.42.0-beta.21" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 572858a82..b528fc57d 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.20", + "version": "0.42.0-beta.21", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 18bd9e1c4..a69f8e6c3 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.20", + "version": "0.42.0-beta.21", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 79671f79e..6b97d7e5d 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.20", + "version": "0.42.0-beta.21", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 6048d5def..f7591e824 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.20", + "version": "0.42.0-beta.21", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index 7c6e7d4a4..2e6abc68a 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.20", + "version": "0.42.0-beta.21", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 917f779fb..ebf2cd55b 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.20", + "version": "0.42.0-beta.21", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 97d3aec62..8b89322e0 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.20", + "version": "0.42.0-beta.21", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index ae6debdd1..8dd8fcb52 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.20", + "version": "0.42.0-beta.21", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 631340ce2..23da1099c 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.20" +version = "0.42.0-beta.21" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 1d83c0cd4..371b41beb 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.20" +version = "0.42.0-beta.21" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 11f1c9512..534b2b570 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.20" +version = "0.42.0-beta.21" edition = "2021" license.workspace = true repository.workspace = true From 564f8f93d44dd070305aaafc65d1dd590c7bd01d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 17:09:53 +0800 Subject: [PATCH 70/78] test(python): cover embedded plans over enterprise bases (#5150) ## Summary Clarify in the persistence guide and `persist` docstring that only the plan destination must be Embedded. The base table can be Embedded or Enterprise; an Enterprise base is pinned through the plan's recorded base branch/version. Add a focused loopback regression that persists a plan from a mock remote base into an Embedded database, reopens the plan by destination with `db.open_table`, advances the mock base's latest version to v2, and verifies a fresh remote handle observes v2 while `Permutation` still reads the plan's recorded main/v1 coordinates. Sequential iteration and duplicate/unsorted offsets follow the stored plan order, and the mock records nonempty v1 scan/gather requests. ## Verification - Focused test plus affected remote mock tests: 3 passed. - `ruff format --check` and `ruff check` passed. - `git diff --check` passed. This is a docs/test-only follow-up. It does not add Enterprise-resident plan persistence or change plan ordering. --- docs/web/training/permutation.mdx | 9 +++-- python/python/lancedb/permutation.py | 16 +++++--- python/python/tests/test_permutation.py | 49 +++++++++++++++++++++++++ python/python/tests/utils.py | 38 ++++++++++++++++--- 4 files changed, 97 insertions(+), 15 deletions(-) diff --git a/docs/web/training/permutation.mdx b/docs/web/training/permutation.mdx index 952341ea9..1f2f31596 100644 --- a/docs/web/training/permutation.mdx +++ b/docs/web/training/permutation.mdx @@ -35,6 +35,9 @@ By default a permutation table is stored in memory. Call `persist` before `execu LanceDB connection backed by local files or object storage. The plan becomes an ordinary table, so another process with access to the same storage can open it and use `Permutation.from_tables` to read the same split. +Only the plan destination must be embedded. The base table can be Embedded or Enterprise; an Enterprise base is +pinned through the plan's recorded base branch and version. + ```py Python icon=Python from lancedb.permutation import Permutation, permutation_builder @@ -57,9 +60,9 @@ reopened directly in a worker process. `mode="create"` is the default and fails when the destination table already exists. Pass `mode="overwrite"` to replace it explicitly. Overwriting writes a new table version; readers that already opened the previous version keep -reading that snapshot. Use `namespace_path` to create the plan in a namespace. Persisting to LanceDB Enterprise -connections is not supported yet, because reproducible Enterprise plan ordering requires deterministic remote row -ordering. +reading that snapshot. Use `namespace_path` to create the plan in a namespace. Persisting the plan itself to a +LanceDB Enterprise connection is not supported yet, because reproducible Enterprise plan ordering requires +deterministic remote row ordering. The plan records the base table version and branch in its schema metadata. `Permutation.base_version` and `Permutation.base_branch` read those values without querying the base table; both are `None` for older plans that did diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index 0369ccec5..ff1cf7b59 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -294,10 +294,12 @@ class PermutationBuilder: """ Store the permutation table in an embedded database. - Persisting a plan makes the same split available to another process or - another machine with access to the destination storage. The plan is an - ordinary LanceDB table containing row ids and split ids; it can be - opened with [open_table][lancedb.db.DBConnection.open_table] and passed to + The base table can be Embedded or Enterprise; this connection is only the + plan destination. Persisting a plan makes the same split available to + another process or another machine with access to the destination storage. + The plan is an ordinary LanceDB table containing row ids and split ids; it + can be opened with [open_table][lancedb.db.DBConnection.open_table] and + passed to [Permutation.from_tables][lancedb.permutation.Permutation.from_tables]. The table returned by ``execute`` keeps the destination connection and namespace context, so it can be pickled and reopened directly. @@ -305,8 +307,10 @@ class PermutationBuilder: Parameters ---------- db: DBConnection - An embedded LanceDB connection. Local files and object storage are - supported; LanceDB Enterprise connections are not supported yet. + An embedded LanceDB connection for the plan destination. Local files + and object storage are supported. The base table may be Embedded or + Enterprise; persisting the plan itself to Enterprise is not supported + yet. table_name: str The name of the permutation table to create. namespace_path: list[str], optional diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 22df4570c..1e23d6d99 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -222,6 +222,55 @@ def test_base_branch_property_reads_plan_metadata(tmp_path): assert permutation.num_rows == 20 +def test_persist_embedded_plan_for_remote_base(tmp_path): + from lancedb import deserialize_conn + + server = MockPermutationServer(num_rows=8) + db = connect(tmp_path) + + with mock_remote_table(server) as remote: + permutation_builder(remote).shuffle(seed=7).persist(db, "plan").execute() + plan = db.open_table("plan") + expected_ids = plan.to_arrow().to_pydict()["row_id"] + assert expected_ids != list(range(8)) + + # Advance the mock's latest version. A fresh handle must see v2, while + # the plan's recorded v1 still pins every read to the old snapshot. + server.publish_version(2, list(range(100, 108))) + fresh_remote = deserialize_conn( + remote._serialized_connection_state() + ).open_table(server.name) + assert fresh_remote.version == 2 + + permutation = Permutation.from_tables(fresh_remote, plan) + assert permutation.base_version == 1 + assert permutation.base_branch is None + assert permutation._plan_version == 1 + assert permutation.permutation_table.version == 1 + + sequential_ids = [ + row["id"] + for batch in permutation.iter(3, skip_last_batch=False) + for row in batch + ] + assert sequential_ids == expected_ids + assert [row["id"] for row in permutation.__getitems__([5, 1, 5, 3])] == [ + expected_ids[i] for i in [5, 1, 5, 3] + ] + + # The plan is local, but its build and gathers address the remote base + # at the recorded main/v1 snapshot. Latest describes carry no version. + assert server.scans + assert server.takes + for body in [*server.scans, *server.takes]: + assert body.get("version") == 1 + assert body.get("branch") is None + describe_versions = [body.get("version") for body in server.describe_bodies] + assert None in describe_versions + assert 1 in describe_versions + assert all(body.get("branch") is None for body in server.describe_bodies) + + def test_persisted_plan_pickle_reopens_same_snapshot_after_overwrite(tmp_path): from datetime import timedelta import pickle diff --git a/python/python/tests/utils.py b/python/python/tests/utils.py index 7c4c30b71..90ad26463 100644 --- a/python/python/tests/utils.py +++ b/python/python/tests/utils.py @@ -51,21 +51,42 @@ class MockPermutationServer: the server, which is the part that has to stay compatible. """ - def __init__(self, name="remote_data", num_rows=8, vary_scan_order=False): + def __init__( + self, name="remote_data", num_rows=8, vary_scan_order=False, latest_version=1 + ): self.name = name self.num_rows = num_rows + self.latest_version = latest_version + self.version_rows = {1: list(range(num_rows))} + self.describe_bodies = [] self.query_bodies = [] # Stand in for a distributed scan that answers in no fixed order. self.vary_scan_order = vary_scan_order self.scan_calls = 0 + def publish_version(self, version, row_ids): + """Advance the mock's latest version without changing its schema.""" + self.latest_version = version + self.version_rows[version] = list(row_ids) + + def _rows_for_version(self, requested_version): + version = ( + self.latest_version if requested_version is None else requested_version + ) + return self.version_rows.get(version, self.version_rows[1]) + def __call__(self, request): path = request.path if path == f"/v1/table/{self.name}/describe/": + body = self._read_body(request) + self.describe_bodies.append(body) + version = ( + self.latest_version if body.get("version") is None else body["version"] + ) return self._json( request, { - "version": 1, + "version": version, "schema": { "fields": [ {"name": "id", "type": {"type": "int64"}, "nullable": False} @@ -78,8 +99,8 @@ class MockPermutationServer: # Null spec: this table has no RTE write path. return self._json(request, {"rte_spec": None}) if path == f"/v1/table/{self.name}/count_rows/": - self._read_body(request) - return self._json(request, self.num_rows) + body = self._read_body(request) + return self._json(request, len(self._rows_for_version(body.get("version")))) if path == f"/v1/table/{self.name}/query/": return self._query(request, self._read_body(request)) @@ -124,10 +145,15 @@ class MockPermutationServer: def _query(self, request, body): self.query_bodies.append(body) + version_rows = self._rows_for_version(body.get("version")) if is_row_id_take(body): # A row-id take. Answer ascending, so tests prove the client reorders. - row_ids = sorted(parse_in_list(body["filter"])) + row_ids = sorted( + row_id + for row_id in parse_in_list(body["filter"]) + if row_id in version_rows + ) return self._arrow( request, pa.table( @@ -140,7 +166,7 @@ class MockPermutationServer: if body.get("columns") == ["_rowid"]: # The permutation build scan: row ids and nothing else. - row_ids = list(range(self.num_rows)) + row_ids = list(version_rows) if self.vary_scan_order and self.scan_calls % 2: row_ids.reverse() self.scan_calls += 1 From 7970d3075ca98056c10f071d6d6646363c4a943d Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Sat, 21 Nov 2026 13:52:49 -0800 Subject: [PATCH 71/78] docs: install the public CLI from the hosted script (#5139) Installing the CLI from the guide previously required a repository checkout or a manual download. The installer is available directly from the downloads site. This updates the guide and quickstart for the v0.42.0 stable release. --- docs/web/quickstart.mdx | 3 ++- docs/web/tools/cli.mdx | 25 ++++++++++++++----------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index 12a57c06f..c01686c2c 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -268,7 +268,8 @@ at the data: -See [SQL](/basics/sql) for the Flight SQL client and CLI alternatives to `execute_query()`. +To run SQL from your terminal, [install the LanceDB CLI](/tools/cli#install). +See [SQL](/basics/sql) for other Flight SQL clients. Now add a near-duplicate frame -- frame 5 is one video frame after frame 2, with an almost identical embedding -- and build the vector index that `dedupe` reads: diff --git a/docs/web/tools/cli.mdx b/docs/web/tools/cli.mdx index a225287b9..92730a9f0 100644 --- a/docs/web/tools/cli.mdx +++ b/docs/web/tools/cli.mdx @@ -1,7 +1,7 @@ --- title: "LanceDB CLI" sidebarTitle: "CLI" -description: "Connect to LanceDB, run SQL, and manage connection profiles with the lancedb command-line client." +description: "Install the LanceDB CLI, connect to a deployment, run SQL, and manage connection profiles." icon: terminal keywords: ["cli", "command line", "sql", "profiles", "authentication"] --- @@ -18,24 +18,27 @@ statements supported by your deployment. ## Install -From a repository checkout, use the shell installer to select the archive for -your machine. For example, to install a specific published beta: +On Apple Silicon macOS or Linux (x86-64 or ARM64), run the hosted installer. +It downloads the latest stable CLI for your platform, verifies the archive's +SHA-256 checksum, and installs the executable in `$HOME/.local/bin`. ```sh -LANCEDB_VERSION=v0.42.0-beta.19 sh scripts/install.sh +curl -fsSL https://downloads.lancedb.com/cli/install.sh | sh +"$HOME/.local/bin/lancedb" --version ``` -Omit `LANCEDB_VERSION` to select the latest stable GitHub release. The selected -release must include CLI archives. The installer verifies the archive checksum -and installs to `$HOME/.local/bin/lancedb`. If you already use an Enterprise CLI, -set `LANCEDB_INSTALL_DIR` to a separate absolute directory and invoke the public -client by its full path. To upgrade, move the existing executable first. +Add `$HOME/.local/bin` to your `PATH` to run `lancedb` by name. To install a +specific release, pass the tag to `sh`, for example +`curl -fsSL https://downloads.lancedb.com/cli/install.sh | LANCEDB_VERSION=v0.42.0 sh`. +If you already use the Enterprise CLI, set `LANCEDB_INSTALL_DIR` to a separate +absolute directory and invoke the public CLI by its full path. To upgrade, move +the existing executable first. ### Manual download Download a CLI archive and `SHA256SUMS` from the [LanceDB releases page](https://github.com/lancedb/lancedb/releases). The CLI -shares the SDK release version, including beta versions. +shares the SDK release version. | Platform | Target | Requirements | | --- | --- | --- | @@ -46,7 +49,7 @@ shares the SDK release version, including beta versions. Set the version and target to match your chosen release and platform: ```sh -CLI_VERSION=X.Y.Z # Replace with the release version, for example X.Y.Z-beta.N +CLI_VERSION=0.42.0 # Replace with the release version you want CLI_TARGET=aarch64-apple-darwin CLI_STEM="lancedb-v${CLI_VERSION}-${CLI_TARGET}" CLI_RELEASE_URL="https://github.com/lancedb/lancedb/releases/download/v${CLI_VERSION}" From e3e55844bc6b73c14c8d5dfaf44f1d1387f9440e Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sat, 21 Nov 2026 14:35:04 -0800 Subject: [PATCH 72/78] fix: add SQL query timeout and cancellation controls Add per-query SQL deadlines, read timeouts, and drop cancellation controls for Rust and Python. --- docs/src/python/python.md | 23 +- docs/web/basics/sql.mdx | 47 +++ python/python/lancedb/_lancedb.pyi | 3 + python/python/lancedb/db.py | 43 ++- python/python/lancedb/namespace.py | 12 + python/python/lancedb/remote/db.py | 6 + python/python/tests/test_sql.py | 86 +++++- python/src/connection.rs | 14 +- rust/lancedb/src/connection.rs | 28 ++ rust/lancedb/src/database.rs | 3 + rust/lancedb/src/remote/db.rs | 3 + rust/lancedb/src/remote/sql.rs | 230 ++++++++++++-- rust/lancedb/src/remote/sql/function.rs | 3 + .../src/remote/sql/materialized_view.rs | 2 + rust/lancedb/src/remote/sql/objects.rs | 1 + rust/lancedb/src/remote/sql/secret.rs | 3 + rust/lancedb/src/remote/sql/stream.rs | 58 +++- rust/lancedb/src/remote/sql/view.rs | 2 + rust/lancedb/src/remote/sql_test.rs | 290 +++++++++++++++++- rust/lancedb/src/remote/table.rs | 5 + rust/lancedb/src/sql.rs | 24 +- 21 files changed, 834 insertions(+), 52 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 32afe3d77..47a20aa57 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -306,7 +306,8 @@ call or return a polling continuation that the SDK follows automatically. This behavior is the same with and without parameters. Open the reader directly; a directly streamed query needs its reader to make progress. Dropping an unread handle or its reader stops direct streaming. Deferred execution continues until -explicitly cancelled. +explicitly cancelled by default; use `cancel_on_drop=True` to attempt cancellation +when its unread handle or reader is dropped. For example: @@ -360,6 +361,26 @@ reader = db.execute_query( # await query.cancel() ``` +Set `timeout` to bound submission and result consumption together, including +any time before opening a reader. Set `read_timeout` to limit each server read. +Both accept `datetime.timedelta` and apply to one execution. An expired timeout +or failed result read stops reading and attempts to cancel Flight execution. +Cancellation on drop requires the submitting runtime to remain alive. Durable +server-side jobs require explicit `db.cancel_job(query.job_id)`. + +```python +from datetime import timedelta + +query = db.execute_query_async( + "SELECT * FROM events", + timeout=timedelta(seconds=30), + read_timeout=timedelta(seconds=5), + cancel_on_drop=True, +) +# To stop this execution explicitly: +query.cancel() +``` + ## Namespaces (Synchronous) A namespace-backed connection resolves tables through a diff --git a/docs/web/basics/sql.mdx b/docs/web/basics/sql.mdx index 89f465e65..42615191f 100644 --- a/docs/web/basics/sql.mdx +++ b/docs/web/basics/sql.mdx @@ -247,6 +247,53 @@ cancellation. Background operations such as index builds return a [job](/basics/jobs) handle instead. Use the API for the returned handle to check status and retrieve results. +### Timeouts and cancellation {#query-timeouts} + +Rust and Python SQL executions support per-query limits. Python's synchronous +and asynchronous connections accept the same keyword arguments: + +```python +from datetime import timedelta + +query = db.execute_query_async( + "SELECT frame_id, caption FROM frames", + timeout=timedelta(seconds=30), + read_timeout=timedelta(seconds=5), + cancel_on_drop=True, +) +# Cancel explicitly if these results are no longer needed. +query.cancel() +``` + +`timeout` starts at submission and covers result consumption, including time +before opening a reader. `read_timeout` overrides the connection's limit for each +server read. Expiry stops reads and attempts to cancel Flight execution. The +execution deadline is also sent to the server on result-streaming RPCs. + +By default, deferred queries can be detached. `cancel_on_drop=True` attempts +cancellation when an unread handle or its reader is dropped; it requires the +submitting runtime to remain alive. Directly streamed queries always stop on +drop. With an asynchronous Python connection, await submission and +`query.cancel()`. + +Rust exposes the same controls on the submission builder: + +```rust +use std::time::Duration; + +let query = db.execute_query_async("SELECT frame_id, caption FROM frames") + .timeout(Duration::from_secs(30)) + .read_timeout(Duration::from_secs(5)) + .cancel_on_drop(true) + .execute() + .await?; +query.cancel().await?; +``` + +These options cancel Flight execution. A durable server-side job can outlive its +Flight waiter; cancel it explicitly with `db.cancel_job(query.job_id)` in Python, +or `Connection::cancel_job` in Rust. + ## Query plans {#query-plans} Use query plans to understand how LanceDB reads data, applies filters and uses diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 6632b2acf..01e7a3369 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -324,6 +324,9 @@ class Connection(object): *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[pa.RecordBatch] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> SqlQuery: ... async def describe_query(self, query_id: UUID) -> QueryDescription: ... async def create_table( diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 6de3e050c..4d5840527 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1717,6 +1717,9 @@ class DBConnection(EnforceOverrides): *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> pa.RecordBatchReader: """Execute SQL and return a blocking Arrow reader. @@ -1731,6 +1734,9 @@ class DBConnection(EnforceOverrides): query, default_namespace_path=default_namespace_path, parameters=parameters, + timeout=timeout, + read_timeout=read_timeout, + cancel_on_drop=cancel_on_drop, ).reader() def execute_query_async( @@ -1739,6 +1745,9 @@ class DBConnection(EnforceOverrides): *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> SqlQuery: """Start executing SQL and return its query handle. @@ -1764,13 +1773,24 @@ class DBConnection(EnforceOverrides): With or without parameters, the server chooses whether to stream rows on the initial call or return a polling continuation. The reader follows either path transparently. Dropping an unread handle or its reader - stops a directly streamed query; deferred execution requires explicit - cancellation. Open ``reader()`` directly: a streamed query needs its - reader to make progress and reports ``running`` until the stream ends. + stops a directly streamed query. Set ``cancel_on_drop=True`` to also + attempt cancellation of deferred Flight execution when its unread handle + or reader is dropped. By default, deferred queries can be detached. + Open ``reader()`` directly: a streamed query needs its reader to make + progress and reports ``running`` until the stream ends. Once a server-side SQL job exists, ``describe().job_id`` exposes its durable Job Registry id while the query is still running. This is separate from the connection-scoped query ``id``. + ``timeout`` limits submission and result consumption together, starting + when the query is submitted. It also applies before a reader is opened. + ``read_timeout`` overrides the connection's limit for each server read. + Both accept ``datetime.timedelta``. On expiry or a failed result read, + the SDK stops reading and attempts to cancel Flight execution. + Cancellation on drop is best effort and requires the connection's runtime + to remain alive. Durable server-side jobs require explicit + ``cancel_job(query.job_id)`` regardless of these options. + LanceDB Embedded connections do not support SQL. """ raise NotImplementedError( @@ -4630,6 +4650,9 @@ class AsyncConnection(object): *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> AsyncRecordBatchReader: """Execute SQL and return an asynchronous Arrow reader. @@ -4644,6 +4667,9 @@ class AsyncConnection(object): query, default_namespace_path=default_namespace_path, parameters=parameters, + timeout=timeout, + read_timeout=read_timeout, + cancel_on_drop=cancel_on_drop, ) return await submitted.reader() @@ -4653,6 +4679,9 @@ class AsyncConnection(object): *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> AsyncSqlQuery: """Start executing SQL and return its query handle. @@ -4660,6 +4689,11 @@ class AsyncConnection(object): references. The namespace defaults to ``["public"]``. ``parameters`` binds values to ``$1`` / ``$name`` placeholders; see [DBConnection.execute_query_async][lancedb.db.DBConnection.execute_query_async]. + ``timeout`` covers submission through result consumption, including + time before opening a reader. ``read_timeout`` limits each server read. + ``cancel_on_drop=True`` also attempts to cancel deferred Flight execution + when its unread handle or reader is dropped. See the synchronous method + above for cancellation and durable-job behavior. LanceDB Embedded connections raise ``NotImplementedError``. """ return AsyncSqlQuery( @@ -4667,6 +4701,9 @@ class AsyncConnection(object): query, default_namespace_path=default_namespace_path, parameters=to_parameter_batch(parameters), + timeout=timeout, + read_timeout=read_timeout, + cancel_on_drop=cancel_on_drop, ) ) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 4c8ec1a62..ff75c22f1 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -1732,12 +1732,18 @@ class AsyncLanceNamespaceDBConnection: *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> AsyncRecordBatchReader: """Execute SQL when supported by the underlying connection.""" return await self._inner.execute_query( query, default_namespace_path=default_namespace_path, parameters=parameters, + timeout=timeout, + read_timeout=read_timeout, + cancel_on_drop=cancel_on_drop, ) async def execute_query_async( @@ -1746,6 +1752,9 @@ class AsyncLanceNamespaceDBConnection: *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> AsyncSqlQuery: """Start executing SQL when supported by the underlying connection. @@ -1755,6 +1764,9 @@ class AsyncLanceNamespaceDBConnection: query, default_namespace_path=default_namespace_path, parameters=parameters, + timeout=timeout, + read_timeout=read_timeout, + cancel_on_drop=cancel_on_drop, ) async def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription: diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 4061db3e1..1e550b003 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1421,6 +1421,9 @@ class RemoteDBConnection(DBConnection): *, default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, + timeout: Optional[timedelta] = None, + read_timeout: Optional[timedelta] = None, + cancel_on_drop: bool = False, ) -> SqlQuery: """Start executing SQL through this LanceDB Enterprise connection. @@ -1436,6 +1439,9 @@ class RemoteDBConnection(DBConnection): query, default_namespace_path=default_namespace_path, parameters=parameters, + timeout=timeout, + read_timeout=read_timeout, + cancel_on_drop=cancel_on_drop, ) ) ) diff --git a/python/python/tests/test_sql.py b/python/python/tests/test_sql.py index a479fa5d1..fc6f94ad0 100644 --- a/python/python/tests/test_sql.py +++ b/python/python/tests/test_sql.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import threading +from datetime import timedelta from uuid import UUID import numpy as np @@ -13,6 +14,7 @@ from lancedb import _lancedb from lancedb.arrow import AsyncRecordBatchReader from lancedb.db import AsyncConnection from lancedb.remote.db import RemoteDBConnection +from lancedb.namespace import AsyncLanceNamespaceDBConnection from lancedb.sql import AsyncQuery, Query, to_parameter_batch NIL_QUERY_ID = UUID(int=0) @@ -22,24 +24,46 @@ class FakeNativeQuery: id = UUID("0198f1b2-c3d4-7e5f-8123-456789abcdef") job_id = None + def __init__(self): + self.cancelled = False + async def reader(self): return pa.table({"value": [1, 2]}) + async def cancel(self): + self.cancelled = True + class FakeNativeConnection: def __init__(self): self.parameters = [] + self.options = [] async def execute_query_async( - self, query, *, default_namespace_path=None, parameters=None + self, + query, + *, + default_namespace_path=None, + parameters=None, + timeout=None, + read_timeout=None, + cancel_on_drop=False, ): self.parameters.append(parameters) + self.options.append((timeout, read_timeout, cancel_on_drop)) return FakeNativeQuery() class FakeAsyncConnection: async def execute_query_async( - self, query, *, default_namespace_path=None, parameters=None + self, + query, + *, + default_namespace_path=None, + parameters=None, + timeout=None, + read_timeout=None, + cancel_on_drop=False, ): return AsyncQuery(FakeNativeQuery()) @@ -401,3 +425,61 @@ def test_sql_input_error_metadata_crosses_native_boundary(job_id): assert error.grpc_code == 3 assert str(error).startswith("No column 'missing' in table events") assert not str(error).startswith("SQL error") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["execute_query", "execute_query_async"]) +async def test_async_sql_execution_controls_are_forwarded(method): + native = FakeNativeConnection() + connection = AsyncConnection(native) + await getattr(connection, method)( + "SELECT 1", + timeout=timedelta(seconds=30), + read_timeout=timedelta(seconds=5), + cancel_on_drop=True, + ) + assert native.options == [(timedelta(seconds=30), timedelta(seconds=5), True)] + + +@pytest.mark.parametrize("method", ["execute_query", "execute_query_async"]) +def test_sync_sql_execution_controls_are_forwarded(method): + native = FakeNativeConnection() + connection = RemoteDBConnection.__new__(RemoteDBConnection) + connection._conn = AsyncConnection(native) + getattr(connection, method)( + "SELECT 1", + timeout=timedelta(seconds=30), + read_timeout=timedelta(seconds=5), + cancel_on_drop=True, + ) + assert native.options == [(timedelta(seconds=30), timedelta(seconds=5), True)] + + +@pytest.mark.asyncio +async def test_async_query_cancellation_reaches_the_native_handle(): + native = FakeNativeQuery() + await AsyncQuery(native).cancel() + assert native.cancelled + + +def test_sync_query_cancellation_reaches_the_native_handle(): + native = FakeNativeQuery() + Query(AsyncQuery(native)).cancel() + assert native.cancelled + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["execute_query", "execute_query_async"]) +async def test_namespace_sql_execution_controls_are_forwarded(method): + native = FakeNativeConnection() + connection = AsyncLanceNamespaceDBConnection.__new__( + AsyncLanceNamespaceDBConnection + ) + connection._inner = AsyncConnection(native) + await getattr(connection, method)( + "SELECT 1", + timeout=timedelta(seconds=30), + read_timeout=timedelta(seconds=5), + cancel_on_drop=True, + ) + assert native.options == [(timedelta(seconds=30), timedelta(seconds=5), True)] diff --git a/python/src/connection.rs b/python/src/connection.rs index 40e3c7b42..3d1ad6d30 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -375,19 +375,29 @@ impl Connection { self.get_inner().map(|inner| inner.uri().to_string()) } - #[pyo3(signature = (query, *, default_namespace_path=None, parameters=None))] + #[pyo3(signature = (query, *, default_namespace_path=None, parameters=None, timeout=None, read_timeout=None, cancel_on_drop=false))] pub fn execute_query_async<'a>( self_: PyRef<'a, Self>, query: String, default_namespace_path: Option>, parameters: Option>, + timeout: Option, + read_timeout: Option, + cancel_on_drop: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let default_namespace_path = parse_default_namespace_path(default_namespace_path)?; future_into_py(self_.py(), async move { let mut operation = inner .execute_query_async(query) - .default_namespace_path(default_namespace_path); + .default_namespace_path(default_namespace_path) + .cancel_on_drop(cancel_on_drop); + if let Some(timeout) = timeout { + operation = operation.timeout(timeout); + } + if let Some(timeout) = read_timeout { + operation = operation.read_timeout(timeout); + } if let Some(PyArrowType(parameters)) = parameters { operation = operation.parameters(parameters); } diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index d413b2b78..ac742eec7 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -5,6 +5,7 @@ use std::collections::HashMap; use std::sync::Arc; +use std::time::Duration; use arrow_array::RecordBatch; use arrow_schema::SchemaRef; @@ -427,6 +428,33 @@ impl ExecuteQueryAsyncBuilder { } } + /// Limit this execution from submission through result consumption. + /// + /// Expiry stops result reads and attempts to cancel Flight execution, even + /// if no reader was opened. It does not cancel durable server-side jobs. + /// Without this option, the connection's existing timeout settings apply. + pub fn timeout(mut self, timeout: Duration) -> Self { + self.request.options.timeout = Some(timeout); + self + } + + /// Override the connection's timeout for each server read on this query. + pub fn read_timeout(mut self, timeout: Duration) -> Self { + self.request.options.read_timeout = Some(timeout); + self + } + + /// Cancel deferred Flight execution when its unread handle or reader is dropped. + /// + /// This is best effort and requires the submitting Tokio runtime to remain + /// alive. Defaults to false, allowing deferred queries to be detached. + /// Directly streamed queries already stop on drop. Durable jobs require + /// explicit job cancellation regardless of this setting. + pub fn cancel_on_drop(mut self, cancel: bool) -> Self { + self.request.options.cancel_on_drop = cancel; + self + } + /// Set the namespace used for unqualified table names. /// /// An empty path is treated as `public`, which is the SQL name for the diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index b89c9f95e..b021bf0ee 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -212,6 +212,8 @@ pub struct ExecuteQueryRequest { /// also binds `$`. See /// [`ExecuteQueryAsyncBuilder::parameters`](crate::connection::ExecuteQueryAsyncBuilder::parameters). pub parameters: Option, + /// Execution limits and cancellation behavior for this statement. + pub options: crate::sql::QueryOptions, } impl ExecuteQueryRequest { @@ -220,6 +222,7 @@ impl ExecuteQueryRequest { query: query.into(), default_namespace_path: vec!["public".to_string()], parameters: None, + options: Default::default(), } } } diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 2e91fc15d..f17bcc2b0 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1008,6 +1008,7 @@ impl Database for RemoteDatabase { query: sql, default_namespace_path: namespace_path.to_vec(), parameters: None, + options: Default::default(), }) .await?; integration_sql::decode_info(&result.reader().await?.try_collect::>().await?) @@ -1024,6 +1025,7 @@ impl Database for RemoteDatabase { query: format!("DESCRIBE STORAGE INTEGRATION {name}"), default_namespace_path: namespace_path.to_vec(), parameters: None, + options: Default::default(), }) .await?; integration_sql::decode_info(&result.reader().await?.try_collect::>().await?) @@ -1046,6 +1048,7 @@ impl Database for RemoteDatabase { query: format!("DROP STORAGE INTEGRATION {name}"), default_namespace_path: namespace_path.to_vec(), parameters: None, + options: Default::default(), }) .await?; result.reader().await?.try_collect::>().await?; diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index f5e053f9f..b2ca5651f 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -51,8 +51,10 @@ const DEFAULT_SQL_PORT: u16 = 10025; const DEFAULT_SQL_TLS_PORT: u16 = 10026; const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(120); const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(300); +const AUTOMATIC_CANCELLATION_TIMEOUT: Duration = Duration::from_secs(5); const STATUS_POLL_TIMEOUT: Duration = Duration::from_secs(1); const MIN_POLL_INTERVAL: Duration = Duration::from_millis(50); +const MAX_SQL_TIMEOUT: Duration = Duration::from_secs(99_999_999 * 60 * 60); const MAX_SQL_MESSAGE_SIZE: usize = 1024 * 1024 * 1024; const SQL_JOB_ID_METADATA_KEY: &str = "x-lancedb-sql-job-id"; const TERMINAL_QUERY_RETENTION: Duration = Duration::from_secs(300); @@ -69,6 +71,7 @@ pub(super) struct SubmittedQuery { pub(super) materialized_view_job_handle_supported: bool, } +#[derive(Clone)] struct SqlClientInner { database: String, database_prefix: Option, @@ -77,6 +80,8 @@ struct SqlClientInner { sql_host_override: Option, client_config: ClientConfig, client: Arc>, + deadline: Option, + cancel_on_drop: bool, } struct SqlConnection { @@ -213,6 +218,8 @@ impl SqlClient { sql_host_override, client_config, client: Arc::new(OnceCell::new()), + deadline: None, + cancel_on_drop: false, }), queries: Arc::new(QueryRegistry::new()), } @@ -279,12 +286,34 @@ impl SqlClient { request: ExecuteQueryRequest, materialized_view_job_handle: bool, ) -> Result { - let timeout = self.inner.overall_timeout()?; + let mut client = self.inner.as_ref().clone(); + client.deadline = request + .options + .timeout + .map(|timeout| { + if timeout > MAX_SQL_TIMEOUT { + return Err(Error::InvalidInput { + message: "SQL query timeout exceeds the gRPC limit".to_string(), + }); + } + tokio::time::Instant::now() + .checked_add(timeout) + .ok_or_else(|| Error::InvalidInput { + message: "SQL query timeout is too large".to_string(), + }) + }) + .transpose()?; + client.cancel_on_drop = request.options.cancel_on_drop; + if let Some(read_timeout) = request.options.read_timeout { + client.client_config.timeout_config.read_timeout = Some(read_timeout); + } + let client = Arc::new(client); + let timeout = client.execution_timeout()?; with_overall_timeout(timeout, "SQL query submission", async { validate_namespace_path(&request.default_namespace_path)?; let query_id = Uuid::now_v7(); let opened = StreamingQuery::open( - self.inner.clone(), + client.clone(), &request.query, request.parameters, &request.default_namespace_path, @@ -300,24 +329,26 @@ impl SqlClient { Submission::Stream(response) => { let query = Arc::new(StreamingQuery::new( query_id, - self.inner.clone(), + client.clone(), response, job_id.clone(), )); self.queries .insert(query_id, RegisteredQuery::Streamed(query.clone())); + query.start_deadline(); Query::new(Arc::new(StreamingQueryHandle::new(query))) } Submission::Deferred(poll_info) => { let query = Arc::new(RemoteQuery::new( query_id, - self.inner.clone(), + client.clone(), request.default_namespace_path, poll_info, job_id, )?); self.queries .insert(query_id, RegisteredQuery::Polled(query.clone())); + query.start_deadline(); Query::new(Arc::new(RemoteQueryHandle::new(query))) } }; @@ -375,6 +406,7 @@ impl SqlClient { query: statement, default_namespace_path: namespace, parameters: None, + options: Default::default(), }) .await?, ); @@ -417,6 +449,21 @@ impl SqlClient { } impl SqlClientInner { + fn execution_timeout(&self) -> Result> { + match self.deadline { + Some(deadline) => Ok(Some( + deadline.saturating_duration_since(tokio::time::Instant::now()), + )), + None => self.overall_timeout(), + } + } + + fn set_execution_timeout(&self, request: &mut Request) { + if let Some(deadline) = self.deadline { + request.set_timeout(deadline.saturating_duration_since(tokio::time::Instant::now())); + } + } + fn overall_timeout(&self) -> Result> { resolve_timeout( self.client_config.timeout_config.timeout, @@ -561,6 +608,7 @@ impl SqlClientInner { .clone(); let mut request = Request::new(ticket); *request.metadata_mut() = metadata; + self.set_execution_timeout(&mut request); let response = tokio::time::timeout(read_timeout, connection.client.clone().do_get(request)) .await @@ -801,6 +849,10 @@ struct RemoteQuery { last_accessed: StdMutex, lifecycle: StdMutex, cancel_request_uncertain: Arc, + failure: StdMutex>, + cleanup_started: AtomicBool, + runtime: tokio::runtime::Handle, + deadline_task: StdMutex>, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -843,9 +895,75 @@ impl RemoteQuery { last_accessed: StdMutex::new(Instant::now()), lifecycle: StdMutex::new(lifecycle), cancel_request_uncertain: Arc::new(AtomicBool::new(false)), + failure: StdMutex::new(None), + cleanup_started: AtomicBool::new(false), + runtime: tokio::runtime::Handle::current(), + deadline_task: StdMutex::new(None), }) } + fn start_deadline(self: &Arc) { + let Some(deadline) = self.client.deadline else { + return; + }; + let query = Arc::downgrade(self); + let task = self.runtime.spawn(async move { + tokio::time::sleep_until(deadline).await; + if let Some(query) = query.upgrade() + && !matches!( + query.lifecycle(), + QueryLifecycle::Completed | QueryLifecycle::Cancelled + ) + { + query.fail(&sql_result_timeout()); + } + }); + *self.deadline_task.lock().unwrap() = Some(task.abort_handle()); + } + + fn stop_deadline(&self) { + if let Some(task) = self.deadline_task.lock().unwrap().take() { + task.abort(); + } + } + + fn fail(self: &Arc, error: &Error) { + let lifecycle = self.lifecycle.lock().unwrap(); + if matches!( + *lifecycle, + QueryLifecycle::Completed | QueryLifecycle::Cancelled | QueryLifecycle::Cancelling + ) { + return; + } + self.failure + .lock() + .unwrap() + .get_or_insert_with(|| match error { + Error::Runtime { message } => message.clone(), + other => other.to_string(), + }); + drop(lifecycle); + self.stop_deadline(); + self.mark_terminal(); + self.cancelled.notify_waiters(); + self.cancel_in_background(); + } + + fn cancel_in_background(self: &Arc) { + if matches!( + self.lifecycle(), + QueryLifecycle::Completed | QueryLifecycle::Cancelled + ) || self.cleanup_started.swap(true, Ordering::SeqCst) + { + return; + } + let query = self.clone(); + self.runtime.spawn(async move { + let _ = + tokio::time::timeout(AUTOMATIC_CANCELLATION_TIMEOUT, query.cancel_inner()).await; + }); + } + fn registry_expired(&self, abandoned: bool) -> bool { if let Some(finished) = self.terminal_at.get() { return finished.elapsed() >= TERMINAL_QUERY_RETENTION; @@ -882,6 +1000,7 @@ impl RemoteQuery { } *lifecycle = QueryLifecycle::Cancelled; drop(lifecycle); + self.stop_deadline(); self.mark_terminal(); self.cancelled.notify_waiters(); self.state_changed.notify_waiters(); @@ -916,13 +1035,17 @@ impl RemoteQuery { fn mark_result_completed(&self) -> Result<()> { let mut lifecycle = self.lifecycle.lock().unwrap(); - if matches!( - *lifecycle, - QueryLifecycle::Cancelling | QueryLifecycle::Cancelled - ) { + if self.failure.lock().unwrap().is_some() + || matches!( + *lifecycle, + QueryLifecycle::Cancelling | QueryLifecycle::Cancelled + ) + { return Err(self.cancelled_error()); } *lifecycle = QueryLifecycle::Completed; + drop(lifecycle); + self.stop_deadline(); Ok(()) } @@ -931,13 +1054,20 @@ impl RemoteQuery { } fn is_cancellation_requested(&self) -> bool { - matches!( - self.lifecycle(), - QueryLifecycle::Cancelling | QueryLifecycle::Cancelled - ) + let failed = self.failure.lock().unwrap().is_some(); + failed + || matches!( + self.lifecycle(), + QueryLifecycle::Cancelling | QueryLifecycle::Cancelled + ) } fn cancelled_error(&self) -> Error { + if let Some(message) = self.failure.lock().unwrap().as_ref() { + return Error::Runtime { + message: message.clone(), + }; + } Error::JobCancelled { job_id: Some(self.id.to_string()), } @@ -1214,6 +1344,9 @@ impl RemoteQuery { async fn describe_inner(&self) -> Result { self.touch(); + if self.failure.lock().unwrap().is_some() { + return Err(self.cancelled_error()); + } if self.is_cancellation_requested() { let state = self.state.lock().await.clone(); return query_description(self.id, self.job_id(), &state, self.lifecycle()); @@ -1380,6 +1513,14 @@ impl RemoteQuery { } } +struct CancelQueryOnDrop(Arc); + +impl Drop for CancelQueryOnDrop { + fn drop(&mut self) { + self.0.cancel_in_background(); + } +} + struct RemoteQueryHandle { query: Arc, result_started: AtomicBool, @@ -1394,6 +1535,14 @@ impl RemoteQueryHandle { } } +impl Drop for RemoteQueryHandle { + fn drop(&mut self) { + if self.query.client.cancel_on_drop && !self.result_started.load(Ordering::SeqCst) { + self.query.cancel_in_background(); + } + } +} + #[async_trait::async_trait] impl QueryHandle for RemoteQueryHandle { fn id(&self) -> Uuid { @@ -1410,7 +1559,10 @@ impl QueryHandle for RemoteQueryHandle { } async fn reader(&self) -> Result { - let timeout = self.query.client.overall_timeout()?; + let timeout = self.query.client.execution_timeout()?; + if self.query.failure.lock().unwrap().is_some() { + return Err(self.query.cancelled_error()); + } if self .result_started .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) @@ -1421,9 +1573,22 @@ impl QueryHandle for RemoteQueryHandle { }); } let result_start = ResultStartGuard::new(&self.result_started); + let cancel_on_drop = self + .query + .client + .cancel_on_drop + .then(|| CancelQueryOnDrop(self.query.clone())); let started = Instant::now(); let prepared = - with_overall_timeout(timeout, "SQL query result", self.query.prepare_result()).await?; + match with_overall_timeout(timeout, "SQL query result", self.query.prepare_result()) + .await + { + Ok(prepared) => prepared, + Err(error) => { + self.query.fail(&error); + return Err(error); + } + }; let remaining_timeout = timeout.map(|timeout| timeout.saturating_sub(started.elapsed())); let schema = prepared.schema.clone(); let (sender, receiver) = mpsc::channel(2); @@ -1433,19 +1598,17 @@ impl QueryHandle for RemoteQueryHandle { let result = with_overall_timeout( remaining_timeout, "SQL query result", - query.run_result_stream(prepared, sender), + query.clone().run_result_stream(prepared, sender), ) .await; if let Err(error) = result { + query.fail(&error); let _ = error_sender.send(Err(error)).await; } }); - let stream = futures::stream::unfold(receiver, |mut receiver| async move { - receiver.recv().await.map(|item| (item, receiver)) - }); result_start.commit(); - let stream: SendableRecordBatchStream = - Box::pin(SimpleRecordBatchStream::new(stream, schema)); + let stream = + sql_result_stream(receiver, schema, self.query.client.deadline, cancel_on_drop); Ok(match self.job_id() { Some(job_id) => attach_sql_job_id(stream, &job_id), None => stream, @@ -1457,6 +1620,33 @@ impl QueryHandle for RemoteQueryHandle { } } +fn sql_result_timeout() -> Error { + Error::Runtime { + message: "SQL query result timed out".to_string(), + } +} + +fn sql_result_stream( + receiver: mpsc::Receiver>, + schema: SchemaRef, + deadline: Option, + guard: G, +) -> SendableRecordBatchStream { + let stream = futures::stream::unfold(Some((receiver, guard)), move |state| async move { + let (mut receiver, guard) = state?; + let item = match deadline { + Some(deadline) => tokio::select! { + biased; + _ = tokio::time::sleep_until(deadline) => return Some((Err(sql_result_timeout()), None)), + item = receiver.recv() => item, + }, + None => receiver.recv().await, + }; + item.map(|item| (item, Some((receiver, guard)))) + }); + Box::pin(SimpleRecordBatchStream::new(stream, schema)) +} + fn query_description( id: Uuid, job_id: Option, diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index f0ebf1894..f2a12a024 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -51,6 +51,7 @@ impl SqlClient { ), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, definition, ) @@ -76,6 +77,7 @@ impl SqlClient { ), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, definition, ) @@ -119,6 +121,7 @@ impl SqlClient { ), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, |batches| { let rows = strings(&batches, "status")?; diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index c8e1aa5c3..eb29e62af 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -55,6 +55,7 @@ impl SqlClient { query: statement, default_namespace_path: namespace, parameters: None, + options: Default::default(), }, true, ) @@ -133,6 +134,7 @@ impl SqlClient { query: format!("DESCRIBE MATERIALIZED VIEW {}", quote_identifier(name)), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }) .await?; let mut reader = query.reader().await?; diff --git a/rust/lancedb/src/remote/sql/objects.rs b/rust/lancedb/src/remote/sql/objects.rs index 2ffb08936..482fa46de 100644 --- a/rust/lancedb/src/remote/sql/objects.rs +++ b/rust/lancedb/src/remote/sql/objects.rs @@ -54,6 +54,7 @@ impl SqlClient { query: statement, default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }) .await?; let reader = query.reader().await?; diff --git a/rust/lancedb/src/remote/sql/secret.rs b/rust/lancedb/src/remote/sql/secret.rs index 93c2a6c6e..14c08e94b 100644 --- a/rust/lancedb/src/remote/sql/secret.rs +++ b/rust/lancedb/src/remote/sql/secret.rs @@ -83,6 +83,7 @@ impl SqlClient { ), default_namespace_path: namespace.to_vec(), parameters: Some(parameters), + options: Default::default(), }, |_| Ok(()), ) @@ -102,6 +103,7 @@ impl SqlClient { query: format!("DESCRIBE SECRET {}", quote_identifier(name)), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, secret_info, ) @@ -121,6 +123,7 @@ impl SqlClient { query: format!("DROP SECRET IF EXISTS {}", quote_identifier(name)), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, |_| Ok(()), ) diff --git a/rust/lancedb/src/remote/sql/stream.rs b/rust/lancedb/src/remote/sql/stream.rs index 16155bf7c..b5315353f 100644 --- a/rust/lancedb/src/remote/sql/stream.rs +++ b/rust/lancedb/src/remote/sql/stream.rs @@ -21,9 +21,9 @@ use uuid::Uuid; use super::{ ABANDONED_QUERY_RETENTION, DEFAULT_READ_TIMEOUT, ResultEndpointStream, ResultStartGuard, SqlClientInner, TERMINAL_QUERY_RETENTION, resolve_timeout, sql_error, sql_flight_error, - sql_status_error, with_overall_timeout, + sql_result_stream, sql_status_error, with_overall_timeout, }; -use crate::arrow::{SendableRecordBatchStream, SimpleRecordBatchStream}; +use crate::arrow::SendableRecordBatchStream; use crate::error::{Error, Result}; use crate::sql::{QueryDescription, QueryHandle, QueryStatus}; @@ -56,6 +56,7 @@ pub(super) struct StreamingQuery { terminal_at: OnceLock, last_accessed: StdMutex, job_id: StdMutex>, + deadline_task: StdMutex>, } struct PreparedStream { @@ -183,11 +184,13 @@ impl StreamingQuery { .map_err(|error| sql_flight_error(&request_id, &error))?; let mut request = tonic::Request::new(futures::stream::iter(messages)); *request.metadata_mut() = metadata; + client.set_execution_timeout(&mut request); tokio::time::timeout(read_timeout, flight.do_exchange(request)).await } else { let mut request = tonic::Request::new(Ticket::new(CommandTicket { command }.encode_to_vec())); *request.metadata_mut() = metadata; + client.set_execution_timeout(&mut request); tokio::time::timeout(read_timeout, flight.do_get(request)).await } .map_err(|_| sql_error(&request_id, "SQL query submission timed out"))? @@ -271,9 +274,30 @@ impl StreamingQuery { terminal_at: OnceLock::new(), last_accessed: StdMutex::new(Instant::now()), job_id: StdMutex::new(job_id.filter(|job_id| !job_id.is_empty())), + deadline_task: StdMutex::new(None), } } + pub(super) fn start_deadline(self: &Arc) { + let Some(deadline) = self.client.deadline else { + return; + }; + let query = Arc::downgrade(self); + let task = tokio::spawn(async move { + tokio::time::sleep_until(deadline).await; + if let Some(query) = query.upgrade() { + query.settle(Lifecycle::Failed("SQL query result timed out".to_string())); + query.response.lock().unwrap().take(); + } + }); + *self.deadline_task.lock().unwrap() = Some(task.abort_handle()); + } + + #[cfg(test)] + pub(super) fn deadline_stopped(&self) -> bool { + self.deadline_task.lock().unwrap().is_none() + } + pub(super) fn touch(&self) { *self.last_accessed.lock().unwrap() = Instant::now(); } @@ -328,11 +352,18 @@ impl StreamingQuery { *lifecycle = state; drop(lifecycle); let _ = self.terminal_at.set(Instant::now()); + if let Some(task) = self.deadline_task.lock().unwrap().take() { + task.abort(); + } + self.cancelled.notify_waiters(); true } fn is_cancelled(&self) -> bool { - *self.lifecycle.lock().unwrap() == Lifecycle::Cancelled + matches!( + *self.lifecycle.lock().unwrap(), + Lifecycle::Cancelled | Lifecycle::Failed(_) + ) } fn job_id(&self) -> Option { @@ -359,6 +390,11 @@ impl StreamingQuery { } fn cancelled_error(&self) -> Error { + if let Lifecycle::Failed(message) = &*self.lifecycle.lock().unwrap() { + return Error::Runtime { + message: message.clone(), + }; + } Error::JobCancelled { job_id: Some(self.id.to_string()), } @@ -377,13 +413,7 @@ impl StreamingQuery { /// Take the rows and wait for the first batch, which carries the schema. async fn prepare(&self) -> Result { let Some(rows) = self.response.lock().unwrap().take() else { - // Taken by an earlier attempt that failed, or dropped by a cancel. - return Err(match &*self.lifecycle.lock().unwrap() { - Lifecycle::Failed(message) => Error::Runtime { - message: message.clone(), - }, - _ => self.cancelled_error(), - }); + return Err(self.cancelled_error()); }; let mut rows = Borrowed { query: self, @@ -518,7 +548,7 @@ impl QueryHandle for StreamingQueryHandle { } async fn reader(&self) -> Result { - let timeout = self.query.client.overall_timeout()?; + let timeout = self.query.client.execution_timeout()?; if self .result_started .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) @@ -559,12 +589,8 @@ impl QueryHandle for StreamingQueryHandle { let _ = error_sender.send(Err(error)).await; } }); - let stream = futures::stream::unfold(receiver, |mut receiver| async move { - receiver.recv().await.map(|item| (item, receiver)) - }); result_start.commit(); - let stream: SendableRecordBatchStream = - Box::pin(SimpleRecordBatchStream::new(stream, schema)); + let stream = sql_result_stream(receiver, schema, self.query.client.deadline, ()); Ok(match self.job_id() { Some(job_id) => super::attach_sql_job_id(stream, &job_id), None => stream, diff --git a/rust/lancedb/src/remote/sql/view.rs b/rust/lancedb/src/remote/sql/view.rs index b058269a0..ca09c4b5d 100644 --- a/rust/lancedb/src/remote/sql/view.rs +++ b/rust/lancedb/src/remote/sql/view.rs @@ -111,6 +111,7 @@ impl SqlClient { ), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, move |batches| view_description(batches, namespace_path), ) @@ -132,6 +133,7 @@ impl SqlClient { query: format!("DESCRIBE VIEW {}", quote_identifier(name)), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, move |batches| view_description(batches, namespace_path), ) diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index eb70e87ac..7f1767ff1 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -116,6 +116,7 @@ struct CapturedHeaders { api_key: String, database_prefix: String, materialized_view_job_handle: Option, + grpc_timeout: Option, } /// Every exchange's statement and the parameter row it arrived with. @@ -138,6 +139,7 @@ struct TestSqlService { first_continuation_count: Arc, transient_poll_failures: Arc, headers: Arc>>, + result_deadlines: Arc>>>, gate_refresh_release: Arc, exchanges: ReceivedExchanges, result_overrides: Arc>>, @@ -172,6 +174,9 @@ impl TestSqlService { .to_string() }; self.headers.lock().unwrap().push(CapturedHeaders { + grpc_timeout: metadata + .get("grpc-timeout") + .map(|value| value.to_str().unwrap().to_owned()), database: header("database"), namespace_path: header("namespace-path"), request_id: header("x-request-id"), @@ -315,6 +320,7 @@ impl Default for TestSqlService { first_continuation_count: Arc::new(AtomicUsize::new(0)), transient_poll_failures: Arc::new(AtomicUsize::new(0)), headers: Arc::new(std::sync::Mutex::new(Vec::new())), + result_deadlines: Arc::new(std::sync::Mutex::new(Vec::new())), gate_refresh_release: Arc::new(Notify::new()), exchanges: Arc::new(std::sync::Mutex::new(Vec::new())), result_overrides: Arc::new(std::sync::Mutex::new(HashMap::new())), @@ -533,6 +539,14 @@ impl FlightService for TestSqlService { PROTOCOL_VERSION ); } + if initial.is_none() { + self.result_deadlines.lock().unwrap().push( + request + .metadata() + .get("grpc-timeout") + .map(|value| value.to_str().unwrap().to_owned()), + ); + } let query = initial .as_ref() .map(|command| command.query.as_bytes()) @@ -1584,6 +1598,7 @@ async fn fast_durable_job_failure_exposes_the_same_job_id_on_the_query_handle() query: "SELECT durable job failure".into(), default_namespace_path: vec![], parameters: None, + options: Default::default(), }) .await .unwrap(); @@ -1937,10 +1952,12 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { .delay_next .store(true, Ordering::SeqCst); assert_overall_timeout(collect_result(&timeout_query).await, "result"); - timeout_header_provider - .delay_next - .store(true, Ordering::SeqCst); - assert_overall_timeout(timeout_query.cancel().await, "cancellation"); + wait_for( + &cancel_count, + 1, + "the overall timeout must cancel execution", + ) + .await; timeout_query.cancel().await.unwrap(); let pre_dispatch_timeout = timeout_client @@ -2346,7 +2363,14 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { .submit("SELECT fail", &["public".to_string()]) .await .unwrap(); + let before_failure = cancel_count.load(Ordering::SeqCst); assert!(collect_result(&failed).await.is_err()); + wait_for( + &cancel_count, + before_failure + 1, + "failed result reads must cancel execution", + ) + .await; let registry = QueryRegistry::new(); for descriptor in ["active-one", "active-two"] { @@ -2411,7 +2435,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { assert_eq!(client.initialized_client_count().await, 1); assert_eq!(query_count.load(Ordering::SeqCst), 21); assert_eq!(do_get_count.load(Ordering::SeqCst), 17); - assert_eq!(cancel_count.load(Ordering::SeqCst), 15); + assert_eq!(cancel_count.load(Ordering::SeqCst), 16); assert_eq!(first_result, vec![expected.clone()]); assert!(empty_result.is_empty()); assert!(client.describe(Uuid::nil()).await.is_err()); @@ -5066,3 +5090,259 @@ async fn remote_cleanup_preview_uses_sql_without_job_calls() { ); shutdown.send(()).unwrap(); } + +#[tokio::test] +async fn sql_deadline_expires_unread_streamed_and_deferred_queries() { + for deferred in [false, true] { + for parameters in [None, Some(parameter_row())] { + let service = TestSqlService { + adaptive: true, + defer: deferred, + ..TestSqlService::default() + }; + let cancellations = service.cancel_count.clone(); + let headers = service.headers.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT slow get"); + request.parameters = parameters; + request.options.timeout = Some(Duration::from_secs(3)); + let query = client.execute(request).await.unwrap(); + assert!(headers.lock().unwrap()[0].grpc_timeout.is_some()); + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(4)).await; + tokio::task::yield_now().await; + tokio::time::resume(); + assert_overall_timeout(query.describe().await, "result"); + assert_overall_timeout(client.describe(query.id()).await, "result"); + assert_overall_timeout(query.reader().await, "result"); + if deferred { + wait_for( + &cancellations, + 1, + "expiry must cancel deferred execution without a reader", + ) + .await; + } + let ordinary = client + .execute(ExecuteQueryRequest::new("SELECT 1")) + .await + .unwrap(); + assert!( + !collect_result(&ordinary).await.unwrap().is_empty(), + "query options must not change the connection defaults" + ); + } + } +} + +#[tokio::test] +async fn a_deferred_result_timeout_sends_cancellation() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..TestSqlService::default() + }; + let cancellations = service.cancel_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT slow get"); + request.options.timeout = Some(Duration::from_secs(3)); + let query = client.execute(request).await.unwrap(); + tokio::time::pause(); + tokio::time::advance(Duration::from_millis(2_900)).await; + let result = query.reader().await; + tokio::time::resume(); + assert_overall_timeout(result, "result"); + wait_for( + &cancellations, + 1, + "a deferred reader timeout must cancel execution", + ) + .await; +} + +#[tokio::test] +async fn sql_read_timeout_is_per_query_and_cancels_deferred_execution() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..TestSqlService::default() + }; + let cancellations = service.cancel_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT slow get"); + request.options.read_timeout = Some(Duration::from_millis(100)); + let query = client.execute(request).await.unwrap(); + let error = collect_result(&query).await.unwrap_err(); + assert!( + error.to_string().contains("SQL result read timed out"), + "{error}" + ); + wait_for( + &cancellations, + 1, + "a read timeout must cancel deferred execution", + ) + .await; + let next = client + .execute(ExecuteQueryRequest::new("SELECT slow get")) + .await + .unwrap(); + assert!(!collect_result(&next).await.unwrap().is_empty()); +} + +#[tokio::test] +async fn deferred_cancellation_on_drop_is_opt_in() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..TestSqlService::default() + }; + let cancellations = service.cancel_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let detached = client + .execute(ExecuteQueryRequest::new("SELECT 1")) + .await + .unwrap(); + let id = detached.id(); + drop(detached); + assert_eq!( + client.describe(id).await.unwrap().status, + QueryStatus::Finished + ); + assert_eq!(cancellations.load(Ordering::SeqCst), 0); + let mut request = ExecuteQueryRequest::new("SELECT 1"); + request.options.cancel_on_drop = true; + let query = client.execute(request).await.unwrap(); + let id = query.id(); + // Drop outside the async runtime, as Python garbage collection may do. + std::thread::spawn(move || drop(query)).join().unwrap(); + wait_for(&cancellations, 1, "dropping an opted-in handle must cancel").await; + assert_eq!( + client.describe(id).await.unwrap().status, + QueryStatus::Cancelled + ); +} + +#[tokio::test] +async fn deferred_reader_owns_cancellation_after_the_handle_is_dropped() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..TestSqlService::default() + }; + let cancellations = service.cancel_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT slow"); + request.options.cancel_on_drop = true; + let query = client.execute(request).await.unwrap(); + let rows = query.reader().await.unwrap(); + drop(query); + assert_eq!( + cancellations.load(Ordering::SeqCst), + 0, + "an active reader must survive dropping its query handle" + ); + drop(rows); + wait_for( + &cancellations, + 1, + "dropping the reader must cancel deferred execution", + ) + .await; +} + +#[tokio::test] +async fn a_completed_query_is_not_cancelled_on_drop_or_deadline() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..TestSqlService::default() + }; + let cancellations = service.cancel_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT 1"); + request.options.timeout = Some(Duration::from_secs(3)); + request.options.cancel_on_drop = true; + let query = client.execute(request).await.unwrap(); + assert!(!collect_result(&query).await.unwrap().is_empty()); + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(4)).await; + tokio::task::yield_now().await; + tokio::time::resume(); + assert_eq!( + query.describe().await.unwrap().status, + QueryStatus::Finished + ); + drop(query); + assert_eq!(cancellations.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn sql_deadline_applies_to_buffered_results_and_stops_its_timer_on_completion() { + for deferred in [false, true] { + let service = TestSqlService { + adaptive: true, + defer: deferred, + ..TestSqlService::default() + }; + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT 1"); + request.options.timeout = Some(Duration::from_secs(3)); + let query = client.execute(request).await.unwrap(); + let mut rows = query.reader().await.unwrap(); + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!( + query.describe().await.unwrap().status, + QueryStatus::Finished + ); + match client.queries.get(query.id()).unwrap() { + RegisteredQuery::Polled(query) => { + assert!(query.deadline_task.lock().unwrap().is_none()) + } + RegisteredQuery::Streamed(query) => assert!(query.deadline_stopped()), + } + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(4)).await; + tokio::time::resume(); + assert_overall_timeout(rows.try_next().await, "result"); + assert!(rows.try_next().await.unwrap().is_none()); + } +} + +#[tokio::test] +async fn sql_deadline_is_forwarded_to_deferred_result_requests() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..TestSqlService::default() + }; + let deadlines = service.result_deadlines.clone(); + let headers = service.headers.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT 1"); + request.options.timeout = Some(Duration::from_secs(3)); + let query = client.execute(request).await.unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(!collect_result(&query).await.unwrap().is_empty()); + let deadlines = deadlines.lock().unwrap(); + let result_deadline = deadlines[0] + .as_deref() + .expect("the result request must carry an execution deadline"); + assert_ne!( + Some(result_deadline), + headers.lock().unwrap()[0].grpc_timeout.as_deref(), + "the timeout budget must not restart for the result request" + ); +} + +#[tokio::test] +async fn sql_rejects_timeouts_that_cannot_be_encoded_by_grpc() { + let (client, _shutdown) = + start_sql_service(TestSqlService::default(), ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT 1"); + request.options.timeout = Some(Duration::from_secs(u64::MAX)); + assert!(matches!( + client.execute(request).await, + Err(Error::InvalidInput { .. }) + )); +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 8dbf75aea..6b46c45fc 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4237,6 +4237,7 @@ impl BaseTable for RemoteTable { query: statement, default_namespace_path: self.namespace.clone(), parameters: None, + options: Default::default(), }) .await .map_err(cleanup::map_error)?; @@ -4266,6 +4267,7 @@ impl BaseTable for RemoteTable { query: statement, default_namespace_path: self.namespace.clone(), parameters: None, + options: Default::default(), }) .await .map_err(cleanup::map_error)?; @@ -4298,6 +4300,7 @@ impl BaseTable for RemoteTable { query: statement, default_namespace_path: self.namespace.clone(), parameters: None, + options: Default::default(), }) .await .map_err(optimize::map_optimize_error)?; @@ -4958,6 +4961,7 @@ impl BaseTable for RemoteTable { query: statement, default_namespace_path: self.namespace.clone(), parameters: options.parameters, + options: Default::default(), }) .await .map_err(prewarm::map_error)?; @@ -4997,6 +5001,7 @@ impl BaseTable for RemoteTable { query: statement, default_namespace_path: self.namespace.clone(), parameters: options.parameters, + options: Default::default(), }) .await .map_err(prewarm::map_explain_error)?; diff --git a/rust/lancedb/src/sql.rs b/rust/lancedb/src/sql.rs index bda5df085..88195aff2 100644 --- a/rust/lancedb/src/sql.rs +++ b/rust/lancedb/src/sql.rs @@ -3,7 +3,7 @@ //! Handles to SQL queries running on a LanceDB Enterprise database. -use std::{fmt, sync::Arc}; +use std::{fmt, sync::Arc, time::Duration}; use async_trait::async_trait; use chrono::{DateTime, Utc}; @@ -11,6 +11,23 @@ use uuid::Uuid; use crate::{Result, arrow::SendableRecordBatchStream}; +/// Controls for one SQL execution. +#[non_exhaustive] +#[derive(Clone, Debug, Default)] +pub struct QueryOptions { + /// Limit submission and result consumption together, starting at submission. + /// On expiry, the SDK stops reading and attempts to cancel Flight execution. + /// Durable server-side jobs still require explicit job cancellation. + pub timeout: Option, + /// Limit each wait for a server response or the next result batch. + /// Defaults to the connection's read timeout. + pub read_timeout: Option, + /// Attempt to cancel deferred Flight execution when its unread handle or + /// reader is dropped. Defaults to false so deferred queries can be detached. + /// Directly streamed queries always stop when their reader is dropped. + pub cancel_on_drop: bool, +} + /// The externally visible lifecycle state of a submitted SQL query. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum QueryStatus { @@ -73,8 +90,9 @@ pub(crate) trait QueryHandle: Send + Sync { /// The handle can be inspected, opened as an Arrow reader, or cancelled. /// The server may stream results on the initial call or defer execution and /// return result tickets. Dropping an unread handle or its reader stops a -/// directly streamed query; deferred execution continues until explicitly -/// cancelled. This applies equally with and without parameters. +/// directly streamed query. Deferred execution continues until cancelled, +/// unless a timeout or `cancel_on_drop` was set on its execution builder. +/// This applies equally with and without parameters. /// [`Self::id`] is scoped to the connection that submitted the query. When the /// server runs the statement as a SQL job, [`Self::job_id`] exposes the durable /// Job Registry identifier accepted by `open_job`. From 2b1b2a29dd9600f0ebcf8d8fed665d1bdb2cb669 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sat, 21 Nov 2026 15:04:34 -0800 Subject: [PATCH 73/78] feat!: layer GPU settings and total execution limits (#5146) BREAKING CHANGE: Resource inputs use the same names at Function registration, column/MV creation, and refresh. Use total_cpu_millis, total_memory_bytes, and total_gpu_count for execution-wide worker budgets, plus gpu_class and positive gpu_count for each worker. Replace budget dictionary inputs and unprefixed aggregate limits with these fields. Move existing refresh gpu_count caps to total_gpu_count; gpu_count now selects devices per worker. Each setting resolves independently: refresh > column/MV creation > Function annotation > deployment. Creation settings also apply to initial MV population and automatic refresh. MVs sum total budgets across distinct pinned Function versions; per-worker GPU counts use the largest Function default unless overridden. An unset GPU class resolves to gpu_class="any" after inheritance; an explicit "any" overrides a registered concrete class. Use gpu_class="default" to pin the default pool explicitly. ```python @function( gpu=True, gpu_class="h100", gpu_count=2, total_cpu_millis=8000, total_memory_bytes=16 * 1024**3, total_gpu_count=4, ) def embed(text: str) -> list[float]: ... version = db.create_function(embed) table.add_columns( {"embedding": version(text=col("text"))}, gpu_class="any", gpu_count=1, total_gpu_count=8, ) table.refresh_column_async( "embedding", gpu_class="h100", gpu_count=4, total_gpu_count=8, ) mv = db.create_materialized_view( "embeddings", query="SELECT embed(text) AS embedding FROM documents", gpu_class="any", gpu_count=2, total_gpu_count=8, ) mv.refresh(gpu_count=4, total_gpu_count=8) ``` ```mermaid flowchart TD R["Refresh settings"] --> E["Effective settings, resolved per field"] D["Column or MV creation settings"] --> E F["Function settings"] --> E C["Deployment defaults"] --> E E --> W["GPU class and device count per worker"] E --> T["Total CPU, memory and GPU ceilings"] ``` Pinned Function images retain their identity. Registration GPU counts are defaults; execution overrides determine worker allocation. Admission rejects GPU counts below an image's minimum requirement or above the total budget. Python, Rust, SQL/REST and supported TypeScript operations use the same resource model. No local builds or tests, as requested; regression coverage runs in CI. --- docs/src/js/classes/Connection.md | 10 + docs/src/js/classes/MaterializedView.md | 10 + docs/src/js/classes/Table.md | 28 +- docs/src/js/globals.md | 1 - .../FunctionWorkerResourceBudget.md | 39 --- .../src/js/interfaces/RefreshColumnOptions.md | 46 +++- docs/web/curation/create-function.mdx | 90 ++++++- .../add-computed-column.mdx | 41 +-- .../feature-engineering/refresh-column.mdx | 84 +++--- .../refresh-materialized-view.mdx | 57 +++-- docs/web/management/function.mdx | 4 +- docs/web/sql/ddl/function.mdx | 7 +- docs/web/sql/ddl/materialized-view.mdx | 20 ++ docs/web/sql/dml/refresh-column.mdx | 16 +- .../web/sql/dml/refresh-materialized-view.mdx | 18 +- nodejs/__test__/materialized_view.test.ts | 29 ++- nodejs/__test__/remote.test.ts | 87 +++---- nodejs/__test__/table.test.ts | 5 +- nodejs/lancedb/connection.ts | 35 +++ nodejs/lancedb/index.ts | 1 - nodejs/lancedb/materialized_view.ts | 28 ++ nodejs/lancedb/table.ts | 48 ++-- nodejs/src/connection.rs | 45 ++++ nodejs/src/table.rs | 107 ++++---- python/python/lancedb/_lancedb.pyi | 44 +++- python/python/lancedb/db.py | 101 ++++++++ python/python/lancedb/functions.py | 124 ++++++--- python/python/lancedb/materialized_view.py | 102 ++++---- python/python/lancedb/namespace.py | 40 +++ python/python/lancedb/remote/db.py | 35 +++ python/python/lancedb/remote/table.py | 28 +- python/python/lancedb/resources.py | 48 ++++ python/python/lancedb/table.py | 240 +++++++++++------- .../tests/test_first_class_function_slice1.py | 38 ++- .../tests/test_first_class_function_slice2.py | 90 ++++++- .../python/tests/test_materialized_views.py | 58 ++++- python/python/tests/test_remote_db.py | 89 ++----- python/python/tests/test_table.py | 10 +- python/src/connection.rs | 48 +++- python/src/table.rs | 198 +++++++-------- rust/lancedb/src/function.rs | 153 ++++++++++- rust/lancedb/src/materialized_view.rs | 142 ++++++++--- rust/lancedb/src/remote/db.rs | 33 +++ rust/lancedb/src/remote/sql_test.rs | 68 ++++- rust/lancedb/src/remote/table.rs | 87 ++++--- rust/lancedb/src/table.rs | 10 +- rust/lancedb/src/table/add_columns.rs | 34 ++- rust/lancedb/src/table/computed_columns.rs | 240 +++++++++++------- rust/lancedb/src/table/refresh.rs | 137 +++++++--- .../tests/first_class_function_slice2.rs | 3 + 50 files changed, 2110 insertions(+), 946 deletions(-) delete mode 100644 docs/src/js/interfaces/FunctionWorkerResourceBudget.md create mode 100644 python/python/lancedb/resources.py diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index 83c182cf2..06be760ef 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -196,10 +196,20 @@ it can be queried, indexed and searched, and it appears in `tableNames`. * **options?** +* **options.gpuClass?**: `string` + +* **options.gpuCount?**: `number` + * **options.limit?**: `number` * **options.select?**: [`MaterializedViewSelect`](../type-aliases/MaterializedViewSelect.md) +* **options.totalCpuMillis?**: `number` + +* **options.totalGpuCount?**: `number` + +* **options.totalMemoryBytes?**: `number` + * **options.where?**: `string` * **options.withNoData?**: `boolean` diff --git a/docs/src/js/classes/MaterializedView.md b/docs/src/js/classes/MaterializedView.md index 3ba4d56b3..7543a2f9d 100644 --- a/docs/src/js/classes/MaterializedView.md +++ b/docs/src/js/classes/MaterializedView.md @@ -78,8 +78,18 @@ source-version pinning. Their results leave `mode`, `rowsWritten`, and * **options.full?**: `boolean` +* **options.gpuClass?**: `string` + +* **options.gpuCount?**: `number` + * **options.sourceVersion?**: `number` +* **options.totalCpuMillis?**: `number` + +* **options.totalGpuCount?**: `number` + +* **options.totalMemoryBytes?**: `number` + #### Returns `Promise`<[`RefreshMaterializedViewResult`](../interfaces/RefreshMaterializedViewResult.md)> diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 781f7b24a..a1618c47b 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1480,26 +1480,18 @@ LanceDB Enterprise it is the server's backfill job. `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`, - `maxConcurrency`, `resourceBudget`, `supervisorResources`, + `maxConcurrency`, `totalCpuMillis`, `totalMemoryBytes`, `supervisorResources`, `planningWorkers` and `maxExecutorProcessesPerWorker` size registered Function refreshes. `retryPolicy` overrides user-code retries only when repeating partial work is safe; set `maxAttempts: 1` to disable retries. `maxConcurrency` overrides the registered default for this logical execution only and is a positive integer; it is not an account-wide - quota. A `resourceBudget` requires `cpuMillis` and - `memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function. - `supervisorResources` and each `planningWorkers.resources` entry require - positive `cpuMillis`, `memoryBytes` and `ephemeralStorageBytes`. - `planningWorkers` also requires positive `maxWorkers`, - `rowsPerWorker` and `fragmentsPerWorker`. - The budget applies only to this explicit refresh and does not configure - a later automatic refresh. - `gpuCount` at the top level is the shorthand that preserves the - deployment defaults for CPU and memory, and cannot be combined with - `resourceBudget`. `numWorkers` applies only to expression columns; use - `resourceBudget` for registered Functions. All are LanceDB Enterprise - only; a LanceDB Embedded refresh rejects every option other than - `batchSize`, `gpuClass` and `gpuCount`. + quota. `totalCpuMillis`, `totalMemoryBytes`, and `totalGpuCount` override + their corresponding execution-wide resource limits independently. Unset + values inherit column defaults, then Function defaults, then deployment + defaults. A zero GPU limit is valid for CPU-only Functions. + `supervisorResources` and `planningWorkers.resources` are per-pod sizes. + `numWorkers` applies only to expression columns. `publicationIntervalRows` opts into publishing completed Function split ranges once their accumulated unpublished rows reach the threshold. It must be a positive safe integer and requires non-Blob Function outputs. @@ -1515,10 +1507,8 @@ LanceDB Enterprise it is the server's backfill job. ```ts const job = await table.refreshColumnAsync("embedding", { where: "published_at > '2026-01-01'", - resourceBudget: { - cpuMillis: 8000, - memoryBytes: 16 * 1024 ** 3, - }, + totalCpuMillis: 8000, + totalMemoryBytes: 16 * 1024 ** 3, maxConcurrency: 4, publicationIntervalRows: 10000, errorPolicy: "skip", diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 9f7ed53e4..79ebf0f13 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -115,7 +115,6 @@ - [FunctionRefreshPlanningConfig](interfaces/FunctionRefreshPlanningConfig.md) - [FunctionRefreshPodResources](interfaces/FunctionRefreshPodResources.md) - [FunctionRetryPolicy](interfaces/FunctionRetryPolicy.md) -- [FunctionWorkerResourceBudget](interfaces/FunctionWorkerResourceBudget.md) - [HnswPqOptions](interfaces/HnswPqOptions.md) - [HnswSqOptions](interfaces/HnswSqOptions.md) - [IndexConfig](interfaces/IndexConfig.md) diff --git a/docs/src/js/interfaces/FunctionWorkerResourceBudget.md b/docs/src/js/interfaces/FunctionWorkerResourceBudget.md deleted file mode 100644 index 0352bc833..000000000 --- a/docs/src/js/interfaces/FunctionWorkerResourceBudget.md +++ /dev/null @@ -1,39 +0,0 @@ -[**@lancedb/lancedb**](../README.md) • **Docs** - -*** - -[@lancedb/lancedb](../globals.md) / FunctionWorkerResourceBudget - -# Interface: FunctionWorkerResourceBudget - -Aggregate worker resources for one Enterprise Function refresh. - -## Properties - -### cpuMillis - -```ts -cpuMillis: number; -``` - -Aggregate CPU budget in millicores; 1000 is one CPU. - -*** - -### gpuCount? - -```ts -optional gpuCount: number; -``` - -Aggregate GPU budget. Omitted means zero, a CPU-only refresh. - -*** - -### memoryBytes - -```ts -memoryBytes: number; -``` - -Aggregate memory budget in bytes. diff --git a/docs/src/js/interfaces/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md index 07157e4ab..4a5b256f7 100644 --- a/docs/src/js/interfaces/RefreshColumnOptions.md +++ b/docs/src/js/interfaces/RefreshColumnOptions.md @@ -8,8 +8,7 @@ Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores -`batchSize`, `gpuClass` and `gpuCount` and rejects the rest, including -`resourceBudget`. +`batchSize`, `gpuClass` and `totalGpuCount` and rejects the rest. ## Properties @@ -50,7 +49,7 @@ GPU class for Function workers. optional gpuCount: number; ``` -Positive aggregate GPU budget for Function workers. +Positive GPU count allocated to each Function worker. *** @@ -140,17 +139,6 @@ Requires LanceDB Enterprise with non-Blob Function outputs. *** -### resourceBudget? - -```ts -optional resourceBudget: FunctionWorkerResourceBudget; -``` - -Complete aggregate CPU and memory budget for a registered Function -refresh. `gpuCount` inside the budget defaults to zero. - -*** - ### retryPolicy? ```ts @@ -181,6 +169,36 @@ CPU, memory, and ephemeral-storage limits for the refresh supervisor. *** +### totalCpuMillis? + +```ts +optional totalCpuMillis: number; +``` + +Override the total CPU budget in millicores for this refresh. + +*** + +### totalGpuCount? + +```ts +optional totalGpuCount: number; +``` + +Nonnegative total GPU budget for Function workers. + +*** + +### totalMemoryBytes? + +```ts +optional totalMemoryBytes: number; +``` + +Override the total memory budget in bytes for this refresh. + +*** + ### where? ```ts diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 1e26f778f..2f822ae10 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -194,8 +194,9 @@ and remote-API Functions both build on below. `db.list_gpu_classes()` lists the GPU classes configured for the deployment. Each record reports the operator's hardware description and limits; it does not mean a GPU is currently free. Listing requires the System Usage -permission. Pass a returned class name to `gpu_class` to fix that placement -in the Function version. `gpu=True` remains required: +permission. Pass a returned class name to `gpu_class`, such as `gpu=True, gpu_class="a10g", gpu_count=2`, +to select a pool; `gpu_count` controls the GPUs allocated together to each worker. +`gpu_count` defaults to one. Omitting `gpu` uses CPU workers: ```python Python icon="python" @@ -242,9 +243,29 @@ longest observed call. The 600 seconds above is one working GPU example, not a universal recommendation. Older servers that do not implement `GET /v1/gpu/classes` raise -`NotImplementedError`. Without `gpu_class`, the deployment's default GPU -class is used. The class is immutable with the Function version; set a -per-refresh class or aggregate GPU budget through +`NotImplementedError`. With `gpu=True`, omitting `gpu_class` accepts any +eligible configured class, equivalent to `gpu_class="any"`. Use +`gpu_class="default"` to request the default pool explicitly. Class names +must be lowercase. Counts +must be positive integers; the deployment must have a node that can supply +that many devices together. `max_gpu_count_per_worker` in the class inventory +is the operator's cap; an unset cap does not promise unlimited hardware. +Use `gpu=True, gpu_class="any", gpu_count=2` when any configured GPU class is acceptable, but each +worker needs two devices together. `gpu=True, gpu_class="any"` requests one GPU. The server +selects a class that fits the request using operator-configured limits, +preferring known multi-GPU limits over unspecified limits. The selected +class is fixed for the worker cohort; selection does not reserve capacity +until the worker is scheduled. `gpu=True, gpu_count=2` makes the same request +as `gpu=True, gpu_class="any", gpu_count=2`. A Function with an `any` request +can share a SQL job with a +Function pinned to a class; that job uses the pinned class. + +The request is immutable with the Function version. Configure tensor +parallelism in the model separately, for example vLLM's +`tensor_parallel_size=2` for `gpu=True, gpu_class="a10g", gpu_count=2`. + +The refresh `total_gpu_count` is a separate aggregate budget across workers and +must be at least the Function's per-worker count. Set it through [`refresh_column_async`](/feature-engineering/refresh-column#resources). The model loads once per worker instance, in `__init__`; `__call__` only @@ -480,3 +501,62 @@ as `bytes`; this feature does not add streamed outputs. Filling the column a Function is bound to, and re-filling it as inputs change. + + +## Default execution budgets + +`total_cpu_millis`, `total_memory_bytes`, and +`total_gpu_count` supply execution-wide defaults. CPU is in millicores +(1000 = one core), memory is in bytes, and GPU count is a total across workers. +All five resource settings use the same names at registration, creation, and +refresh. Each resolves independently in this order: + +1. The refresh's value. +2. The column or materialized view's value. +3. The registered Function's value. +4. The deployment default for total budgets and device count; any eligible + configured GPU class when no layer specifies one. + +For a materialized view using multiple Functions, the third layer adds the +`total_*` budgets across distinct pinned Function versions. Its per-worker GPU +count uses the largest Function default, and GPU classes must be compatible +unless the declaration or refresh overrides the class. Calling the same version +more than once counts it once. Column and view defaults also apply when the +service schedules a refresh automatically. Integer overflow or a budget that +cannot fit a required worker is rejected. + +```python +@function( + gpu=True, + gpu_class="h100", + gpu_count=2, + total_cpu_millis=8000, + total_memory_bytes=16 * 1024**3, + total_gpu_count=4, +) +def embed(text: str) -> list[float]: ... + +version = db.create_function(embed) +table.add_columns( + {"embedding": version(text=col("text"))}, + gpu_class="any", + gpu_count=1, + total_gpu_count=8, +) +table.refresh_column("embedding", gpu_class="h100", gpu_count=4, total_gpu_count=8) + +db.create_materialized_view( + "embeddings", query="SELECT embed(text) AS embedding FROM documents", + total_cpu_millis=16000, + gpu_class="any", + gpu_count=2, + total_gpu_count=8, +) +``` + +`gpu_class` selects the GPU pool and `gpu_count` selects the positive number +of devices allocated together to each worker. Both can be overridden at +column/MV creation and refresh. An explicit `gpu_class="any"` replaces a +registered class with any eligible configured pool. These settings require a +GPU Function for computed columns. The `total_*` values are ceilings for the +whole worker fleet. CPU and memory can limit the fleet before it reaches its GPU ceiling. diff --git a/docs/web/feature-engineering/add-computed-column.mdx b/docs/web/feature-engineering/add-computed-column.mdx index 7cc9f6988..730d0081e 100644 --- a/docs/web/feature-engineering/add-computed-column.mdx +++ b/docs/web/feature-engineering/add-computed-column.mdx @@ -71,45 +71,46 @@ Both a Function application and a SQL expression accept `auto_refresh_enabled` and `auto_refresh_interval_seconds`, and both refresh and toggle the same way; see [Auto Refresh](/enterprise/auto-refresh). -Python and Rust Function declarations can also set -`auto_refresh_resource_budget` to give their automatic refreshes an aggregate -CPU, memory, and optional GPU budget. CPU and memory are required. The nested -`gpu_count` defaults to zero, so omitting it requests CPU-only workers: +Function declarations can set `total_cpu_millis`, +`total_memory_bytes`, and `total_gpu_count`. Each optional +value supplies a default for both manual and automatic refreshes. `gpu_class` +and `gpu_count` similarly override the Function's per-worker GPU defaults. ```python Python icon="python" table.add_columns( {"caption": version(jpeg=col("jpeg"))}, - auto_refresh_resource_budget={ - "cpu_millis": 8000, - "memory_bytes": 16 * 1024**3, - }, + total_cpu_millis=8000, + total_memory_bytes=16 * 1024**3, + total_gpu_count=4, + gpu_class="any", + gpu_count=2, ) ``` ```rust Rust icon="rust" +use lancedb::table::computed_columns::ComputedColumnOptions; + table .add_columns() .function(function_application) .computed_options(ComputedColumnOptions { - auto_refresh_enabled: true, - auto_refresh_interval_seconds: None, - auto_refresh_resource_budget: Some( - FunctionWorkerResourceBudget::new(8000, 17_179_869_184), - ), + total_cpu_millis: Some(8000), + total_memory_bytes: Some(16 * 1024_u64.pow(3)), + total_gpu_count: Some(4), + gpu_class: Some("any".into()), + gpu_count: Some(2), + ..Default::default() }) .execute() .await?; ``` -This setting applies to every output in the Function binding. SQL-expression -columns do not use Function workers, so they reject -`auto_refresh_resource_budget` instead of accepting an option that has no -effect. The separate `resource_budget` refresh option configures one explicit -refresh and does not change this automatic-refresh declaration. The Node.js -SDK does not currently expose a Function declaration through `addColumns`, so -this option is not added to an unsupported surface. +Refresh values with the same names override these column defaults. Unspecified column +values inherit the pinned Function's `total_*` settings, then the +deployment defaults. The GPU budget must fit one Function worker. These +settings apply to registered Function columns in LanceDB Enterprise. ## Fill a column with a SQL expression {#expressions} diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index de0b56888..9a7e0e452 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -333,7 +333,7 @@ too slow or too expensive: ```sql SQL icon="database" REFRESH COLUMN embedding ON documents - WITH (cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2) + WITH (total_cpu_millis = 8000, total_memory_bytes = 17179869184, total_gpu_count = 2) ``` @@ -342,75 +342,65 @@ up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the fleet. They are not per-worker allocations or a guaranteed worker count. `num_workers` is only accepted for SQL-expression columns; registered Function columns reject it. -In particular, `gpu_count = 2` does not request two devices inside one Python +In particular, `total_gpu_count = 2` does not request two devices inside one Python process or enable tensor parallelism. Inspect configured GPU classes and their per-worker limits with `db.list_gpu_classes()` or `SHOW GPU CLASSES`. Choose a model that fits the worker shape supported by your deployment; see [GPU placement and budgets](/enterprise/function-operations#gpu). -The SDKs accept the same nested budget. CPU and memory are required; the GPU -count inside the budget defaults to zero, so a CPU-only Function can omit it: +The SDKs expose the same independent total limits: ```python Python icon="python" job = table.refresh_column_async( "embedding", - resource_budget={ - "cpu_millis": 8000, - "memory_bytes": 16 * 1024**3, - }, + total_cpu_millis=8000, + total_memory_bytes=16 * 1024**3, + total_gpu_count=2, ) job.wait() ``` ```rust Rust icon="rust" -use lancedb::table::{ - FunctionWorkerResourceBudget, - RefreshColumnOptions, -}; +use lancedb::table::RefreshColumnOptions; let _job = table .refresh_column_async_with_options( "embedding", - RefreshColumnOptions::default().resource_budget( - FunctionWorkerResourceBudget::new(8000, 17_179_869_184), - ), + RefreshColumnOptions::default() + .total_cpu_millis(8000) + .total_memory_bytes(17_179_869_184) + .total_gpu_count(2), ) .await?; ``` ```typescript TypeScript icon="typescript" const job = await table.refreshColumnAsync("embedding", { - resourceBudget: { - cpuMillis: 8000, - memoryBytes: 16 * 1024 ** 3, - }, + totalCpuMillis: 8000, + totalMemoryBytes: 16 * 1024 ** 3, + totalGpuCount: 2, }); await job.wait(); ``` -On current SQL servers, the equivalent `REFRESH COLUMN ... WITH (...)` form -still takes all three fields when CPU or memory is set; use `gpu_count = 0` -for a CPU-only Function. The SDK normalizes an omitted nested GPU count to a -numeric zero before sending the request. - -The existing top-level `gpu_count` / `gpuCount` option remains the shorthand -for changing only the aggregate GPU budget. It cannot be combined with the -complete resource budget. Omitting both preserves the server's existing -defaults. +Each supplied `total_*` value overrides that resource for this refresh. +Unspecified values inherit the column's `total_*` settings, then the +pinned Function's defaults, then the deployment defaults. `total_gpu_count=0` +limits the refresh to CPU workers and cannot run a GPU Function. {/* Draft for the Function refresh control-plane resource release. -`resource_budget` above sizes the Function workers. Two independent options +`total_cpu_millis`, `total_memory_bytes`, and `total_gpu_count` above sizes the Function workers. Two independent options size the refresh control plane for a registered Function. `supervisor_resources` sets the CPU, memory and ephemeral-storage limits of the supervisor pod. `planning_workers` sets the resources of one planning worker and the sizing of the CPU-only planning fleet: `max_workers`, `rows_per_worker` and `fragments_per_worker`. Every field is required and must be positive. Omitting either option leaves the server's configured -defaults unchanged, and either can be combined with `resource_budget`. +defaults unchanged, and either can be combined with `total_cpu_millis`, `total_memory_bytes`, and `total_gpu_count`. ```python Python icon="python" @@ -495,11 +485,11 @@ The SDK validates the shape and sends these values only with this explicit refresh request. A supporting LanceDB Enterprise server is required. */} -These examples configure only the explicit refresh shown. A registered -Function declaration can separately set `auto_refresh_resource_budget` on -`add_columns`; that declaration controls the budget for its automatic -refreshes. SQL-expression columns reject the automatic resource-budget option -because they do not use Function workers. +A Function column may set `total_cpu_millis`, +`total_memory_bytes`, and `total_gpu_count` on `add_columns`. +These override the Function defaults for both manual and automatic refreshes. +The settings apply to registered Function columns; SQL-expression columns use +`num_workers` instead. To override the registered Function's call concurrency for this logical execution only: @@ -531,7 +521,7 @@ await job.wait(); `max_concurrency` caps user-code calls in flight for one Function within one logical execution. It is not an account-wide quota and does not resize or -rewrite `resource_budget`. Omitting it uses the registration default; a +rewrite `total_cpu_millis`, `total_memory_bytes`, and `total_gpu_count`. Omitting it uses the registration default; a refresh value overrides that default for this execution only. `batch_size` caps rows in one Function call; LanceDB adapts actual call and @@ -613,7 +603,7 @@ gpu_class = next(gpu.name for gpu in classes if gpu.gpu_model == "NVIDIA H100") job = table.refresh_column_async( "embedding", gpu_class=gpu_class, - gpu_count=4, + total_gpu_count=4, batch_size=32, ) ``` @@ -637,7 +627,7 @@ async fn refresh( "embedding", RefreshColumnOptions::default() .gpu_class(gpu_class) - .gpu_count(4) + .total_gpu_count(4) .batch_size(32), ) .await?; @@ -646,19 +636,21 @@ async fn refresh( ``` -`gpu_count` is the aggregate GPU budget for the refresh's Function workers, -not a request for that many GPUs per worker. It must be positive and preserves -the deployment's CPU and memory defaults. +`total_gpu_count` is the aggregate GPU budget for the refresh's Function workers, +and `gpu_count` is the positive number of devices allocated together to each +worker. The total budget must fit at least one worker. Omitted CPU and memory +values inherit column settings, then Function settings, then deployment defaults. `gpu_class` must name a class returned by `list_gpu_classes()`; class names -are lowercase DNS labels. Omit either option to use the Function's registered -class or the server's configured budget. `list_gpu_classes()` requires System +are lowercase DNS labels; `"any"` accepts any eligible configured class. Each +omitted setting inherits the column's setting, then the Function's setting. +If no layer specifies a GPU class, omission is equivalent to `"any"`. `list_gpu_classes()` requires System Usage permission, and raises `NotImplementedError` when the server predates GPU class discovery. The Rust GPU discovery and refresh controls are not in the latest Rust release. TypeScript does not expose GPU class discovery; pass `gpuClass` -and `gpuCount` in the `refreshColumnAsync` options. +and `totalGpuCount` in the `refreshColumnAsync` options. Completed Function outputs publish with their fragment by default. To opt into @@ -750,8 +742,8 @@ The SDK rejects a blank `where`, a `max_failed_fraction` outside 0 to 1, a timeout that is not a positive number and a zero worker or process count before sending the request; the server validates everything else. A LanceDB Embedded refresh rejects every option other than `batch_size`, `gpu_class` -and `gpu_count`; in particular, it rejects `resource_budget` rather than -silently ignoring it. +and `total_gpu_count`; in particular, it rejects `total_cpu_millis` and +`total_memory_bytes` rather than silently ignoring them. ## When a refresh fails {#failures} diff --git a/docs/web/feature-engineering/refresh-materialized-view.mdx b/docs/web/feature-engineering/refresh-materialized-view.mdx index 74fcce2fb..2325d846f 100644 --- a/docs/web/feature-engineering/refresh-materialized-view.mdx +++ b/docs/web/feature-engineering/refresh-materialized-view.mdx @@ -60,20 +60,20 @@ LanceDB Embedded it always matches `rows_written` from the most recent refresh. {/* -Draft: publish this section after the Python/Rust resource-budget SDK support -is released. TypeScript parity is tracked separately in issue #4903. +Draft: publish this section after the resource-control SDK support is released. ## Resource budgets {#resources} -For training-data curation, bound the resources used to recompute a view: +Bound the resources used to recompute a view: ```python Python icon="python" job = view.refresh_async( - cpu_millis=8000, - memory_bytes=16 * 1024**3, - gpu_count=2, + total_cpu_millis=8000, + total_memory_bytes=16 * 1024**3, + total_gpu_count=4, gpu_class="h100", + gpu_count=2, ) job.wait() ``` @@ -84,38 +84,45 @@ use lancedb::materialized_view::MaterializedView; async fn refresh(view: &MaterializedView) -> lancedb::Result<()> { let job = view .refresh() - .cpu_millis(8000) - .memory_bytes(16_u64 << 30) - .gpu_count(2) + .total_cpu_millis(8000) + .total_memory_bytes(16_u64 << 30) + .total_gpu_count(4) .gpu_class("h100") + .gpu_count(2) .execute_async() .await?; job.wait().await?; Ok(()) } ``` + +```typescript TypeScript icon="js" +await view.refresh({ + totalCpuMillis: 8000, + totalMemoryBytes: 16 * 1024 ** 3, + totalGpuCount: 4, + gpuClass: "h100", + gpuCount: 2, +}); +``` -The same options are available on `refresh`, asynchronous Python connections, -and the Rust refresh builder (`cpu_millis`, `memory_bytes`, `gpu_count`, and -`gpu_class`). CPU is in millicores (8000 means eight cores), memory is bytes, -and GPU count is an aggregate concurrent cap. CPU or memory requires all three -budget fields. Use zero GPUs for a CPU-only view, or specify a GPU cap alone. +CPU is in millicores (8000 means eight cores), memory is in bytes, and +`total_gpu_count` is the aggregate concurrent GPU cap. `gpu_count` allocates +that many devices together to each worker; the total cap must fit at least +one worker. Use `total_gpu_count=0` for a CPU-only view. -The cap covers the refresh execution and its Function processes together. -It does not allocate that budget separately to each Function. A GPU class -selects placement for this execution; discover configured classes with -`db.list_gpu_classes()`. A cap does not promise more parallelism: current MV -refreshes use at most one GPU. Omitted settings keep existing defaults. +Each omitted setting inherits the view's creation setting, then the Function +setting. Total budgets across distinct pinned Function versions are summed; +the per-worker count uses their largest default. Remaining total budgets use +deployment defaults. An unresolved GPU class is equivalent to `"any"`, and +an explicit `gpu_class="any"` overrides a concrete creation or Function class. +Discover configured classes with `db.list_gpu_classes()`. -These controls require an Enterprise server with an isolated backend that can -enforce them; Embedded and unsupported execution backends reject them. Earlier -Enterprise servers reject the new SQL options. See the +These controls require LanceDB Enterprise with an isolated backend that can +enforce them; Embedded and unsupported execution backends reject them. See the [SQL resource options](/sql/dml/refresh-materialized-view#resources). -TypeScript does not expose these options yet; SDK parity is tracked in -[issue #4903](https://github.com/lancedb/lancedb/issues/4903). - */} ## Automatic refresh {#auto-refresh} diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 4de54e78a..7c0a19da4 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -635,7 +635,9 @@ dependencies are part of its definition: | `conda`, `conda_channels` | conda packages instead of pip; channels in priority order | | `env` | environment variables | | `python_version` | Python major/minor for the execution environment, defaulting to yours | -| `gpu` | whether every execution requires a GPU | +| `gpu` | Enable GPU execution with `True` (Python) or `true` (SQL); defaults to CPU execution | +| `gpu_class` | Operator-configured GPU class, such as `h100`; requires GPU execution | +| `gpu_count` | GPUs allocated together per Function worker; positive integer, defaults to one; requires GPU execution | ```python Python icon="python" diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index 691118026..643ee36a2 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -63,8 +63,9 @@ version is unaffected. | `apt` | OS packages to install in the worker environment | | `image` | a specific container image to run the worker in, such as `'host/repo@sha256:...'` | | `python_version` | worker Python version; `3.12` when omitted, whatever Python you send the statement from | -| `gpu` | `'true'` when every execution needs a GPU | -| `gpu_class` | which configured GPU class to run on, when `gpu = 'true'` | +| `gpu` | Enable GPU execution with `True` (Python) or `true` (SQL); defaults to CPU execution | +| `gpu_class` | Operator-configured GPU class, such as `h100`; requires GPU execution | +| `gpu_count` | GPUs allocated together per Function worker; positive integer, defaults to one; requires GPU execution | | `result_stability` | `'input_and_context'` or `'per_call'` | | `batch_size` | maximum rows per Function call | | `row_timeout_seconds` | per-row (or per-batch, for a vectorized Function) execution timeout | @@ -76,7 +77,7 @@ version is unaffected. | `LANGUAGE` other than `python` | refused | | `pip` and `conda` together | refused (pick one) | | `conda_channels` without `conda` | refused | -| `gpu` set to anything but `'true'` | refused | +| An invalid GPU class, zero GPU count, or a count above the configured class limit | refused; use a configured `gpu_class` and a positive `gpu_count` | | An empty body | refused | | Any other option | refused, and the message lists what is supported | diff --git a/docs/web/sql/ddl/materialized-view.mdx b/docs/web/sql/ddl/materialized-view.mdx index a2a5024f6..271885fec 100644 --- a/docs/web/sql/ddl/materialized-view.mdx +++ b/docs/web/sql/ddl/materialized-view.mdx @@ -155,3 +155,23 @@ same underlying job as dropping any table, `drop_table` or `drop_object`. How a refresh works, in LanceDB Enterprise. + + +### Resource settings + +Creation accepts `total_cpu_millis`, `total_memory_bytes`, and `total_gpu_count` +as execution-wide defaults, plus `gpu_class` and positive `gpu_count` for each +worker. Refresh accepts the same names and overrides each supplied field. +Unspecified fields inherit creation settings, then Function settings, then +deployment defaults. A materialized view sums total budgets across distinct +pinned Function versions; per-worker counts use the largest Function default +unless overridden. + +```sql +CREATE MATERIALIZED VIEW embeddings +WITH (gpu_class = 'any', gpu_count = 2, total_gpu_count = 8) +AS SELECT embed(text) AS embedding FROM documents; + +REFRESH MATERIALIZED VIEW embeddings +WITH (gpu_class = 'h100', gpu_count = 4, total_gpu_count = 8); +``` diff --git a/docs/web/sql/dml/refresh-column.mdx b/docs/web/sql/dml/refresh-column.mdx index e680823ef..c0cb57fdb 100644 --- a/docs/web/sql/dml/refresh-column.mdx +++ b/docs/web/sql/dml/refresh-column.mdx @@ -52,10 +52,11 @@ to let LanceDB track which outputs need updating. | Option | Meaning | | --- | --- | | `num_workers` | fixed worker count for SQL-expression columns; rejected for registered Function columns | -| `cpu_millis` | aggregate CPU ceiling across the refresh's Function workers, in thousandths of a CPU | -| `memory_bytes` | aggregate memory ceiling across the refresh's Function workers, in bytes | -| `gpu_count` | aggregate GPU budget across the refresh's workers. Function columns only | -| `gpu_class` | GPU class name for the refresh's workers. Function columns only | +| `total_cpu_millis` | aggregate CPU ceiling across the refresh's Function workers, in thousandths of a CPU | +| `total_memory_bytes` | aggregate memory ceiling across the refresh's Function workers, in bytes | +| `total_gpu_count` | aggregate GPU budget across the refresh's workers. Function columns only | +| `gpu_class` | GPU class name for the refresh's workers; `any` accepts any eligible pool. Function columns only | +| `gpu_count` | positive number of GPUs allocated together to each worker. Function columns only | | `batch_size` | maximum rows passed to one Function call; actual calls can be smaller. Function columns only | | `max_executor_processes_per_worker` | cap on executor processes per worker. Function columns only | | `row_timeout_seconds` | deadline for one Function call. Function columns only | @@ -66,14 +67,15 @@ to let LanceDB track which outputs need updating. ```sql SQL icon="database" REFRESH COLUMN embedding ON documents - WITH (cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2) + WITH (total_cpu_millis = 8000, total_memory_bytes = 17179869184, total_gpu_count = 2) ``` The example allows up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the Function workers together. It does not reserve those resources per worker or -guarantee a worker count. When setting CPU or memory, provide all three budget -fields. A complete CPU-only budget uses `gpu_count = 0`. +guarantee a worker count. Set each resource independently; omitted values inherit +column `total_*` settings, then Function defaults, then deployment defaults. +A CPU-only GPU budget uses `total_gpu_count = 0`. Set `error_policy` on the refresh, not on the Function definition. With `skip`, inspect failures with `SHOW ERRORS` or `table.function_errors()` and retry the diff --git a/docs/web/sql/dml/refresh-materialized-view.mdx b/docs/web/sql/dml/refresh-materialized-view.mdx index e83337c7d..ef662e01d 100644 --- a/docs/web/sql/dml/refresh-materialized-view.mdx +++ b/docs/web/sql/dml/refresh-materialized-view.mdx @@ -14,8 +14,8 @@ A LanceDB extension with no DataFusion equivalent. ```sql SQL icon="database" REFRESH MATERIALIZED VIEW - [WITH (full = , cpu_millis = , memory_bytes = , - gpu_count = , gpu_class = '')] + [WITH (full = , total_cpu_millis = , total_memory_bytes = , + total_gpu_count = , gpu_class = '')] ``` @@ -43,20 +43,20 @@ Set budgets for one refresh execution: ```sql REFRESH MATERIALIZED VIEW curated_training_set WITH ( - cpu_millis = 8000, - memory_bytes = 17179869184, - gpu_count = 2, + total_cpu_millis = 8000, + total_memory_bytes = 17179869184, + total_gpu_count = 2, gpu_class = 'h100' ); ``` -`cpu_millis` is CPU capacity in millicores (1000 = one core), not CPU time. -`memory_bytes` caps memory in bytes. `gpu_count` caps concurrent GPUs for the +`total_cpu_millis` is CPU capacity in millicores (1000 = one core), not CPU time. +`total_memory_bytes` caps memory in bytes. `total_gpu_count` caps concurrent GPUs for the refresh. These are aggregate caps across its SQL execution and Function processes; they are not multiplied by the number of Functions in the query. -CPU or memory requires all three budget fields. CPU and memory must be positive; -`gpu_count = 0` is allowed for CPU-only views. A GPU budget alone is also accepted. +Each resource may be overridden independently. CPU and memory must be positive; +`total_gpu_count = 0` is allowed for CPU-only views. A GPU budget alone is also accepted. A cap does not reserve all of its GPUs or increase refresh parallelism. Current MV refreshes use at most one GPU, shared by their GPU Function calls. diff --git a/nodejs/__test__/materialized_view.test.ts b/nodejs/__test__/materialized_view.test.ts index 0840395fe..00d2e40e3 100644 --- a/nodejs/__test__/materialized_view.test.ts +++ b/nodejs/__test__/materialized_view.test.ts @@ -121,7 +121,34 @@ describe("materialized views", () => { .spyOn(view.table(), "refreshMaterializedView") .mockResolvedValue(remoteResult); expect(await view.refresh({ full: true })).toEqual(remoteResult); - expect(refresh).toHaveBeenCalledWith(undefined, true); + expect(refresh).toHaveBeenCalledWith( + undefined, + true, + undefined, + undefined, + undefined, + undefined, + undefined, + ); + expect( + await view.refresh({ + full: true, + totalCpuMillis: 4000, + totalMemoryBytes: 8_000_000_000, + totalGpuCount: 4, + gpuClass: "any", + gpuCount: 2, + }), + ).toEqual(remoteResult); + expect(refresh).toHaveBeenLastCalledWith( + undefined, + true, + 4000, + 8_000_000_000, + 4, + "any", + 2, + ); }); experimentalTest("lists views and rejects non-views", async () => { diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 14b581a2c..9dca563e3 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -998,7 +998,7 @@ describe("remote connection", () => { publicationIntervalRows: 60, maxConcurrency: 3, gpuClass: "a10g", - gpuCount: 2, + totalGpuCount: 2, errorPolicy: "skip", maxFailedFraction: 0.01, maxFailedRows: 50, @@ -1021,10 +1021,8 @@ describe("remote connection", () => { }); } await table.refreshColumnAsync("embedding", { - resourceBudget: { - cpuMillis: 8_000, - memoryBytes: 16 * 1024 ** 3, - }, + totalCpuMillis: 8_000, + totalMemoryBytes: 16 * 1024 ** 3, }); await expect( table.refreshColumnAsync("embedding", { @@ -1069,75 +1067,53 @@ describe("remote connection", () => { [{ maxConcurrency: Number.NaN }, "maxConcurrency"], [{ maxConcurrency: Number.POSITIVE_INFINITY }, "maxConcurrency"], [{ numWorkers: 0 }, "num_workers"], - [{ gpuCount: 0 }, "gpu_count"], + [ { - resourceBudget: { - cpuMillis: 1_000, - memoryBytes: 1_024, - }, - gpuCount: 1, + totalCpuMillis: 0, + totalMemoryBytes: 1_024, }, - "gpu_count cannot be combined with resource_budget", + "totalCpuMillis", ], [ { - resourceBudget: { - cpuMillis: 0, - memoryBytes: 1_024, - }, + totalCpuMillis: 1_000, + totalMemoryBytes: 1_024, + totalGpuCount: 1.5, }, - "resourceBudget.cpuMillis", + "totalGpuCount", ], [ { - resourceBudget: { - cpuMillis: 1_000, - memoryBytes: 1_024, - gpuCount: 1.5, - }, + totalCpuMillis: 1_000, + totalMemoryBytes: 1_024, + totalGpuCount: -1, }, - "resourceBudget.gpuCount", + "totalGpuCount", ], [ { - resourceBudget: { - cpuMillis: 1_000, - memoryBytes: 1_024, - gpuCount: -1, - }, + totalCpuMillis: 1_000, + totalMemoryBytes: 1_024, + totalGpuCount: 2 ** 32, }, - "resourceBudget.gpuCount", + "totalGpuCount", ], [ { - resourceBudget: { - cpuMillis: 1_000, - memoryBytes: 1_024, - gpuCount: 2 ** 32, - }, + totalCpuMillis: 1_000, + totalMemoryBytes: 1_024, + totalGpuCount: Number.NaN, }, - "resourceBudget.gpuCount", + "totalGpuCount", ], [ { - resourceBudget: { - cpuMillis: 1_000, - memoryBytes: 1_024, - gpuCount: Number.NaN, - }, + totalCpuMillis: 1_000, + totalMemoryBytes: 1_024, + totalGpuCount: Number.POSITIVE_INFINITY, }, - "resourceBudget.gpuCount", - ], - [ - { - resourceBudget: { - cpuMillis: 1_000, - memoryBytes: 1_024, - gpuCount: Number.POSITIVE_INFINITY, - }, - }, - "resourceBudget.gpuCount", + "totalGpuCount", ], [ { @@ -1186,7 +1162,7 @@ describe("remote connection", () => { JSON.parse( `{"column": "embedding", "where": "id % 2 = 0", "batch_size": 16, "publication_interval_rows": 60, - "max_concurrency": 3, "gpu_class": "a10g", "gpu_count": 2, + "max_concurrency": 3, "gpu_class": "a10g", "total_gpu_count": 2, "error_policy": "skip", "max_failed_fraction": 0.01, "max_failed_rows": 50, "row_timeout_seconds": 30, "init_timeout_seconds": 120, @@ -1202,12 +1178,7 @@ describe("remote connection", () => { '{"column": "embedding", "publication_interval_rows": 9007199254740991}', ), JSON.parse( - `{"column": "embedding", - "resource_budget": { - "cpu_millis": 8000, - "memory_bytes": 17179869184, - "gpu_count": 0 - }}`, + '{"column":"embedding","total_cpu_millis":8000,"total_memory_bytes":17179869184}', ), ]); }); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 970f2f7ca..1f3cff276 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -6310,9 +6310,10 @@ describe("computed columns", () => { ).rejects.toThrow("max_concurrency requires a LanceDB Enterprise refresh"); await expect( table.refreshColumnAsync("x", { - resourceBudget: { cpuMillis: 1_000, memoryBytes: 1_024 }, + totalCpuMillis: 1_000, + totalMemoryBytes: 1_024, }), - ).rejects.toThrow("resource_budget requires a LanceDB Enterprise refresh"); + ).rejects.toThrow("total_cpu_millis requires a LanceDB Enterprise refresh"); await expect( table.refreshColumn("x", { supervisorResources: { diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index ce71c4e89..8a818b682 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -286,6 +286,11 @@ export abstract class Connection { where?: string; limit?: number; withNoData?: boolean; + totalCpuMillis?: number; + totalMemoryBytes?: number; + totalGpuCount?: number; + gpuClass?: string; + gpuCount?: number; }, ): Promise; @@ -674,9 +679,34 @@ export class LocalConnection extends Connection { where?: string; limit?: number; withNoData?: boolean; + totalCpuMillis?: number; + totalMemoryBytes?: number; + totalGpuCount?: number; + gpuClass?: string; + gpuCount?: number; }, ): Promise { validateNonNegativeInteger(options?.limit, "limit"); + for (const [name, value] of [ + ["totalCpuMillis", options?.totalCpuMillis], + ["totalMemoryBytes", options?.totalMemoryBytes], + ["totalGpuCount", options?.totalGpuCount], + ["gpuCount", options?.gpuCount], + ] as const) { + validateNonNegativeInteger(value, name); + if (value === 0 && name !== "totalGpuCount") { + throw new Error(`${name} must be positive`); + } + } + if ( + options?.totalGpuCount !== undefined && + options.totalGpuCount > 4294967295 + ) { + throw new Error("totalGpuCount exceeds 4294967295"); + } + if (options?.gpuCount !== undefined && options.gpuCount > 4294967295) { + throw new Error("gpuCount exceeds 4294967295"); + } const innerTable = await this.inner.createMaterializedView( name, source, @@ -684,6 +714,11 @@ export class LocalConnection extends Connection { options?.where, options?.limit, options?.withNoData ?? false, + options?.totalCpuMillis, + options?.totalMemoryBytes, + options?.totalGpuCount, + options?.gpuClass, + options?.gpuCount, ); return new MaterializedView(new LocalTable(innerTable)); } diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 67c385186..e8a015c59 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -60,7 +60,6 @@ export { FunctionRefreshPlanningConfig, FunctionRefreshPodResources, FunctionRetryPolicy, - FunctionWorkerResourceBudget, RefreshColumnResult, FunctionErrors, FunctionErrorsOptions, diff --git a/nodejs/lancedb/materialized_view.ts b/nodejs/lancedb/materialized_view.ts index afb61b9ab..d6c101b67 100644 --- a/nodejs/lancedb/materialized_view.ts +++ b/nodejs/lancedb/materialized_view.ts @@ -197,11 +197,39 @@ export class MaterializedView { async refresh(options?: { full?: boolean; sourceVersion?: number; + totalCpuMillis?: number; + totalMemoryBytes?: number; + totalGpuCount?: number; + gpuClass?: string; + gpuCount?: number; }): Promise { validateNonNegativeInteger(options?.sourceVersion, "sourceVersion"); + for (const [name, value] of [ + ["totalCpuMillis", options?.totalCpuMillis], + ["totalMemoryBytes", options?.totalMemoryBytes], + ["totalGpuCount", options?.totalGpuCount], + ["gpuCount", options?.gpuCount], + ] as const) { + validateNonNegativeInteger(value, name); + if (value === 0 && name !== "totalGpuCount") { + throw new Error(`${name} must be positive`); + } + if ( + (name === "gpuCount" || name === "totalGpuCount") && + value !== undefined && + value > 4294967295 + ) { + throw new Error(`${name} exceeds 4294967295`); + } + } return await this.inner.refreshMaterializedView( options?.sourceVersion, options?.full, + options?.totalCpuMillis, + options?.totalMemoryBytes, + options?.totalGpuCount, + options?.gpuClass, + options?.gpuCount, ); } } diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 30fb60d23..6645e0205 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -962,26 +962,18 @@ export abstract class Table { * `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, * `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` * and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`, - * `maxConcurrency`, `resourceBudget`, `supervisorResources`, + * `maxConcurrency`, `totalCpuMillis`, `totalMemoryBytes`, `supervisorResources`, * `planningWorkers` and `maxExecutorProcessesPerWorker` size registered * Function refreshes. `retryPolicy` overrides user-code retries only when * repeating partial work is safe; set `maxAttempts: 1` to disable retries. * `maxConcurrency` overrides the registered default for this logical * execution only and is a positive integer; it is not an account-wide - * quota. A `resourceBudget` requires `cpuMillis` and - * `memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function. - * `supervisorResources` and each `planningWorkers.resources` entry require - * positive `cpuMillis`, `memoryBytes` and `ephemeralStorageBytes`. - * `planningWorkers` also requires positive `maxWorkers`, - * `rowsPerWorker` and `fragmentsPerWorker`. - * The budget applies only to this explicit refresh and does not configure - * a later automatic refresh. - * `gpuCount` at the top level is the shorthand that preserves the - * deployment defaults for CPU and memory, and cannot be combined with - * `resourceBudget`. `numWorkers` applies only to expression columns; use - * `resourceBudget` for registered Functions. All are LanceDB Enterprise - * only; a LanceDB Embedded refresh rejects every option other than - * `batchSize`, `gpuClass` and `gpuCount`. + * quota. `totalCpuMillis`, `totalMemoryBytes`, and `totalGpuCount` override + * their corresponding execution-wide resource limits independently. Unset + * values inherit column defaults, then Function defaults, then deployment + * defaults. A zero GPU limit is valid for CPU-only Functions. + * `supervisorResources` and `planningWorkers.resources` are per-pod sizes. + * `numWorkers` applies only to expression columns. * `publicationIntervalRows` opts into publishing completed Function split * ranges once their accumulated unpublished rows reach the threshold. * It must be a positive safe integer and requires non-Blob Function outputs. @@ -991,10 +983,8 @@ export abstract class Table { * ```ts * const job = await table.refreshColumnAsync("embedding", { * where: "published_at > '2026-01-01'", - * resourceBudget: { - * cpuMillis: 8000, - * memoryBytes: 16 * 1024 ** 3, - * }, + * totalCpuMillis: 8000, + * totalMemoryBytes: 16 * 1024 ** 3, * maxConcurrency: 4, * publicationIntervalRows: 10000, * errorPolicy: "skip", @@ -1067,6 +1057,11 @@ export abstract class Table { abstract refreshMaterializedView( sourceVersion?: number, full?: boolean, + totalCpuMillis?: number, + totalMemoryBytes?: number, + totalGpuCount?: number, + gpuClass?: string, + gpuCount?: number, ): Promise; /** @ignore */ @@ -2048,8 +2043,21 @@ export class LocalTable extends Table { async refreshMaterializedView( sourceVersion?: number, full?: boolean, + totalCpuMillis?: number, + totalMemoryBytes?: number, + totalGpuCount?: number, + gpuClass?: string, + gpuCount?: number, ): Promise { - return await this.inner.refreshMaterializedView(sourceVersion, full); + return await this.inner.refreshMaterializedView( + sourceVersion, + full, + totalCpuMillis, + totalMemoryBytes, + totalGpuCount, + gpuClass, + gpuCount, + ); } async materializedViewDefinition(): Promise { diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index 7a32756c3..7537a8bcd 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -303,6 +303,7 @@ impl Connection { } #[napi(catch_unwind)] + #[allow(clippy::too_many_arguments)] pub async fn create_materialized_view( &self, name: String, @@ -311,6 +312,11 @@ impl Connection { filter: Option, limit: Option, with_no_data: bool, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, ) -> napi::Result
          { let mut builder = self.get_inner()?.create_materialized_view(name, source); if let Some(projections) = projections { @@ -331,6 +337,45 @@ impl Connection { .map_err(|_| napi::Error::from_reason("limit must be a non-negative integer"))?; builder = builder.limit(limit); } + const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; + for (name, value, maximum, minimum) in [ + ("total_cpu_millis", total_cpu_millis, MAX_SAFE_INTEGER, 1.0), + ( + "total_memory_bytes", + total_memory_bytes, + MAX_SAFE_INTEGER, + 1.0, + ), + ("total_gpu_count", total_gpu_count, u32::MAX as f64, 0.0), + ] { + if let Some(value) = value { + if !value.is_finite() || value.fract() != 0.0 || value < minimum || value > maximum + { + return Err(napi::Error::from_reason(format!( + "{name} must be an integer between {minimum} and {maximum}" + ))); + } + builder = match name { + "total_cpu_millis" => builder.total_cpu_millis(value as u64), + "total_memory_bytes" => builder.total_memory_bytes(value as u64), + _ => builder.total_gpu_count(value as u32), + }; + } + } + if let Some(class) = gpu_class { + builder = builder.gpu_class(class); + } + if let Some(count) = gpu_count { + if !count.is_finite() + || count.fract() != 0.0 + || !(1.0..=u32::MAX as f64).contains(&count) + { + return Err(napi::Error::from_reason( + "gpuCount must be an integer between 1 and 4294967295", + )); + } + builder = builder.gpu_count(count as u32); + } builder = builder.with_no_data(with_no_data); let view = builder.execute().await.default_error()?; Ok(Table::new(view.table().clone())) diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 728240cf8..5b1153909 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -11,8 +11,7 @@ use lancedb::table::{ AddDataMode, ColumnAlteration as LanceColumnAlteration, DeltaRef as LanceDbDeltaRef, FieldMetadataUpdate as LanceFieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig as LanceFunctionRefreshPlanningConfig, - FunctionRefreshPodResources as LanceFunctionRefreshPodResources, - FunctionWorkerResourceBudget as LanceFunctionWorkerResourceBudget, NewColumnTransform, Ref, + FunctionRefreshPodResources as LanceFunctionRefreshPodResources, NewColumnTransform, Ref, Table as LanceDbTable, TableDelta as LanceDbTableDelta, }; use napi::Env; @@ -774,10 +773,16 @@ impl Table { } #[napi(catch_unwind)] + #[allow(clippy::too_many_arguments)] pub async fn refresh_materialized_view( &self, source_version: Option, full: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, ) -> napi::Result { let view = lancedb::MaterializedView::from_table(self.inner_ref()?.clone()) .await @@ -789,6 +794,30 @@ impl Table { })?; builder = builder.source_version(version); } + let resources: lancedb::table::RefreshColumnOptions = RefreshColumnOptions { + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count, + ..Default::default() + } + .try_into()?; + if let Some(value) = resources.total_cpu_millis { + builder = builder.total_cpu_millis(value); + } + if let Some(value) = resources.total_memory_bytes { + builder = builder.total_memory_bytes(value); + } + if let Some(value) = resources.total_gpu_count { + builder = builder.total_gpu_count(value); + } + if let Some(value) = resources.gpu_class { + builder = builder.gpu_class(value); + } + if let Some(value) = resources.gpu_count { + builder = builder.gpu_count(value); + } let result = builder.execute().await.default_error()?; Ok(result.into()) } @@ -1916,18 +1945,6 @@ pub struct FunctionErrorsOptions { pub page_token: Option, } -/// Aggregate worker resources for one Enterprise Function refresh. -#[napi(object)] -#[derive(Clone, Debug)] -pub struct FunctionWorkerResourceBudget { - /// Aggregate CPU budget in millicores; 1000 is one CPU. - pub cpu_millis: f64, - /// Aggregate memory budget in bytes. - pub memory_bytes: f64, - /// Aggregate GPU budget. Omitted means zero, a CPU-only refresh. - pub gpu_count: Option, -} - /// CPU, memory, and ephemeral-storage limits for one Function refresh /// control-plane pod. #[napi(object)] @@ -1990,18 +2007,6 @@ fn positive_safe_integer(value: f64, name: &str) -> napi::Result { Ok(value as u64) } -fn resource_budget_gpu_count(value: Option) -> napi::Result { - let Some(value) = value else { - return Ok(0); - }; - if !value.is_finite() || value.fract() != 0.0 || !(0.0..=u32::MAX as f64).contains(&value) { - return Err(napi::Error::from_reason( - "resourceBudget.gpuCount must be an integer between 0 and 4294967295", - )); - } - Ok(value as u32) -} - fn positive_u32(value: Option, name: &str) -> napi::Result> { value .map(|value| { @@ -2020,8 +2025,7 @@ fn positive_u32(value: Option, name: &str) -> napi::Result> { /// Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every /// option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores -/// `batchSize`, `gpuClass` and `gpuCount` and rejects the rest, including -/// `resourceBudget`. +/// `batchSize`, `gpuClass` and `totalGpuCount` and rejects the rest. #[napi(object)] #[derive(Clone, Debug, Default)] pub struct RefreshColumnOptions { @@ -2040,15 +2044,18 @@ pub struct RefreshColumnOptions { pub max_concurrency: Option, /// GPU class for Function workers. pub gpu_class: Option, - /// Complete aggregate CPU and memory budget for a registered Function - /// refresh. `gpuCount` inside the budget defaults to zero. - pub resource_budget: Option, + /// Positive GPU count allocated to each Function worker. + pub gpu_count: Option, + /// Override the total CPU budget in millicores for this refresh. + pub total_cpu_millis: Option, + /// Override the total memory budget in bytes for this refresh. + pub total_memory_bytes: Option, /// CPU, memory, and ephemeral-storage limits for the refresh supervisor. pub supervisor_resources: Option, /// Resources and sizing for the refresh planning fleet. pub planning_workers: Option, - /// Positive aggregate GPU budget for Function workers. - pub gpu_count: Option, + /// Nonnegative total GPU budget for Function workers. + 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 @@ -2083,17 +2090,14 @@ impl TryFrom for lancedb::table::RefreshColumnOptions { .transpose()?; options.max_concurrency = positive_u32(value.max_concurrency, "maxConcurrency")?; options.gpu_class = value.gpu_class; - options.resource_budget = value - .resource_budget - .map(|budget| { - Ok::<_, napi::Error>( - LanceFunctionWorkerResourceBudget::new( - positive_safe_integer(budget.cpu_millis, "resourceBudget.cpuMillis")?, - positive_safe_integer(budget.memory_bytes, "resourceBudget.memoryBytes")?, - ) - .with_gpu_count(resource_budget_gpu_count(budget.gpu_count)?), - ) - }) + options.gpu_count = positive_u32(value.gpu_count, "gpuCount")?; + options.total_cpu_millis = value + .total_cpu_millis + .map(|value| positive_safe_integer(value, "totalCpuMillis")) + .transpose()?; + options.total_memory_bytes = value + .total_memory_bytes + .map(|value| positive_safe_integer(value, "totalMemoryBytes")) .transpose()?; options.supervisor_resources = value .supervisor_resources @@ -2147,7 +2151,20 @@ impl TryFrom for lancedb::table::RefreshColumnOptions { )) }) .transpose()?; - options.gpu_count = value.gpu_count; + options.total_gpu_count = value + .total_gpu_count + .map(|count| { + if !count.is_finite() + || count.fract() != 0.0 + || !(0.0..=u32::MAX as f64).contains(&count) + { + return Err(napi::Error::from_reason( + "totalGpuCount must be an integer between 0 and 4294967295", + )); + } + Ok(count as u32) + }) + .transpose()?; options.retry_policy = value.retry_policy.map(|policy| { let mut converted = lancedb::function::FunctionRetryPolicy::default(); if let Some(max_attempts) = policy.max_attempts { diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 01e7a3369..a1d4c2445 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -388,6 +388,11 @@ class Connection(object): with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, *, query: Optional[str] = None, exist_ok: bool = False, @@ -402,6 +407,11 @@ class Connection(object): with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, *, query: Optional[str] = None, exist_ok: bool = False, @@ -754,7 +764,11 @@ class Table: columns: list[tuple[str, str]], auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[int] = None, - auto_refresh_resource_budget: Optional[dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> AddColumnsResult: ... async def add_function_columns( self, @@ -762,7 +776,11 @@ class Table: output_name: Optional[str], auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[int] = None, - auto_refresh_resource_budget: Optional[dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> AddColumnsResult: ... async def refresh_column( self, @@ -772,11 +790,13 @@ class Table: batch_size: Optional[int] = None, max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, - resource_budget: Optional[dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, supervisor_resources: Optional[dict[str, int]] = None, planning_workers: Optional[dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + total_gpu_count: Optional[int] = None, retry_policy: Optional[str] = None, error_policy: Optional[str] = None, max_failed_fraction: Optional[float] = None, @@ -800,11 +820,13 @@ class Table: batch_size: Optional[int] = None, max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, - resource_budget: Optional[dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, supervisor_resources: Optional[dict[str, int]] = None, planning_workers: Optional[dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + total_gpu_count: Optional[int] = None, retry_policy: Optional[str] = None, error_policy: Optional[str] = None, max_failed_fraction: Optional[float] = None, @@ -856,20 +878,22 @@ class Table: source_version: Optional[int] = None, *, full: bool = False, - cpu_millis: Optional[int] = None, - memory_bytes: Optional[int] = None, - gpu_count: Optional[int] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> RefreshMaterializedViewResult: ... async def refresh_materialized_view_async( self, source_version: Optional[int] = None, *, full: bool = False, - cpu_millis: Optional[int] = None, - memory_bytes: Optional[int] = None, - gpu_count: Optional[int] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> Job: ... async def materialized_view_definition(self) -> str: ... async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 4d5840527..9efee4393 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -118,6 +118,7 @@ from .namespace_utils import ( _normalize_drop_namespace_mode, _normalize_drop_namespace_behavior, ) +from .resources import _resource_options def _view_description( @@ -764,6 +765,11 @@ class DBConnection(EnforceOverrides): exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. @@ -807,6 +813,14 @@ class DBConnection(EnforceOverrides): Positive, finite refresh interval in seconds in LanceDB Enterprise. When omitted, the server determines when to refresh. + total_cpu_millis: int, optional + Default total CPU budget in millicores for initial population and + refreshes. Overrides Function defaults. LanceDB Enterprise only. + total_memory_bytes: int, optional + Default total memory budget in bytes. LanceDB Enterprise only. + total_gpu_count: int, optional + Default total GPU budget across workers. LanceDB Enterprise only. + Returns ------- MaterializedView @@ -818,6 +832,13 @@ class DBConnection(EnforceOverrides): ... query="SELECT kind, count(*) AS n FROM events GROUP BY kind", ... ) """ + _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) raise NotImplementedError( _append_doc_url( "materialized views are not supported on this connection type", @@ -838,6 +859,11 @@ class DBConnection(EnforceOverrides): exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> Job[None]: """Submit materialized-view creation and return its job. @@ -854,6 +880,13 @@ class DBConnection(EnforceOverrides): Servers without early registry-handle support return a connection-scoped query job instead. Its ID cannot be reopened with :meth:`open_job`. """ + _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) raise NotImplementedError( _append_doc_url( "materialized views are not supported on this connection type", @@ -2322,6 +2355,11 @@ class LanceDBConnection(DBConnection): exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. @@ -2349,6 +2387,13 @@ class LanceDBConnection(DBConnection): >>> view.table.count_rows() # doctest: +SKIP 1 """ + _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) LOOP.run( self._conn.create_materialized_view( name, @@ -2361,6 +2406,11 @@ class LanceDBConnection(DBConnection): exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, ) ) return MaterializedView(self.open_table(name)) @@ -2379,7 +2429,19 @@ class LanceDBConnection(DBConnection): exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> Job[None]: + _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) job = LOOP.run( self._conn.create_materialized_view_async( name, @@ -2392,6 +2454,11 @@ class LanceDBConnection(DBConnection): exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, ) ) return Job(job) @@ -3711,6 +3778,11 @@ class AsyncConnection(object): exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> AsyncMaterializedView: """Define a materialized view named ``name`` over the table ``source``. @@ -3723,6 +3795,13 @@ class AsyncConnection(object): See [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. """ + _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) _validate_create_materialized_view(source, query, select, where, limit) if source is not None: source, native_options = await self._materialized_view_source( @@ -3742,7 +3821,12 @@ class AsyncConnection(object): exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, **native_options, + gpu_class=gpu_class, + gpu_count=gpu_count, ) return AsyncMaterializedView(AsyncTable(inner)) @@ -3759,6 +3843,11 @@ class AsyncConnection(object): exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> AsyncJob[None]: """Submit materialized-view creation and return its job. @@ -3769,6 +3858,13 @@ class AsyncConnection(object): Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id`` identifies that query on this connection. """ + _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) _validate_create_materialized_view(source, query, select, where, limit) if source is not None: source, native_options = await self._materialized_view_source( @@ -3788,7 +3884,12 @@ class AsyncConnection(object): exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, **native_options, + gpu_class=gpu_class, + gpu_count=gpu_count, ) return AsyncJob(inner) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index ab8c66b22..ba7241ceb 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -65,15 +65,13 @@ from .schema import is_blob_v2_field as _is_blob_v2_field from ._blob_reader import BlobReader from ._lancedb import _validate_conda_requirement from .secrets import EnvVarSecret +from .resources import _validate_gpu_class_name _Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1) _UInt32 = conint(strict=True, ge=0, le=2**32 - 1) +_PositiveUInt32 = conint(strict=True, ge=1, le=2**32 - 1) _UInt64 = conint(strict=True, ge=0, le=2**64 - 1) -_GPU_CLASS_NAME = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$") -_GPU_CLASS_ERROR = ( - "gpu_class must be a lowercase name of at most 63 letters, digits, or " - "hyphens, and cannot start or end with a hyphen" -) +_PositiveUInt64 = conint(strict=True, ge=1, le=2**64 - 1) def _validate_gpu_wire_marker(value: Any) -> bool: @@ -82,16 +80,24 @@ def _validate_gpu_wire_marker(value: Any) -> bool: return True -def _normalize_gpu_marker(value: bool) -> Optional[bool]: - if not isinstance(value, bool): +def _normalize_gpu_request( + gpu: Optional[bool], gpu_class: Optional[str], gpu_count: Optional[int] +) -> tuple[Optional[bool], Optional[str], Optional[int]]: + if gpu is not None and not isinstance(gpu, bool): raise ValueError("gpu must be a boolean") - return True if value else None - - -def _validate_gpu_class_name(value: Any) -> str: - if not isinstance(value, str) or not _GPU_CLASS_NAME.fullmatch(value): - raise ValueError(_GPU_CLASS_ERROR) - return value + if gpu is not True: + if gpu_class is not None or gpu_count is not None: + raise ValueError("gpu_class and gpu_count require gpu=True") + return None, None, None + if gpu_class is not None: + gpu_class = _validate_gpu_class_name(gpu_class) + if gpu_count is None: + gpu_count = 1 + if isinstance(gpu_count, bool) or not isinstance(gpu_count, int): + raise ValueError("gpu_count must be a positive integer") + if not 1 <= gpu_count <= 2**32 - 1: + raise ValueError("gpu_count must be between 1 and 4294967295") + return True, gpu_class, gpu_count def _validate_batch_size(value: Any) -> Optional[int]: @@ -452,8 +458,10 @@ class PythonRuntimeSpec(_RemoteValue): V1 supports ``kind="python"``. Newer runtime kinds remain readable, while their unknown payload fields are intentionally not retained by the client. - ``kind="python_v2"`` requires ``gpu=True`` and may name an operator-defined - ``gpu_class``. + ``kind="python_v2"`` requires ``gpu=True``. Its ``gpu_class`` records the + requested operator-defined class or ``"any"`` for any eligible class; + omitting it also accepts any eligible class. It does not identify the + hardware selected for execution. """ kind: str @@ -462,6 +470,7 @@ class PythonRuntimeSpec(_RemoteValue): env: Optional[Mapping[str, str]] = None gpu: Optional[bool] = None gpu_class: Optional[str] = None + gpus_per_worker: Optional[_PositiveUInt32] = None @model_validator(mode="before") @classmethod @@ -499,6 +508,8 @@ class PythonRuntimeSpec(_RemoteValue): raise ValueError( "python runtime with gpu_class requires kind='python_v2'" ) + if self.gpus_per_worker is not None: + raise ValueError("gpus_per_worker requires kind='python_v2'") elif self.kind == "python_v2": if self.python_version is None: raise ValueError("python_v2 runtime requires python_version") @@ -512,6 +523,7 @@ class PythonRuntimeSpec(_RemoteValue): object.__setattr__(self, "env", None) object.__setattr__(self, "gpu", None) object.__setattr__(self, "gpu_class", None) + object.__setattr__(self, "gpus_per_worker", None) return self @property @@ -713,8 +725,9 @@ class FunctionVersion(_RemoteValue): version also requires matching the source and all other registration inputs, including signature, Secret bindings, models, and execution controls. - ``gpu_class`` is the operator-defined GPU pool fixed into this Function - version, or ``None`` when registration used the deployment default. + ``gpu_class`` records the default GPU pool for this Function version. + Column/MV creation and refresh can override it independently of the + per-worker ``gpu_count`` in the requested runtime. ``batch_size``, ``max_concurrency``, ``row_timeout_seconds``, and ``result_stability`` retain the execution controls reported by the @@ -749,6 +762,9 @@ class FunctionVersion(_RemoteValue): gpu_class: Optional[str] = None batch_size: Optional[int] = None max_concurrency: Optional[int] = None + total_cpu_millis: Optional[_PositiveUInt64] = None + total_memory_bytes: Optional[_PositiveUInt64] = None + total_gpu_count: Optional[_UInt32] = None row_timeout_seconds: Optional[float] = None result_stability: Optional[str] = None runtime: Optional[PythonRuntimeSpec] = None @@ -941,6 +957,9 @@ class FunctionRegistrationRequest(_RemoteValue): runtime: PythonRuntimeSpec batch_size: Optional[int] = None max_concurrency: Optional[int] = None + total_cpu_millis: Optional[_PositiveUInt64] = None + total_memory_bytes: Optional[_PositiveUInt64] = None + total_gpu_count: Optional[_UInt32] = None row_timeout_seconds: Optional[float] = None retry_policy: Optional[FunctionRetryPolicy] = None secret_bindings: tuple[SecretBinding, ...] = () @@ -3213,8 +3232,12 @@ class FunctionDefinition: max_concurrency: Optional[int] = None, row_timeout_seconds: Optional[float] = None, retry_policy: Optional[FunctionRetryPolicy] = None, - gpu: bool = False, + gpu: Optional[bool] = None, gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, conda: tuple[str, ...] = (), conda_channels: tuple[str, ...] = (), apt: tuple[str, ...] = (), @@ -3235,11 +3258,9 @@ class FunctionDefinition: if conda_channels and not conda: raise ValueError("conda_channels requires conda packages") _validate_package_requirements("conda" if conda else "pip", conda or pip) - gpu_marker = _normalize_gpu_marker(gpu) - if gpu_class is not None: - _validate_gpu_class_name(gpu_class) - if gpu_marker is None: - raise ValueError("gpu_class requires gpu=True") + gpu_marker, gpu_class, gpus_per_worker = _normalize_gpu_request( + gpu, gpu_class, gpu_count + ) packages = tuple(sorted(set(conda if conda else pip))) system_packages = tuple(sorted(set(apt))) if any( @@ -3357,6 +3378,7 @@ class FunctionDefinition: env=environment, gpu=gpu_marker, gpu_class=gpu_class, + gpus_per_worker=gpus_per_worker, ) self._function = function self._request = FunctionRegistrationRequest( @@ -3378,6 +3400,9 @@ class FunctionDefinition: runtime=runtime, batch_size=batch_size, max_concurrency=max_concurrency, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, row_timeout_seconds=row_timeout_seconds, retry_policy=retry_policy, models=models, @@ -3489,8 +3514,12 @@ def function( max_concurrency: Optional[int] = None, row_timeout_seconds: Optional[float] = None, retry_policy: Optional[FunctionRetryPolicy] = None, - gpu: bool = False, + gpu: Optional[bool] = None, gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, conda: tuple[str, ...] | list[str] = (), conda_channels: tuple[str, ...] | list[str] = (), apt: tuple[str, ...] | list[str] = (), @@ -3513,8 +3542,12 @@ def function( max_concurrency: Optional[int] = None, row_timeout_seconds: Optional[float] = None, retry_policy: Optional[FunctionRetryPolicy] = None, - gpu: bool = False, + gpu: Optional[bool] = None, gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, conda: tuple[str, ...] | list[str] = (), conda_channels: tuple[str, ...] | list[str] = (), apt: tuple[str, ...] | list[str] = (), @@ -3735,16 +3768,27 @@ def function( and backoff. A refresh may override this default. Retrying a partial call must be safe; completed calls are not repeated. For batch Functions, skip after exhaustion applies to the whole failed call. - gpu : bool, default False - Whether every remote execution requires a GPU. The execution platform - selects one compatible GPU for each worker. The requirement is part of - the immutable Function version. + gpu : bool, optional + Enable GPU execution. Defaults to CPU execution. gpu_class : str, optional - Operator-defined GPU class for every execution of this Function, such - as ``"a10g"`` or ``"h100"``. Requires ``gpu=True`` and follows the - lowercase 63-character DNS-label rule. The class is part of the - immutable Function version; per-refresh aggregate GPU budgets are - selected through ``refresh_column`` instead of registration. + Select an operator-configured GPU pool, such as ``"h100"``. + Requires ``gpu=True``. Omitting it is equivalent to ``"any"`` and accepts + any eligible configured GPU class. Use ``"default"`` to select the + deployment's default pool explicitly. + gpu_count : int, optional + Default GPUs allocated together to each Function worker. Requires ``gpu=True`` + and defaults to one. Column/MV creation and refresh can override it. + Must be a positive integer. Refresh + ``total_gpu_count`` limits the total GPUs across the worker fleet. + total_cpu_millis : int, optional + Default total CPU budget for an execution, in millicores (1000 = one + core). A column/MV declaration or refresh may override this value. + total_memory_bytes : int, optional + Default total memory budget for an execution, in bytes. + total_gpu_count : int, optional + Default total GPU budget across an execution's workers. This is + separate from ``gpu_count``, which allocates GPUs to each worker. + MVs add the defaults of their distinct pinned Function versions. code : sequence of module, optional Top-level modules or packages shipped with the Function and importable by their own names. Package resources, including binary data and @@ -3788,13 +3832,13 @@ def function( ... return value >>> batch_identity(pa.array([1, 2, 3])).to_pylist() [1, 2, 3] - >>> @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") + >>> @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g", gpu_count=2) ... def gpu_score(value: int) -> int: ... return value * 2 >>> gpu_score.registration_request.runtime.gpu True - >>> gpu_score.registration_request.runtime.gpu_class - 'a10g' + >>> gpu_score.registration_request.runtime.gpus_per_worker + 2 >>> @function ... class scale: ... def __init__(self, factor: float, offset: float = 0.0): @@ -3871,6 +3915,10 @@ def function( retry_policy=retry_policy, gpu=gpu, gpu_class=gpu_class, + gpu_count=gpu_count, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, conda=tuple(conda), conda_channels=tuple(conda_channels), apt=tuple(apt), diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py index dc04f89f8..28f7d9401 100644 --- a/python/python/lancedb/materialized_view.py +++ b/python/python/lancedb/materialized_view.py @@ -17,9 +17,9 @@ from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, Union import json from dataclasses import dataclass -from .functions import _validate_gpu_class_name from .background_loop import LOOP from .job import AsyncJob, Job, _typed_job +from .resources import _resource_options if TYPE_CHECKING: import pyarrow as pa @@ -167,31 +167,16 @@ def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]: return normalized -def _refresh_execution_options(cpu_millis, memory_bytes, gpu_count, gpu_class): - values = { - "cpu_millis": cpu_millis, - "memory_bytes": memory_bytes, - "gpu_count": gpu_count, - } - for name, value in values.items(): - maximum = 2**32 - 1 if name == "gpu_count" else 2**64 - 1 - minimum = 0 if name == "gpu_count" else 1 - if value is not None and ( - type(value) is not int or not minimum <= value <= maximum - ): - raise ValueError( - f"{name} must be an integer between {minimum} and {maximum}" - ) - if (cpu_millis is not None or memory_bytes is not None) and any( - value is None for value in values.values() - ): - raise ValueError( - "cpu_millis, memory_bytes, and gpu_count must be specified together" - ) - if gpu_class is not None: - values["gpu_class"] = _validate_gpu_class_name(gpu_class) - if gpu_count == 0: - raise ValueError("gpu_class requires a positive GPU budget") +def _refresh_execution_options( + total_cpu_millis, total_memory_bytes, total_gpu_count, gpu_class, gpu_count=None +): + values = _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) return {name: value for name, value in values.items() if value is not None} @@ -228,10 +213,11 @@ class AsyncMaterializedView: *, full: bool = False, source_version: Optional[int] = None, - cpu_millis: Optional[int] = None, - memory_bytes: Optional[int] = None, - gpu_count: Optional[int] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> "RefreshMaterializedViewResult": """Recompute the view from its source. @@ -240,11 +226,14 @@ class AsyncMaterializedView: and ``source_version`` selects a source version instead of the latest. LanceDB Enterprise SQL refreshes do not support source-version pinning. - ``cpu_millis`` (1000 = one core), ``memory_bytes``, and ``gpu_count`` - cap aggregate resources for this execution, including its Function - processes. CPU or memory requires all three budget fields; GPU count - may be zero for CPU-only views. ``gpu_class`` selects an operator-defined - GPU class for this execution only. Omitted options preserve defaults. + ``total_cpu_millis`` (1000 = one core), ``total_memory_bytes``, and + ``total_gpu_count`` cap aggregate resources for this execution, + including its Function processes. Each resource may be overridden + independently. Unset values inherit the view defaults, then the sum + across distinct pinned Functions, then deployment defaults. GPU count + may be zero for CPU-only views. + ``gpu_class`` selects an operator-defined GPU class for this execution + only. Omitted options preserve defaults. These options require an Enterprise backend that enforces isolation; Embedded refreshes reject them. Other servers may reject the new options. @@ -256,7 +245,11 @@ class AsyncMaterializedView: source_version=source_version, full=full, **_refresh_execution_options( - cpu_millis, memory_bytes, gpu_count, gpu_class + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count=gpu_count, ), ) @@ -265,10 +258,11 @@ class AsyncMaterializedView: *, full: bool = False, source_version: Optional[int] = None, - cpu_millis: Optional[int] = None, - memory_bytes: Optional[int] = None, - gpu_count: Optional[int] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> "AsyncJob[RefreshMaterializedViewResult]": """Submit a refresh and return its job without waiting. @@ -289,7 +283,11 @@ class AsyncMaterializedView: source_version=source_version, full=full, **_refresh_execution_options( - cpu_millis, memory_bytes, gpu_count, gpu_class + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count=gpu_count, ), ), RefreshMaterializedViewResult.from_json, @@ -326,10 +324,11 @@ class MaterializedView: *, full: bool = False, source_version: Optional[int] = None, - cpu_millis: Optional[int] = None, - memory_bytes: Optional[int] = None, - gpu_count: Optional[int] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> "RefreshMaterializedViewResult": """Recompute the view from its source. See [AsyncMaterializedView.refresh][lancedb.materialized_view.AsyncMaterializedView.refresh].""" @@ -338,7 +337,11 @@ class MaterializedView: full=full, source_version=source_version, **_refresh_execution_options( - cpu_millis, memory_bytes, gpu_count, gpu_class + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count=gpu_count, ), ) ) @@ -348,10 +351,11 @@ class MaterializedView: *, full: bool = False, source_version: Optional[int] = None, - cpu_millis: Optional[int] = None, - memory_bytes: Optional[int] = None, - gpu_count: Optional[int] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> "Job[RefreshMaterializedViewResult]": """Submit a refresh and return its job without waiting. @@ -364,7 +368,11 @@ class MaterializedView: full=full, source_version=source_version, **_refresh_execution_options( - cpu_millis, memory_bytes, gpu_count, gpu_class + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count=gpu_count, ), ) ) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index ff75c22f1..bee9576c2 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -738,6 +738,11 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, exist_ok: bool = False, ) -> "MaterializedView": """Define a materialized view over a table in the root namespace. @@ -757,7 +762,12 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, exist_ok=exist_ok, + gpu_class=gpu_class, + gpu_count=gpu_count, ) ).name ) @@ -776,6 +786,11 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, exist_ok: bool = False, ) -> Job[None]: job = LOOP.run( @@ -789,7 +804,12 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, exist_ok=exist_ok, + gpu_class=gpu_class, + gpu_count=gpu_count, ) ) return Job(job) @@ -1396,6 +1416,11 @@ class AsyncLanceNamespaceDBConnection: with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, exist_ok: bool = False, ) -> "AsyncMaterializedView": """Define a materialized view over a table in the root namespace.""" @@ -1409,7 +1434,12 @@ class AsyncLanceNamespaceDBConnection: with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, exist_ok=exist_ok, + gpu_class=gpu_class, + gpu_count=gpu_count, ) # Reopen through the namespace so the view's table carries the # namespace client and pushdown configuration a bare inner table lacks. @@ -1427,6 +1457,11 @@ class AsyncLanceNamespaceDBConnection: with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, exist_ok: bool = False, ) -> AsyncJob[None]: """Submit materialized-view creation and return its job.""" @@ -1440,7 +1475,12 @@ class AsyncLanceNamespaceDBConnection: with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, exist_ok=exist_ok, + gpu_class=gpu_class, + gpu_count=gpu_count, ) async def open_materialized_view(self, name: str) -> "AsyncMaterializedView": diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 1e550b003..bf2f5669f 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -62,6 +62,7 @@ from lance_namespace import ( from ..pydantic import LanceModel from ..table import Table from ..util import validate_table_name +from ..resources import _resource_options def _duration_seconds(value: Optional[timedelta]) -> Optional[float]: @@ -822,7 +823,19 @@ class RemoteDBConnection(DBConnection): exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> MaterializedView: + _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) from .table import RemoteTable view = LOOP.run( @@ -837,6 +850,11 @@ class RemoteDBConnection(DBConnection): exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, ) ) return MaterializedView( @@ -862,7 +880,19 @@ class RemoteDBConnection(DBConnection): exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> Job[None]: + _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) job = LOOP.run( self._conn.create_materialized_view_async( name, @@ -875,6 +905,11 @@ class RemoteDBConnection(DBConnection): exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, ) ) return Job(job) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index b96a3c80e..2b723d0d4 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1200,7 +1200,9 @@ class RemoteTable(Table): computed: Dict[str, str] | None = None, auto_refresh_enabled: bool | None = None, auto_refresh_interval_seconds: int | None = None, - auto_refresh_resource_budget: Optional[Dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, ) -> AddColumnsResult: return LOOP.run( self._table.add_columns( @@ -1208,7 +1210,9 @@ class RemoteTable(Table): computed=computed, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, - auto_refresh_resource_budget=auto_refresh_resource_budget, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, ) ) @@ -1220,11 +1224,12 @@ class RemoteTable(Table): batch_size: Optional[int] = None, max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, - resource_budget: Optional[Dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, supervisor_resources: Optional[Dict[str, int]] = None, planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, - gpu_count: Optional[int] = None, + total_gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, max_failed_fraction: Optional[float] = None, @@ -1247,11 +1252,12 @@ class RemoteTable(Table): batch_size=batch_size, max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, - resource_budget=resource_budget, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, supervisor_resources=supervisor_resources, planning_workers=planning_workers, gpu_class=gpu_class, - gpu_count=gpu_count, + total_gpu_count=total_gpu_count, retry_policy=retry_policy, error_policy=error_policy, max_failed_fraction=max_failed_fraction, @@ -1277,11 +1283,12 @@ class RemoteTable(Table): batch_size: Optional[int] = None, max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, - resource_budget: Optional[Dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, supervisor_resources: Optional[Dict[str, int]] = None, planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, - gpu_count: Optional[int] = None, + total_gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, max_failed_fraction: Optional[float] = None, @@ -1305,11 +1312,12 @@ class RemoteTable(Table): batch_size=batch_size, max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, - resource_budget=resource_budget, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, supervisor_resources=supervisor_resources, planning_workers=planning_workers, gpu_class=gpu_class, - gpu_count=gpu_count, + total_gpu_count=total_gpu_count, retry_policy=retry_policy, error_policy=error_policy, max_failed_fraction=max_failed_fraction, diff --git a/python/python/lancedb/resources.py b/python/python/lancedb/resources.py new file mode 100644 index 000000000..f37d48612 --- /dev/null +++ b/python/python/lancedb/resources.py @@ -0,0 +1,48 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import re +from typing import Any, Optional, Union + + +def _validate_gpu_class_name(value: Any) -> str: + if not isinstance(value, str) or not re.fullmatch( + r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", value + ): + raise ValueError( + "gpu_class must be a lowercase name of at most 63 letters, digits, or " + "hyphens, and cannot start or end with a hyphen" + ) + return value + + +def _resource_options( + cpu: Optional[int], + memory: Optional[int], + gpu: Optional[int], + *, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, +) -> dict[str, Union[int, str]]: + result: dict[str, Union[int, str]] = {} + for name, value, maximum, minimum in ( + ("total_cpu_millis", cpu, 2**64 - 1, 1), + ("total_memory_bytes", memory, 2**64 - 1, 1), + ("total_gpu_count", gpu, 2**32 - 1, 0), + ("gpu_count", gpu_count, 2**32 - 1, 1), + ): + if value is None: + continue + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"{name} must be an integer") + if not minimum <= value <= maximum: + raise ValueError(f"{name} must be between {minimum} and {maximum}") + result[name] = value + if gpu_class is not None: + result["gpu_class"] = _validate_gpu_class_name(gpu_class) + if gpu is not None and ( + (gpu_count is not None and gpu_count > gpu) + or (gpu_class is not None and gpu == 0) + ): + raise ValueError("total_gpu_count cannot fit one Function worker") + return result diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 71688a56e..bcc540517 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -132,6 +132,7 @@ from .schema import ( row_addressable_blob_v2_paths, schema_has_blob_field, ) +from .resources import _resource_options def _should_push_down_query_table( @@ -3456,7 +3457,11 @@ class Table(ABC): computed: Dict[str, str] | None = None, auto_refresh_enabled: bool | None = None, auto_refresh_interval_seconds: int | None = None, - auto_refresh_resource_budget: Optional[Dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ): """ Add new columns with defined values. @@ -3525,13 +3530,12 @@ class Table(ABC): When omitted, the server determines when to refresh. Applies to every computed output in this call. Scheduling options require computed or Function columns. - auto_refresh_resource_budget: dict[str, int], optional - Aggregate CPU, memory, and GPU budget for automatic refreshes of a - registered Function declaration. ``cpu_millis`` and - ``memory_bytes`` are required; ``gpu_count`` defaults to zero. - This option cannot be used with SQL-expression columns. LanceDB - Enterprise only. - + total_cpu_millis: int, optional + Default total CPU budget for manual and automatic Function refreshes. + total_memory_bytes: int, optional + Default total memory budget for these refreshes, in bytes. + total_gpu_count: int, optional + Default total GPU budget across the Function workers. Returns ------- AddColumnsResult @@ -3556,6 +3560,13 @@ class Table(ABC): >>> table.to_arrow()["score"].to_pylist() [0.25, 0.75] """ + _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) @abstractmethod def refresh_column( @@ -3566,11 +3577,13 @@ class Table(ABC): batch_size: Optional[int] = None, max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, - resource_budget: Optional[Dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, supervisor_resources: Optional[Dict[str, int]] = None, planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + total_gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, max_failed_fraction: Optional[float] = None, @@ -3625,13 +3638,10 @@ class Table(ABC): actual publication boundary can be larger than this threshold because it also depends on completed work and Function batching. LanceDB Enterprise only; local refreshes reject this option. - resource_budget: dict[str, int], optional - Aggregate resources for one registered Function refresh. The - ``cpu_millis`` and ``memory_bytes`` keys are required; - ``gpu_count`` is optional and defaults to zero, which requests a - CPU-only budget. This budget cannot be combined with the top-level - ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes - reject it. + total_cpu_millis: int, optional + Override the total CPU budget in millicores for this refresh. + total_memory_bytes: int, optional + Override the total memory budget in bytes for this refresh. supervisor_resources: dict[str, int], optional CPU, memory, and ephemeral-storage limits for the Function refresh supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and @@ -3648,11 +3658,10 @@ class Table(ABC): letters, digits, or hyphens, without a leading or trailing hyphen. None keeps the Function's registered class or the deployment default. LanceDB Enterprise only. - gpu_count: int, optional - Positive aggregate GPU budget for Function workers without changing - the deployment's CPU and memory defaults. None leaves the server's - configured budget unchanged. For a complete CPU and memory budget, - use ``resource_budget`` instead. LanceDB Enterprise only. + total_gpu_count: int, optional + Nonnegative total GPU budget for Function workers without changing + the other resource limits. Unspecified resources inherit column defaults, + then Function defaults, then deployment defaults. LanceDB Enterprise only. retry_policy: FunctionRetryPolicy, optional Override retries of failed user-code calls. Only use when repeating partial work is safe. Set max_attempts=1 to disable retries. @@ -3675,7 +3684,7 @@ class Table(ABC): Deadline for Function initialization. LanceDB Enterprise only. num_workers: int, optional Worker count for an expression column; registered Function - columns reject it and use ``resource_budget`` instead. LanceDB + columns reject it and set the corresponding ``total_*`` options. LanceDB Enterprise only. max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB @@ -3714,11 +3723,13 @@ class Table(ABC): batch_size: Optional[int] = None, max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, - resource_budget: Optional[Dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, supervisor_resources: Optional[Dict[str, int]] = None, planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + total_gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, max_failed_fraction: Optional[float] = None, @@ -3772,13 +3783,10 @@ class Table(ABC): actual publication boundary can be larger than this threshold because it also depends on completed work and Function batching. LanceDB Enterprise only; local refreshes reject this option. - resource_budget: dict[str, int], optional - Aggregate resources for one registered Function refresh. The - ``cpu_millis`` and ``memory_bytes`` keys are required; - ``gpu_count`` is optional and defaults to zero, which requests a - CPU-only budget. This budget cannot be combined with the top-level - ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes - reject it. + total_cpu_millis: int, optional + Override the total CPU budget in millicores for this refresh. + total_memory_bytes: int, optional + Override the total memory budget in bytes for this refresh. supervisor_resources: dict[str, int], optional CPU, memory, and ephemeral-storage limits for the Function refresh supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and @@ -3795,11 +3803,10 @@ class Table(ABC): letters, digits, or hyphens, without a leading or trailing hyphen. None keeps the Function's registered class or the deployment default. LanceDB Enterprise only. - gpu_count: int, optional - Positive aggregate GPU budget for Function workers without changing - the deployment's CPU and memory defaults. None leaves the server's - configured budget unchanged. For a complete CPU and memory budget, - use ``resource_budget`` instead. LanceDB Enterprise only. + total_gpu_count: int, optional + Nonnegative total GPU budget for Function workers without changing + the other resource limits. Unspecified resources inherit column defaults, + then Function defaults, then deployment defaults. LanceDB Enterprise only. retry_policy: FunctionRetryPolicy, optional Override retries of failed user-code calls. Only use when repeating partial work is safe. Set max_attempts=1 to disable retries. @@ -3822,7 +3829,7 @@ class Table(ABC): Deadline for Function initialization. LanceDB Enterprise only. num_workers: int, optional Worker count for an expression column; registered Function - columns reject it and use ``resource_budget`` instead. LanceDB + columns reject it and set the corresponding ``total_*`` options. LanceDB Enterprise only. max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB @@ -6485,15 +6492,30 @@ class LanceTable(Table): computed: Dict[str, str] | None = None, auto_refresh_enabled: bool | None = None, auto_refresh_interval_seconds: int | None = None, - auto_refresh_resource_budget: Optional[Dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> AddColumnsResult: + _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) return LOOP.run( self._table.add_columns( transforms, computed=computed, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, - auto_refresh_resource_budget=auto_refresh_resource_budget, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, + total_gpu_count=total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, ) ) @@ -6505,11 +6527,13 @@ class LanceTable(Table): batch_size: Optional[int] = None, max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, - resource_budget: Optional[Dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, supervisor_resources: Optional[Dict[str, int]] = None, planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + total_gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, max_failed_fraction: Optional[float] = None, @@ -6535,11 +6559,12 @@ class LanceTable(Table): batch_size=batch_size, max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, - resource_budget=resource_budget, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, supervisor_resources=supervisor_resources, planning_workers=planning_workers, gpu_class=gpu_class, - gpu_count=gpu_count, + total_gpu_count=total_gpu_count, retry_policy=retry_policy, error_policy=error_policy, max_failed_fraction=max_failed_fraction, @@ -6554,6 +6579,7 @@ class LanceTable(Table): include_quarantined=include_quarantined, function_version=function_version, recompute=recompute, + gpu_count=gpu_count, ) ) @@ -6565,11 +6591,13 @@ class LanceTable(Table): batch_size: Optional[int] = None, max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, - resource_budget: Optional[Dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, supervisor_resources: Optional[Dict[str, int]] = None, planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + total_gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, max_failed_fraction: Optional[float] = None, @@ -6597,11 +6625,12 @@ class LanceTable(Table): batch_size=batch_size, max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, - resource_budget=resource_budget, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, supervisor_resources=supervisor_resources, planning_workers=planning_workers, gpu_class=gpu_class, - gpu_count=gpu_count, + total_gpu_count=total_gpu_count, retry_policy=retry_policy, error_policy=error_policy, max_failed_fraction=max_failed_fraction, @@ -6616,6 +6645,7 @@ class LanceTable(Table): include_quarantined=include_quarantined, function_version=function_version, recompute=recompute, + gpu_count=gpu_count, ) ) ) @@ -9033,7 +9063,11 @@ class AsyncTable: computed: dict[str, str] | None = None, auto_refresh_enabled: bool | None = None, auto_refresh_interval_seconds: int | None = None, - auto_refresh_resource_budget: Optional[Dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, + total_gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, + gpu_count: Optional[int] = None, ) -> AddColumnsResult: """ Add new columns with defined values. @@ -9100,13 +9134,12 @@ class AsyncTable: not force recomputation. Applies to every declared computed output. These options cannot be used with one-time transforms or ordinary all-null columns. - auto_refresh_resource_budget: dict[str, int], optional - Aggregate CPU, memory, and GPU budget for automatic refreshes of - registered Function outputs. ``cpu_millis`` and ``memory_bytes`` - are required; ``gpu_count`` defaults to zero. SQL-expression - columns do not use Function workers and reject this option. - LanceDB Enterprise only. - + total_cpu_millis: int, optional + Default total CPU budget for manual and automatic Function refreshes. + total_memory_bytes: int, optional + Default total memory budget for these refreshes, in bytes. + total_gpu_count: int, optional + Default total GPU budget across the Function workers. Examples -------- >>> await table.add_columns( # doctest: +SKIP @@ -9121,6 +9154,13 @@ class AsyncTable: version: the new version number of the table after adding columns. """ + _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) if auto_refresh_enabled is not None and type(auto_refresh_enabled) is not bool: raise ValueError("auto_refresh_enabled must be a boolean") if auto_refresh_interval_seconds is not None and ( @@ -9134,7 +9174,11 @@ class AsyncTable: options_supplied = ( auto_refresh_enabled is not None or auto_refresh_interval_seconds is not None - or auto_refresh_resource_budget is not None + or total_cpu_millis is not None + or total_memory_bytes is not None + or total_gpu_count is not None + or gpu_class is not None + or gpu_count is not None ) function_application = None function_output_name = None @@ -9163,7 +9207,11 @@ class AsyncTable: function_output_name, auto_refresh_enabled, auto_refresh_interval_seconds, - auto_refresh_resource_budget, + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count, ) if isinstance(transforms, pa.Field): @@ -9184,7 +9232,11 @@ class AsyncTable: list(computed.items()), auto_refresh_enabled, auto_refresh_interval_seconds, - auto_refresh_resource_budget, + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count, ) if options_supplied: raise ValueError( @@ -9208,11 +9260,13 @@ class AsyncTable: batch_size: Optional[int] = None, max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, - resource_budget: Optional[Dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, supervisor_resources: Optional[Dict[str, int]] = None, planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + total_gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, max_failed_fraction: Optional[float] = None, @@ -9267,13 +9321,10 @@ class AsyncTable: actual publication boundary can be larger than this threshold because it also depends on completed work and Function batching. LanceDB Enterprise only; local refreshes reject this option. - resource_budget: dict[str, int], optional - Aggregate resources for one registered Function refresh. The - ``cpu_millis`` and ``memory_bytes`` keys are required; - ``gpu_count`` is optional and defaults to zero, which requests a - CPU-only budget. This budget cannot be combined with the top-level - ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes - reject it. + total_cpu_millis: int, optional + Override the total CPU budget in millicores for this refresh. + total_memory_bytes: int, optional + Override the total memory budget in bytes for this refresh. supervisor_resources: dict[str, int], optional CPU, memory, and ephemeral-storage limits for the Function refresh supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and @@ -9290,11 +9341,10 @@ class AsyncTable: letters, digits, or hyphens, without a leading or trailing hyphen. None keeps the Function's registered class or the deployment default. LanceDB Enterprise only. - gpu_count: int, optional - Positive aggregate GPU budget for Function workers without changing - the deployment's CPU and memory defaults. None leaves the server's - configured budget unchanged. For a complete CPU and memory budget, - use ``resource_budget`` instead. LanceDB Enterprise only. + total_gpu_count: int, optional + Nonnegative total GPU budget for Function workers without changing + the other resource limits. Unspecified resources inherit column defaults, + then Function defaults, then deployment defaults. LanceDB Enterprise only. retry_policy: FunctionRetryPolicy, optional Override retries of failed user-code calls. Only use when repeating partial work is safe. Set max_attempts=1 to disable retries. @@ -9317,7 +9367,7 @@ class AsyncTable: Deadline for Function initialization. LanceDB Enterprise only. num_workers: int, optional Worker count for an expression column; registered Function - columns reject it and use ``resource_budget`` instead. LanceDB + columns reject it and set the corresponding ``total_*`` options. LanceDB Enterprise only. max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB @@ -9345,17 +9395,25 @@ class AsyncTable: RefreshColumnResult The number of rows filled and the new version of the table. """ + _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) return await self._inner.refresh_column( column, where=where, batch_size=batch_size, max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, - resource_budget=resource_budget, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, supervisor_resources=supervisor_resources, planning_workers=planning_workers, gpu_class=gpu_class, - gpu_count=gpu_count, + total_gpu_count=total_gpu_count, retry_policy=None if retry_policy is None else FunctionRetryPolicy.model_validate(retry_policy).model_dump_json(), @@ -9372,6 +9430,7 @@ class AsyncTable: include_quarantined=include_quarantined, function_version=function_version, recompute=recompute, + gpu_count=gpu_count, ) async def retry_failed( @@ -9579,11 +9638,13 @@ class AsyncTable: batch_size: Optional[int] = None, max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, - resource_budget: Optional[Dict[str, int]] = None, + total_cpu_millis: Optional[int] = None, + total_memory_bytes: Optional[int] = None, supervisor_resources: Optional[Dict[str, int]] = None, planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + total_gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, max_failed_fraction: Optional[float] = None, @@ -9637,13 +9698,10 @@ class AsyncTable: actual publication boundary can be larger than this threshold because it also depends on completed work and Function batching. LanceDB Enterprise only; local refreshes reject this option. - resource_budget: dict[str, int], optional - Aggregate resources for one registered Function refresh. The - ``cpu_millis`` and ``memory_bytes`` keys are required; - ``gpu_count`` is optional and defaults to zero, which requests a - CPU-only budget. This budget cannot be combined with the top-level - ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes - reject it. + total_cpu_millis: int, optional + Override the total CPU budget in millicores for this refresh. + total_memory_bytes: int, optional + Override the total memory budget in bytes for this refresh. supervisor_resources: dict[str, int], optional CPU, memory, and ephemeral-storage limits for the Function refresh supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and @@ -9660,11 +9718,10 @@ class AsyncTable: letters, digits, or hyphens, without a leading or trailing hyphen. None keeps the Function's registered class or the deployment default. LanceDB Enterprise only. - gpu_count: int, optional - Positive aggregate GPU budget for Function workers without changing - the deployment's CPU and memory defaults. None leaves the server's - configured budget unchanged. For a complete CPU and memory budget, - use ``resource_budget`` instead. LanceDB Enterprise only. + total_gpu_count: int, optional + Nonnegative total GPU budget for Function workers without changing + the other resource limits. Unspecified resources inherit column defaults, + then Function defaults, then deployment defaults. LanceDB Enterprise only. retry_policy: FunctionRetryPolicy, optional Override retries of failed user-code calls. Only use when repeating partial work is safe. Set max_attempts=1 to disable retries. @@ -9687,7 +9744,7 @@ class AsyncTable: Deadline for Function initialization. LanceDB Enterprise only. num_workers: int, optional Worker count for an expression column; registered Function - columns reject it and use ``resource_budget`` instead. LanceDB + columns reject it and set the corresponding ``total_*`` options. LanceDB Enterprise only. max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB @@ -9731,6 +9788,13 @@ class AsyncTable: >>> asyncio.run(refresh_in_background()) # doctest: +SKIP 'finished' """ + _resource_options( + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=gpu_class, + gpu_count=gpu_count, + ) return _typed_job( await self._inner.refresh_column_async( column, @@ -9738,11 +9802,12 @@ class AsyncTable: batch_size=batch_size, max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, - resource_budget=resource_budget, + total_cpu_millis=total_cpu_millis, + total_memory_bytes=total_memory_bytes, supervisor_resources=supervisor_resources, planning_workers=planning_workers, gpu_class=gpu_class, - gpu_count=gpu_count, + total_gpu_count=total_gpu_count, retry_policy=None if retry_policy is None else FunctionRetryPolicy.model_validate(retry_policy).model_dump_json(), @@ -9759,6 +9824,7 @@ class AsyncTable: include_quarantined=include_quarantined, function_version=function_version, recompute=recompute, + gpu_count=gpu_count, ), RefreshColumnJobResult.from_json, ) diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index 004aca90c..99f891ecb 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -22,6 +22,7 @@ from lancedb.functions import ( SecretReference, ) from lancedb.table import AsyncTable +from lancedb.resources import _resource_options FIXTURES = ( @@ -614,7 +615,11 @@ class _FunctionDeclarationInner: output_name, auto_refresh_enabled, auto_refresh_interval_seconds, - auto_refresh_resource_budget, + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class=None, + gpu_count=None, ): self.calls.append( ( @@ -622,7 +627,9 @@ class _FunctionDeclarationInner: output_name, auto_refresh_enabled, auto_refresh_interval_seconds, - auto_refresh_resource_budget, + total_cpu_millis, + total_memory_bytes, + total_gpu_count, ) ) return "declared" @@ -648,18 +655,22 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica ) assert result == "declared" assert inner.calls[-1][1] == "features" - assert inner.calls[-1][2:] == (None, None, None) + assert inner.calls[-1][2:] == (None, None, None, None, None) bare = application._copy(update={"columns": {}}).rename( columns={"normalized_text": "search_text"} ) result = await table.add_columns( - bare, auto_refresh_enabled=False, auto_refresh_interval_seconds=300 + bare, + auto_refresh_enabled=False, + auto_refresh_interval_seconds=300, + total_cpu_millis=8000, + total_gpu_count=0, ) assert result == "declared" assert inner.calls[-1][1] is None assert inner.calls[-1][0]["columns"] == {"normalized_text": "search_text"} - assert inner.calls[-1][2:] == (False, 300, None) + assert inner.calls[-1][2:] == (False, 300, 8000, None, 0) @pytest.mark.asyncio @@ -715,3 +726,20 @@ def test_rename_requires_named_struct_and_keeps_partial_mapping_immutable(): renamed = application.rename(columns={"normalized_text": "search_text"}) assert dict(application.columns) == {} assert dict(renamed.columns) == {"normalized_text": "search_text"} + + +@pytest.mark.parametrize("gpu_count", [0, -1, True, 1.5, 2**32]) +def test_gpu_worker_count_rejects_invalid_values(gpu_count): + with pytest.raises(ValueError, match="gpu_count"): + _resource_options(None, None, None, gpu_count=gpu_count) + + +def test_gpu_worker_settings_are_separate_from_execution_totals(): + assert _resource_options(8000, None, 8, gpu_class="any", gpu_count=2) == { + "total_cpu_millis": 8000, + "total_gpu_count": 8, + "gpu_class": "any", + "gpu_count": 2, + } + with pytest.raises(ValueError, match="cannot fit"): + _resource_options(None, None, 1, gpu_count=2) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index dbc574e88..b3662e582 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -833,7 +833,7 @@ def test_function_image_requires_digest_reference(image): def test_function_gpu_marker_uses_gpu_runtime(): with pytest.warns(UserWarning, match="uses a scalar callable"): - @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") + @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g", gpu_count=2) def double_on_gpu(value: int) -> int: return value * 2 @@ -841,6 +841,7 @@ def test_function_gpu_marker_uses_gpu_runtime(): assert request["runtime"]["kind"] == "python_v2" assert request["runtime"]["gpu"] is True assert request["runtime"]["gpu_class"] == "a10g" + assert request["runtime"]["gpus_per_worker"] == 2 @function(pip=["pyarrow"]) def cpu_function(value: int) -> int: @@ -856,14 +857,29 @@ def test_function_gpu_marker_uses_gpu_runtime(): def identity(value: int) -> int: return value - for invalid in [None, 0, 1, -1, 1.5, "", "true", "1", "H100"]: - with pytest.raises(ValueError, match="gpu must be a boolean"): + for invalid in [ + 0, + 1, + -1, + 1.5, + "", + "true", + "1", + "a_b", + "-a10g", + "a10g-", + "a" * 64, + ]: + with pytest.raises(ValueError, match="gpu"): function(name="invalid_gpu", gpu=invalid)(identity) - for invalid in ["H100", "a_b", "-a10g", "a10g-", "a" * 64]: + for enabled in (None, False): + for options in ({"gpu_class": "h100"}, {"gpu_count": 2}): + with pytest.raises(ValueError, match="require gpu=True"): + function(gpu=enabled, **options)(identity) + for invalid_class in ("H100", "a_b", "-h100", "h100-", "", "a" * 64): with pytest.raises(ValueError, match="gpu_class"): - function(name="invalid_gpu_class", gpu=True, gpu_class=invalid)(identity) - with pytest.raises(ValueError, match="requires gpu=True"): - function(name="gpu_class_without_gpu", gpu_class="a10g")(identity) + function(gpu=True, gpu_class=invalid_class)(identity) + assert function(gpu=False)(identity).registration_request.runtime.gpu is None base_runtime = { "kind": "python_v2", @@ -895,6 +911,66 @@ class _GpuArrayFunction: return value +@pytest.mark.parametrize( + "name, count", [(None, 1), ("h100", 2), ("a10g", 4), ("any", 2)] +) +def test_gpu_count_is_part_of_runtime_identity(name, count): + with pytest.warns(UserWarning): + definition = function(gpu=True, gpu_class=name, gpu_count=count)( + normalize_score.__wrapped__ + ) + runtime = definition.registration_request.runtime + assert runtime.gpu is True + assert runtime.gpu_class == name + assert runtime.gpus_per_worker == count + encoded = definition.registration_request.to_canonical_json() + assert json.loads(encoded)["runtime"]["gpus_per_worker"] == count + different = runtime._copy(update={"gpus_per_worker": count + 1}) + assert runtime.digest != different.digest + + +@pytest.mark.parametrize("count", [0, -1, True, 1.5, "2", 2**32]) +def test_gpu_annotation_rejects_invalid_counts(count): + with pytest.raises(ValueError, match="gpu_count"): + function(gpu=True, gpu_count=count)(normalize_score.__wrapped__) + + +@pytest.mark.parametrize("count", [0, -1, True, 1.5, "2", 2**32]) +def test_gpu_wire_count_is_a_strict_positive_uint32(count): + with pytest.raises(ValueError): + PythonRuntimeSpec.model_validate( + { + "kind": "python_v2", + "python_version": "3.12", + "environment": {"kind": "pip"}, + "gpu": True, + "gpus_per_worker": count, + } + ) + + +def test_function_annotation_carries_independent_total_defaults(): + definition = function( + total_cpu_millis=8000, + total_memory_bytes=16 * 1024**3, + total_gpu_count=0, + )(normalize_score.__wrapped__) + request = json.loads(definition.registration_request.to_canonical_json()) + assert request["total_cpu_millis"] == 8000 + assert request["total_memory_bytes"] == 16 * 1024**3 + assert request["total_gpu_count"] == 0 + assert "gpu" not in request["runtime"] + for values in ( + {"total_cpu_millis": 0}, + {"total_memory_bytes": True}, + {"total_memory_bytes": 2**64}, + {"total_gpu_count": -1}, + {"total_gpu_count": 2**32}, + ): + with pytest.raises(ValueError): + function(**values)(normalize_score.__wrapped__) + + def test_gpu_scalar_warning_names_the_vectorized_alternative(): with pytest.warns(UserWarning, match="model batch is not inferred"): diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index a006c6529..8aac9698c 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -68,8 +68,12 @@ def mock_remote_materialized_view_refresh(): "resources", [ {}, - {"gpu_count": 2, "gpu_class": "h100"}, - {"cpu_millis": 8000, "memory_bytes": 16 * 1024**3, "gpu_count": 0}, + {"total_gpu_count": 2, "gpu_class": "h100"}, + { + "total_cpu_millis": 8000, + "total_memory_bytes": 16 * 1024**3, + "total_gpu_count": 0, + }, ], ) async def test_remote_refresh_reports_unknown_metrics( @@ -159,13 +163,12 @@ async def test_remote_refresh_reports_unknown_metrics( assert expected.encode() in refresh previous = len(server.commands) for invalid in [ - {"cpu_millis": 0}, - {"memory_bytes": 1}, - {"gpu_count": -1}, - {"gpu_count": True}, - {"gpu_count": 2**32}, + {"total_cpu_millis": 0}, + {"total_gpu_count": -1}, + {"total_gpu_count": True}, + {"total_gpu_count": 2**32}, {"gpu_class": "H200:8"}, - {"gpu_count": 0, "gpu_class": "h100"}, + {"total_gpu_count": 0, "gpu_class": "h100"}, ]: with pytest.raises(ValueError): if sync: @@ -200,6 +203,11 @@ def test_sync_remote_create_uses_public_async_connection(query): exist_ok=False, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, + total_cpu_millis=None, + total_memory_bytes=None, + total_gpu_count=None, + gpu_class=None, + gpu_count=None, ): calls.append( ( @@ -709,6 +717,11 @@ class CapturingCreateConnection: {}, {"auto_refresh_enabled": True}, {"auto_refresh_enabled": False, "auto_refresh_interval_seconds": 0.5}, + {"total_cpu_millis": 8000, "total_gpu_count": 0}, + {"total_memory_bytes": 16 * 1024**3}, + {"gpu_class": "any"}, + {"gpu_count": 2}, + {"gpu_class": "h100", "gpu_count": 2, "total_gpu_count": 4}, ], ) def test_remote_create_forwards_refresh_options_without_interval_default(options): @@ -731,6 +744,11 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options "limit": None, "with_no_data": False, "exist_ok": False, + "total_cpu_millis": options.get("total_cpu_millis"), + "total_memory_bytes": options.get("total_memory_bytes"), + "total_gpu_count": options.get("total_gpu_count"), + "gpu_class": options.get("gpu_class"), + "gpu_count": options.get("gpu_count"), "auto_refresh_enabled": options.get("auto_refresh_enabled"), "auto_refresh_interval_seconds": options.get( "auto_refresh_interval_seconds" @@ -783,18 +801,34 @@ def test_remote_create_rejects_invalid_interval_without_request(seconds): @pytest.mark.experimental_functions -def test_namespace_forwards_automatic_refresh_request(tmp_path): +@pytest.mark.parametrize( + "options", + [ + {"auto_refresh_enabled": True}, + {"total_cpu_millis": 8000, "total_gpu_count": 0}, + {"total_memory_bytes": 1024}, + ], +) +def test_namespace_forwards_automatic_refresh_request(tmp_path, options): db = lancedb.connect_namespace("dir", {"root": str(tmp_path)}) with pytest.raises(NotImplementedError, match="requires LanceDB Enterprise"): - db.create_materialized_view("mv", "source", auto_refresh_enabled=True) + db.create_materialized_view("mv", "source", **options) @pytest.mark.experimental_functions @pytest.mark.asyncio -async def test_async_namespace_forwards_automatic_refresh_request(tmp_path): +@pytest.mark.parametrize( + "options", + [ + {"auto_refresh_enabled": True}, + {"total_cpu_millis": 8000, "total_gpu_count": 0}, + {"total_memory_bytes": 1024}, + ], +) +async def test_async_namespace_forwards_automatic_refresh_request(tmp_path, options): db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}) with pytest.raises(NotImplementedError, match="requires LanceDB Enterprise"): - await db.create_materialized_view("mv", "source", auto_refresh_enabled=True) + await db.create_materialized_view("mv", "source", **options) @pytest.mark.experimental_functions diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index a1d811ec9..e72487a41 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2354,13 +2354,11 @@ def test_remote_create_index_async_returns_job(): {"batch_size": 8}, {"max_concurrency": 3}, {"publication_interval_rows": 60}, - {"resource_budget": {"cpu_millis": 2000, "memory_bytes": 4 * 1024**3}}, + {"total_cpu_millis": 2000, "total_memory_bytes": 4 * 1024**3}, { - "resource_budget": { - "cpu_millis": 8000, - "memory_bytes": 16 * 1024**3, - "gpu_count": 2, - } + "total_cpu_millis": 8000, + "total_memory_bytes": 16 * 1024**3, + "total_gpu_count": 2, }, { "supervisor_resources": { @@ -2379,7 +2377,7 @@ def test_remote_create_index_async_returns_job(): "fragments_per_worker": 8, }, }, - {"gpu_class": "a10g", "gpu_count": 2}, + {"gpu_class": "a10g", "total_gpu_count": 2}, { "retry_policy": {"transient": True, "max_attempts": 3}, "error_policy": "skip", @@ -2417,14 +2415,11 @@ async def test_remote_refresh_async_returns_typed_terminal_result( expected["batch_size"] = refresh_kwargs["batch_size"] if refresh_kwargs.get("gpu_class") is not None: expected["gpu_class"] = refresh_kwargs["gpu_class"] - if refresh_kwargs.get("gpu_count") is not None: - expected["gpu_count"] = refresh_kwargs["gpu_count"] - if refresh_kwargs.get("resource_budget") is not None: - budget = refresh_kwargs["resource_budget"] - expected["resource_budget"] = { - **budget, - "gpu_count": budget.get("gpu_count", 0), - } + if refresh_kwargs.get("total_gpu_count") is not None: + expected["total_gpu_count"] = refresh_kwargs["total_gpu_count"] + for key in ("total_cpu_millis", "total_memory_bytes"): + if refresh_kwargs.get(key) is not None: + expected[key] = refresh_kwargs[key] for key in ("supervisor_resources", "planning_workers"): if refresh_kwargs.get(key) is not None: expected[key] = refresh_kwargs[key] @@ -2606,8 +2601,7 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle(): ({"gpu_class": "H100"}, "gpu_class"), ({"gpu_class": "-a10g"}, "gpu_class"), ({"gpu_class": "a_b"}, "gpu_class"), - ({"gpu_count": 0}, "gpu_count"), - ({"gpu_count": -1}, "gpu_count"), + ({"total_gpu_count": -1}, "total_gpu_count"), ({"retry_policy": {"transient": True, "max_attempts": 0}}, "retry_policy"), ({"error_policy": "retry"}, "error_policy"), ({"where": " "}, "where"), @@ -2624,37 +2618,8 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle(): ({"max_concurrency": 2**32}, "max_concurrency"), ({"num_workers": 0}, "num_workers"), ( - {"resource_budget": {"cpu_millis": 1000}}, - "resource_budget.memory_bytes", - ), - ( - { - "resource_budget": { - "cpu_millis": 0, - "memory_bytes": 1, - } - }, - "resource_budget.cpu_millis", - ), - ( - { - "resource_budget": { - "cpu_millis": 1000, - "memory_bytes": 1, - }, - "gpu_count": 1, - }, - "gpu_count cannot be combined with resource_budget", - ), - ( - { - "resource_budget": { - "cpu_millis": 1000, - "memory_bytes": 1, - "unknown": 1, - } - }, - "unsupported key 'unknown'", + {"total_cpu_millis": 0, "total_memory_bytes": 1}, + "total_cpu_millis", ), ( { @@ -2675,17 +2640,6 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle(): }, "supervisor_resources.ephemeral_storage_bytes", ), - ( - { - "supervisor_resources": { - "cpu_millis": 1, - "memory_bytes": 1, - "ephemeral_storage_bytes": 1, - "unknown": 1, - } - }, - "unsupported key 'unknown'", - ), ( { "planning_workers": { @@ -7673,28 +7627,31 @@ async def test_remote_add_function_columns_forwards_auto_refresh_resource_budget request.send_response(404) request.end_headers() - budget = {"cpu_millis": 2_000, "memory_bytes": 4 * 1024**3} + budget = {"total_cpu_millis": 2_000, "total_memory_bytes": 4 * 1024**3} with mock_lancedb_connection(handler) as db: table = db.open_table("test") table.add_columns( {"embedding": application}, - auto_refresh_resource_budget=budget, + total_cpu_millis=(budget).get("total_cpu_millis"), + total_memory_bytes=(budget).get("total_memory_bytes"), + total_gpu_count=(budget).get("total_gpu_count"), ) async with mock_lancedb_connection_async(handler) as db: table = await db.open_table("test") await table.add_columns( {"embedding": application}, - auto_refresh_resource_budget=budget, + total_cpu_millis=(budget).get("total_cpu_millis"), + total_memory_bytes=(budget).get("total_memory_bytes"), + total_gpu_count=(budget).get("total_gpu_count"), ) assert len(bodies) == 2 for body in bodies: assert body["auto_refresh_enabled"] is True - assert body["auto_refresh_resource_budget"] == { - **budget, - "gpu_count": 0, - } + for key, value in budget.items(): + assert body[key] == value + assert "total_gpu_count" not in body assert body["new_columns"] == [{"name": "embedding", "all_null": True}] diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 2c3ce4a52..7ec1e8dd6 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -6565,8 +6565,8 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size) ({"max_concurrency": 4}, "max_concurrency"), ({"publication_interval_rows": 60}, "publication_interval_rows"), ( - {"resource_budget": {"cpu_millis": 1000, "memory_bytes": 1024}}, - "resource_budget", + {"total_cpu_millis": 1000, "total_memory_bytes": 1024}, + "total_cpu_millis", ), ( { @@ -6864,10 +6864,8 @@ def test_auto_refresh_resource_budget_requires_a_function(tmp_path): with pytest.raises(ValueError, match="registered Function"): table.add_columns( computed={"doubled": "x * 2"}, - auto_refresh_resource_budget={ - "cpu_millis": 1_000, - "memory_bytes": 1_024, - }, + total_cpu_millis=1_000, + total_memory_bytes=1_024, ) assert table.version == before assert table.schema.names == ["x"] diff --git a/python/src/connection.rs b/python/src/connection.rs index 3d1ad6d30..75878cf0e 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -665,7 +665,7 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None, *, query=None, exist_ok=false))] pub fn create_materialized_view( self_: PyRef<'_, Self>, name: String, @@ -676,6 +676,12 @@ impl Connection { with_no_data: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, + query: Option, exist_ok: bool, ) -> PyResult> { @@ -695,6 +701,22 @@ impl Connection { if let Some(seconds) = auto_refresh_interval_seconds { builder = builder.auto_refresh_interval_seconds(seconds); } + if let Some(value) = total_cpu_millis { + builder = builder.total_cpu_millis(value); + } + if let Some(value) = total_memory_bytes { + builder = builder.total_memory_bytes(value); + } + if let Some(value) = total_gpu_count { + builder = builder.total_gpu_count(value); + } + if let Some(value) = gpu_class { + builder = builder.gpu_class(value); + } + if let Some(value) = gpu_count { + builder = builder.gpu_count(value); + } + if let Some(projections) = projections { builder = builder.select(projections); } @@ -711,7 +733,7 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None, *, query=None, exist_ok=false))] pub fn create_materialized_view_async( self_: PyRef<'_, Self>, name: String, @@ -722,6 +744,12 @@ impl Connection { with_no_data: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, + query: Option, exist_ok: bool, ) -> PyResult> { @@ -741,6 +769,22 @@ impl Connection { if let Some(seconds) = auto_refresh_interval_seconds { builder = builder.auto_refresh_interval_seconds(seconds); } + if let Some(value) = total_cpu_millis { + builder = builder.total_cpu_millis(value); + } + if let Some(value) = total_memory_bytes { + builder = builder.total_memory_bytes(value); + } + if let Some(value) = total_gpu_count { + builder = builder.total_gpu_count(value); + } + if let Some(value) = gpu_class { + builder = builder.gpu_class(value); + } + if let Some(value) = gpu_count { + builder = builder.gpu_count(value); + } + if let Some(projections) = projections { builder = builder.select(projections); } diff --git a/python/src/table.rs b/python/src/table.rs index 74f17f724..a0ca2d73e 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -31,8 +31,8 @@ use lancedb::index::scalar::FtsIndexBuilder; use lancedb::table::{ AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, DeltaRef, Duration, FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig, - FunctionRefreshPodResources, FunctionWorkerResourceBudget, IndexRemapMode, NewColumnTransform, - Ref, RefreshColumnOptions, Table as LanceDbTable, TableDelta as LanceDbTableDelta, + FunctionRefreshPodResources, IndexRemapMode, NewColumnTransform, Ref, RefreshColumnOptions, + Table as LanceDbTable, TableDelta as LanceDbTableDelta, }; use lancedb::tokenize as lancedb_tokenize; use pyo3::{ @@ -58,11 +58,13 @@ struct RefreshColumnArgs { batch_size: Option, max_concurrency: Option, publication_interval_rows: Option, - resource_budget: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, supervisor_resources: Option, planning_workers: Option, gpu_class: Option, - gpu_count: Option, + gpu_count: Option, + total_gpu_count: Option, retry_policy: Option, error_policy: Option, max_failed_fraction: Option, @@ -109,65 +111,6 @@ fn positive_u32_integer(value: Option<&Bound<'_, PyAny>>, name: &str) -> PyResul }) } -fn resource_budget_integer( - value: &Bound<'_, PyAny>, - name: &str, - allow_zero: bool, -) -> PyResult { - if value.is_none() || value.is_instance_of::() { - return Err(PyValueError::new_err(format!( - "resource_budget.{name} must be an integer" - ))); - } - let parsed = value - .extract::() - .map_err(|_| PyValueError::new_err(format!("resource_budget.{name} must be an integer")))?; - if !allow_zero && parsed == 0 { - return Err(PyValueError::new_err(format!( - "resource_budget.{name} must be greater than zero" - ))); - } - Ok(parsed) -} - -fn parse_resource_budget( - budget: Option<&Bound<'_, PyDict>>, -) -> PyResult> { - let Some(budget) = budget else { - return Ok(None); - }; - for key in budget.keys() { - let key = key - .extract::() - .map_err(|_| PyValueError::new_err("resource_budget keys must be strings"))?; - if !matches!(key.as_str(), "cpu_millis" | "memory_bytes" | "gpu_count") { - return Err(PyValueError::new_err(format!( - "resource_budget contains unsupported key '{key}'" - ))); - } - } - let cpu_millis = budget - .get_item("cpu_millis")? - .ok_or_else(|| PyValueError::new_err("resource_budget.cpu_millis is required"))?; - let cpu_millis = resource_budget_integer(&cpu_millis, "cpu_millis", false)?; - let memory_bytes = budget - .get_item("memory_bytes")? - .ok_or_else(|| PyValueError::new_err("resource_budget.memory_bytes is required"))?; - let memory_bytes = resource_budget_integer(&memory_bytes, "memory_bytes", false)?; - let gpu_count = match budget.get_item("gpu_count")? { - None => 0, - Some(value) if value.is_none() => 0, - Some(value) => { - u32::try_from(resource_budget_integer(&value, "gpu_count", true)?).map_err(|_| { - PyValueError::new_err("resource_budget.gpu_count must be no greater than u32::MAX") - })? - } - }; - Ok(Some( - FunctionWorkerResourceBudget::new(cpu_millis, memory_bytes).with_gpu_count(gpu_count), - )) -} - fn structured_integer(value: &Bound<'_, PyAny>, name: &str) -> PyResult { if value.is_none() || value.is_instance_of::() { return Err(PyValueError::new_err(format!("{name} must be an integer"))); @@ -275,11 +218,13 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult PyResult 0) - .ok_or_else(|| { - PyValueError::new_err( - "gpu_count must be a positive integer no greater than u32::MAX", - ) - }) + u32::try_from(count).ok().ok_or_else(|| { + PyValueError::new_err( + "total_gpu_count must be a nonnegative integer no greater than u32::MAX", + ) + }) }) .transpose()?; options.validate().infer_error()?; @@ -2723,21 +2667,28 @@ impl Table { }) } - #[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, auto_refresh_resource_budget=None))] + #[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None))] + #[allow(clippy::too_many_arguments)] pub fn add_computed_columns<'py>( self_: PyRef<'py, Self>, columns: Vec<(String, String)>, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, - auto_refresh_resource_budget: Option>, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); let options = ComputedColumnOptions { auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true), auto_refresh_interval_seconds, - auto_refresh_resource_budget: parse_resource_budget( - auto_refresh_resource_budget.as_ref(), - )?, + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count, }; options.validate().infer_error()?; future_into_py(self_.py(), async move { @@ -2754,14 +2705,19 @@ impl Table { }) } - #[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, auto_refresh_resource_budget=None))] + #[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None))] + #[allow(clippy::too_many_arguments)] pub fn add_function_columns<'py>( self_: PyRef<'py, Self>, application_json: String, output_name: Option, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, - auto_refresh_resource_budget: Option>, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, ) -> PyResult> { let application = lancedb::function::FunctionApplication::from_json(&application_json).infer_error()?; @@ -2769,9 +2725,11 @@ impl Table { let options = ComputedColumnOptions { auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true), auto_refresh_interval_seconds, - auto_refresh_resource_budget: parse_resource_budget( - auto_refresh_resource_budget.as_ref(), - )?, + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count, }; options.validate().infer_error()?; future_into_py(self_.py(), async move { @@ -2788,7 +2746,7 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, total_cpu_millis=None, total_memory_bytes=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, total_gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column<'py>( self_: PyRef<'py, Self>, @@ -2797,11 +2755,13 @@ impl Table { batch_size: Option, max_concurrency: Option>, publication_interval_rows: Option, - resource_budget: Option>, + total_cpu_millis: Option, + total_memory_bytes: Option, supervisor_resources: Option>, planning_workers: Option>, gpu_class: Option, - gpu_count: Option, + gpu_count: Option, + total_gpu_count: Option, retry_policy: Option, error_policy: Option, max_failed_fraction: Option, @@ -2828,11 +2788,13 @@ impl Table { batch_size, max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, publication_interval_rows, - resource_budget: parse_resource_budget(resource_budget.as_ref())?, + total_cpu_millis, + total_memory_bytes, supervisor_resources: parse_supervisor_resources(supervisor_resources.as_ref())?, planning_workers: parse_planning_workers(planning_workers.as_ref())?, gpu_class, gpu_count, + total_gpu_count, retry_policy, error_policy, max_failed_fraction, @@ -2852,7 +2814,7 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, total_cpu_millis=None, total_memory_bytes=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, total_gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column_async<'py>( self_: PyRef<'py, Self>, @@ -2861,11 +2823,13 @@ impl Table { batch_size: Option, max_concurrency: Option>, publication_interval_rows: Option, - resource_budget: Option>, + total_cpu_millis: Option, + total_memory_bytes: Option, supervisor_resources: Option>, planning_workers: Option>, gpu_class: Option, - gpu_count: Option, + gpu_count: Option, + total_gpu_count: Option, retry_policy: Option, error_policy: Option, max_failed_fraction: Option, @@ -2892,11 +2856,13 @@ impl Table { batch_size, max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, publication_interval_rows, - resource_budget: parse_resource_budget(resource_budget.as_ref())?, + total_cpu_millis, + total_memory_bytes, supervisor_resources: parse_supervisor_resources(supervisor_resources.as_ref())?, planning_workers: parse_planning_workers(planning_workers.as_ref())?, gpu_class, gpu_count, + total_gpu_count, retry_policy, error_policy, max_failed_fraction, @@ -3031,16 +2997,17 @@ impl Table { }) } - #[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))] + #[pyo3(signature = (source_version=None, *, full=false, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_materialized_view( self_: PyRef<'_, Self>, source_version: Option, full: bool, - cpu_millis: Option, - memory_bytes: Option, - gpu_count: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, gpu_class: Option, + gpu_count: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -3048,18 +3015,21 @@ impl Table { .await .infer_error()?; let mut builder = view.refresh().full(full); - if let Some(value) = cpu_millis { - builder = builder.cpu_millis(value); + if let Some(value) = total_cpu_millis { + builder = builder.total_cpu_millis(value); } - if let Some(value) = memory_bytes { - builder = builder.memory_bytes(value); + if let Some(value) = total_memory_bytes { + builder = builder.total_memory_bytes(value); } - if let Some(value) = gpu_count { - builder = builder.gpu_count(value); + if let Some(value) = total_gpu_count { + builder = builder.total_gpu_count(value); } if let Some(value) = gpu_class { builder = builder.gpu_class(value); } + if let Some(value) = gpu_count { + builder = builder.gpu_count(value); + } if let Some(version) = source_version { builder = builder.source_version(version); } @@ -3068,16 +3038,17 @@ impl Table { }) } - #[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))] + #[pyo3(signature = (source_version=None, *, full=false, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_materialized_view_async( self_: PyRef<'_, Self>, source_version: Option, full: bool, - cpu_millis: Option, - memory_bytes: Option, - gpu_count: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, gpu_class: Option, + gpu_count: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -3085,18 +3056,21 @@ impl Table { .await .infer_error()?; let mut builder = view.refresh().full(full); - if let Some(value) = cpu_millis { - builder = builder.cpu_millis(value); + if let Some(value) = total_cpu_millis { + builder = builder.total_cpu_millis(value); } - if let Some(value) = memory_bytes { - builder = builder.memory_bytes(value); + if let Some(value) = total_memory_bytes { + builder = builder.total_memory_bytes(value); } - if let Some(value) = gpu_count { - builder = builder.gpu_count(value); + if let Some(value) = total_gpu_count { + builder = builder.total_gpu_count(value); } if let Some(value) = gpu_class { builder = builder.gpu_class(value); } + if let Some(value) = gpu_count { + builder = builder.gpu_count(value); + } if let Some(version) = source_version { builder = builder.source_version(version); } diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index db58afa99..270761d28 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -305,6 +305,7 @@ pub enum PythonRuntimeSpec { /// }, /// env: BTreeMap::new(), /// gpu_class: Some("a10g".to_string()), + /// gpus_per_worker: std::num::NonZeroU32::new(2), /// }; /// assert!(runtime.requires_gpu()); /// ``` @@ -312,8 +313,10 @@ pub enum PythonRuntimeSpec { python_version: String, environment: PythonEnvironmentSpec, env: BTreeMap, - /// Operator-defined GPU class; absent uses the deployment default. + /// Operator-defined GPU class; absent accepts any eligible configured class. gpu_class: Option, + /// GPUs allocated together to each worker. + gpus_per_worker: Option, }, /// A runtime kind introduced by a newer server. /// @@ -365,17 +368,30 @@ impl PythonRuntimeSpec { matches!(self, Self::PythonV2 { .. }) } - /// Operator-defined GPU class, or `None` to use the deployment default. + /// Requested GPU class; `None` and `"any"` both accept any eligible class. + /// This does not identify the hardware selected for execution. pub fn gpu_class(&self) -> Option<&str> { match self { Self::PythonV2 { gpu_class, .. } => gpu_class.as_deref(), _ => None, } } + + /// GPUs allocated to one worker; zero for CPU runtimes. + pub fn gpus_per_worker(&self) -> u32 { + match self { + Self::PythonV2 { + gpus_per_worker, .. + } => gpus_per_worker.map_or(1, std::num::NonZeroU32::get), + _ => 0, + } + } } #[derive(Deserialize)] struct PythonRuntimeV1Wire { + #[serde(default)] + gpus_per_worker: Option, python_version: String, environment: PythonEnvironmentSpec, #[serde(default)] @@ -388,6 +404,8 @@ struct PythonRuntimeV1Wire { #[derive(Deserialize)] struct PythonRuntimeV2Wire { + #[serde(default)] + gpus_per_worker: Option, python_version: String, environment: PythonEnvironmentSpec, #[serde(default)] @@ -420,6 +438,11 @@ impl<'de> Deserialize<'de> for PythonRuntimeSpec { "python runtime with gpu_class requires kind='python_v2'", )); } + if wire.gpus_per_worker.is_some() { + return Err(de::Error::custom( + "gpus_per_worker requires kind='python_v2'", + )); + } Ok(Self::Python { python_version: wire.python_version, environment: wire.environment, @@ -440,6 +463,7 @@ impl<'de> Deserialize<'de> for PythonRuntimeSpec { environment: wire.environment, env: wire.env, gpu_class: wire.gpu_class, + gpus_per_worker: wire.gpus_per_worker, }) } _ => Ok(Self::Unrecognized { kind }), @@ -460,6 +484,8 @@ impl Serialize for PythonRuntimeSpec { gpu: Option, #[serde(skip_serializing_if = "Option::is_none")] gpu_class: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + gpus_per_worker: Option, } #[derive(Serialize)] @@ -479,6 +505,7 @@ impl Serialize for PythonRuntimeSpec { env, gpu: None, gpu_class: None, + gpus_per_worker: None, } .serialize(serializer), Self::PythonV2 { @@ -486,6 +513,7 @@ impl Serialize for PythonRuntimeSpec { environment, env, gpu_class, + gpus_per_worker, } => PythonRuntimeRef { kind: "python_v2", python_version, @@ -493,6 +521,7 @@ impl Serialize for PythonRuntimeSpec { env, gpu: Some(true), gpu_class: gpu_class.as_deref(), + gpus_per_worker: *gpus_per_worker, } .serialize(serializer), Self::Unrecognized { kind } => UnrecognizedRuntimeRef { kind }.serialize(serializer), @@ -675,6 +704,24 @@ pub struct FunctionVersion { deserialize_with = "deserialize_max_concurrency" )] max_concurrency: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_total_cpu_millis" + )] + total_cpu_millis: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_total_memory_bytes" + )] + total_memory_bytes: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_total_gpu_count" + )] + total_gpu_count: Option, /// Per-call deadline in seconds. #[serde(default, skip_serializing_if = "Option::is_none")] row_timeout_seconds: Option, @@ -773,6 +820,21 @@ impl FunctionVersion { self.gpu_class.as_deref() } + /// Default total CPU budget for executions of this pinned Function. + pub fn total_cpu_millis(&self) -> Option { + self.total_cpu_millis + } + + /// Default total memory budget for executions of this pinned Function. + pub fn total_memory_bytes(&self) -> Option { + self.total_memory_bytes + } + + /// Default aggregate GPU budget, independent of the per-worker device count. + pub fn total_gpu_count(&self) -> Option { + self.total_gpu_count + } + /// Default maximum rows in one callable batch, when declared. pub fn batch_size(&self) -> Option { self.batch_size @@ -900,6 +962,44 @@ where Ok(value) } +fn deserialize_total_cpu_millis<'de, D>( + deserializer: D, +) -> std::result::Result, D::Error> +where + D: Deserializer<'de>, +{ + let value = Option::::deserialize(deserializer) + .map_err(|error| de::Error::custom(format!("total_cpu_millis: {error}")))?; + if value == Some(0) { + return Err(de::Error::custom("total_cpu_millis must be positive")); + } + Ok(value) +} + +fn deserialize_total_memory_bytes<'de, D>( + deserializer: D, +) -> std::result::Result, D::Error> +where + D: Deserializer<'de>, +{ + let value = Option::::deserialize(deserializer) + .map_err(|error| de::Error::custom(format!("total_memory_bytes: {error}")))?; + if value == Some(0) { + return Err(de::Error::custom("total_memory_bytes must be positive")); + } + Ok(value) +} + +fn deserialize_total_gpu_count<'de, D>( + deserializer: D, +) -> std::result::Result, D::Error> +where + D: Deserializer<'de>, +{ + Option::::deserialize(deserializer) + .map_err(|error| de::Error::custom(format!("total_gpu_count: {error}"))) +} + fn deserialize_max_concurrency<'de, D>( deserializer: D, ) -> std::result::Result, D::Error> @@ -970,6 +1070,27 @@ pub struct FunctionRegistrationRequest { deserialize_with = "deserialize_max_concurrency" )] pub max_concurrency: Option, + /// Default total CPU capacity for one execution, in millicores. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_total_cpu_millis" + )] + pub total_cpu_millis: Option, + /// Default total memory for one execution, in bytes. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_total_memory_bytes" + )] + pub total_memory_bytes: Option, + /// Default total GPUs across one execution's workers. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_total_gpu_count" + )] + pub total_gpu_count: Option, /// Deadline for each Python call, in seconds: one row for scalar Functions /// and one batch for vectorized Functions. It does not govern Function /// initialization. @@ -1010,6 +1131,11 @@ impl FunctionRegistrationRequest { let invalid_input = |message: &'static str| Error::InvalidInput { message: message.to_string(), }; + if self.total_cpu_millis == Some(0) || self.total_memory_bytes == Some(0) { + return Err(invalid_input( + "total_cpu_millis and total_memory_bytes must be positive integers", + )); + } validate_batch_size_value(self.batch_size).map_err(invalid_input)?; validate_max_concurrency_value(self.max_concurrency).map_err(invalid_input)?; validate_row_timeout_value(self.row_timeout_seconds).map_err(invalid_input)?; @@ -1618,6 +1744,7 @@ mod refresh_result_tests { #[cfg(test)] mod conda_environment_tests { use super::{PythonEnvironmentSpec, PythonRuntimeSpec}; + use serde_json::Value; #[test] fn conda_channels_round_trip_and_pip_stays_bare() { @@ -1679,6 +1806,28 @@ mod conda_environment_tests { super::canonical_json(&runtime).unwrap(), r#"{"environment":{"kind":"pip"},"gpu":true,"gpu_class":"a10g","kind":"python_v2","python_version":"3.12"}"# ); + let runtime: PythonRuntimeSpec = serde_json::from_str( + r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"},"gpu":true,"gpu_class":"any","gpus_per_worker":2}"#, + ).unwrap(); + assert_eq!(runtime.gpus_per_worker(), 2); + assert_eq!(runtime.gpu_class(), Some("any")); + let encoded = super::canonical_json(&runtime).unwrap(); + assert_eq!( + serde_json::from_str::(&encoded).unwrap()["gpus_per_worker"], + 2 + ); + for count in [ + serde_json::json!(0), + serde_json::json!(-1), + serde_json::json!(true), + serde_json::json!("2"), + serde_json::json!(1.5), + serde_json::json!(4294967296_u64), + ] { + let mut value: Value = serde_json::from_str(&encoded).unwrap(); + value["gpus_per_worker"] = count; + assert!(serde_json::from_value::(value).is_err()); + } for invalid in [ r#"{"kind":"python","python_version":"3.12","environment":{"kind":"pip"},"gpu":true}"#, diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 4b2a61f2c..0591be948 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -301,6 +301,11 @@ pub struct CreateMaterializedViewRequest { pub auto_refresh_enabled: Option, /// Refresh interval in seconds. When absent, the server determines when to refresh. pub auto_refresh_interval_seconds: Option, + pub total_cpu_millis: Option, + pub total_memory_bytes: Option, + pub total_gpu_count: Option, + pub gpu_class: Option, + pub gpu_count: Option, } /// Prefix of the internal columns holding source columns a computed column @@ -1591,6 +1596,11 @@ pub struct CreateMaterializedViewBuilder { exist_ok: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, } enum MaterializedViewInput { @@ -1632,6 +1642,11 @@ impl CreateMaterializedViewBuilder { exist_ok: false, auto_refresh_enabled: None, auto_refresh_interval_seconds: None, + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + gpu_class: None, + gpu_count: None, } } @@ -1783,6 +1798,36 @@ impl CreateMaterializedViewBuilder { Ok(query) } + /// Set the default total cpu millis budget for this materialized view. + pub fn total_cpu_millis(mut self, value: u64) -> Self { + self.total_cpu_millis = Some(value); + self + } + + /// Set the default total memory bytes budget for this materialized view. + pub fn total_memory_bytes(mut self, value: u64) -> Self { + self.total_memory_bytes = Some(value); + self + } + + /// Set the default total gpu count budget for this materialized view. + pub fn total_gpu_count(mut self, value: u32) -> Self { + self.total_gpu_count = Some(value); + self + } + + /// Set the default GPU pool for initial population and later refreshes. + pub fn gpu_class(mut self, class: impl Into) -> Self { + self.gpu_class = Some(class.into()); + self + } + + /// Set the default positive GPU count for each worker. + pub fn gpu_count(mut self, count: u32) -> Self { + self.gpu_count = Some(count); + self + } + /// Submit creation and initial population, returning a [`Job`] that /// settles when the view is ready. Remote creation submits SQL; the handle's /// [`Job::job_type`] is `"query"` and its ID identifies that query. @@ -1799,6 +1844,11 @@ impl CreateMaterializedViewBuilder { with_no_data: self.with_no_data, auto_refresh_enabled: self.auto_refresh_enabled, auto_refresh_interval_seconds: self.auto_refresh_interval_seconds, + total_cpu_millis: self.total_cpu_millis, + total_memory_bytes: self.total_memory_bytes, + total_gpu_count: self.total_gpu_count, + gpu_class: self.gpu_class.clone(), + gpu_count: self.gpu_count, }) .await; } @@ -1832,7 +1882,14 @@ impl CreateMaterializedViewBuilder { { return Ok(view); } - if self.auto_refresh_enabled == Some(true) || self.auto_refresh_interval_seconds.is_some() { + if self.auto_refresh_enabled == Some(true) + || self.auto_refresh_interval_seconds.is_some() + || self.total_cpu_millis.is_some() + || self.total_memory_bytes.is_some() + || self.total_gpu_count.is_some() + || self.gpu_class.is_some() + || self.gpu_count.is_some() + { return Err(Error::NotSupported { message: "automatic materialized-view refresh requires LanceDB Enterprise" .to_string(), @@ -1961,49 +2018,53 @@ impl MaterializedView { /// Per-execution resource caps and GPU placement for Enterprise MV refreshes. /// /// CPU is in millicores (1000 = one core), memory is bytes, and GPUs are a -/// simultaneous cap across the refresh, not a per-Function allocation. CPU or -/// memory requires all three budget fields. Embedded refreshes reject options. +/// simultaneous cap across the refresh. Each omitted resource inherits the +/// view defaults, then Function defaults, then deployment defaults. +/// Embedded refreshes reject these options. #[derive(Debug, Clone, Default, PartialEq, Eq)] #[non_exhaustive] pub struct RefreshMaterializedViewOptions { - pub cpu_millis: Option, - pub memory_bytes: Option, - pub gpu_count: Option, + pub total_cpu_millis: Option, + pub total_memory_bytes: Option, + pub total_gpu_count: Option, pub gpu_class: Option, + pub gpu_count: Option, } impl RefreshMaterializedViewOptions { pub(crate) fn is_empty(&self) -> bool { - self.cpu_millis.is_none() - && self.memory_bytes.is_none() - && self.gpu_count.is_none() + self.total_cpu_millis.is_none() + && self.total_memory_bytes.is_none() + && self.total_gpu_count.is_none() && self.gpu_class.is_none() + && self.gpu_count.is_none() } pub(crate) fn validate(&self) -> Result<()> { let invalid = |message: &str| Error::InvalidInput { message: message.into(), }; - if self.cpu_millis == Some(0) || self.memory_bytes == Some(0) { + if self.total_cpu_millis == Some(0) || self.total_memory_bytes == Some(0) { return Err(invalid( - "cpu_millis and memory_bytes must be positive integers", - )); - } - if (self.cpu_millis.is_some() || self.memory_bytes.is_some()) - && !(self.cpu_millis.is_some() - && self.memory_bytes.is_some() - && self.gpu_count.is_some()) - { - return Err(invalid( - "cpu_millis, memory_bytes, and gpu_count must be specified together", + "total_cpu_millis and total_memory_bytes must be positive integers", )); } if let Some(class) = &self.gpu_class { crate::function::validate_gpu_class_name(class)?; - if self.gpu_count == Some(0) { + if self.total_gpu_count == Some(0) { return Err(invalid("gpu_class requires a positive GPU budget")); } } + if self.gpu_count == Some(0) { + return Err(invalid("gpu_count must be positive")); + } + if self + .gpu_count + .zip(self.total_gpu_count) + .is_some_and(|(per_worker, total)| per_worker > total) + { + return Err(invalid("total_gpu_count cannot fit one Function worker")); + } Ok(()) } @@ -2013,18 +2074,21 @@ impl RefreshMaterializedViewOptions { if full { values.push("full = true".to_string()); } - if let Some(cpu) = self.cpu_millis { - values.push(format!("cpu_millis = {cpu}")); + if let Some(cpu) = self.total_cpu_millis { + values.push(format!("total_cpu_millis = {cpu}")); } - if let Some(memory) = self.memory_bytes { - values.push(format!("memory_bytes = {memory}")); + if let Some(memory) = self.total_memory_bytes { + values.push(format!("total_memory_bytes = {memory}")); } - if let Some(gpu) = self.gpu_count { - values.push(format!("gpu_count = {gpu}")); + if let Some(gpu) = self.total_gpu_count { + values.push(format!("total_gpu_count = {gpu}")); } if let Some(class) = &self.gpu_class { values.push(format!("gpu_class = '{class}'")); } + if let Some(count) = self.gpu_count { + values.push(format!("gpu_count = {count}")); + } Ok(if values.is_empty() { String::new() } else { @@ -2042,25 +2106,31 @@ pub struct RefreshMaterializedViewBuilder { } impl RefreshMaterializedViewBuilder { - /// Cap total CPU capacity in millicores; requires memory and GPU budgets. - pub fn cpu_millis(mut self, cpu_millis: u64) -> Self { - self.options.cpu_millis = Some(cpu_millis); + /// Override total CPU capacity in millicores for this refresh. + pub fn total_cpu_millis(mut self, total_cpu_millis: u64) -> Self { + self.options.total_cpu_millis = Some(total_cpu_millis); self } - /// Cap total memory in bytes; requires CPU and GPU budgets. - pub fn memory_bytes(mut self, memory_bytes: u64) -> Self { - self.options.memory_bytes = Some(memory_bytes); + /// Override total memory in bytes for this refresh. + pub fn total_memory_bytes(mut self, total_memory_bytes: u64) -> Self { + self.options.total_memory_bytes = Some(total_memory_bytes); self } /// Cap concurrent GPUs for this refresh. Zero is CPU-only. - pub fn gpu_count(mut self, gpu_count: u32) -> Self { - self.options.gpu_count = Some(gpu_count); + pub fn total_gpu_count(mut self, total_gpu_count: u32) -> Self { + self.options.total_gpu_count = Some(total_gpu_count); self } /// Select an operator-configured GPU class for this execution only. + /// Set the positive number of GPUs allocated to each worker. + pub fn gpu_count(mut self, count: u32) -> Self { + self.options.gpu_count = Some(count); + self + } + pub fn gpu_class(mut self, gpu_class: impl Into) -> Self { self.options.gpu_class = Some(gpu_class.into()); self @@ -2448,7 +2518,7 @@ mod tests { .unwrap(); assert!(matches!( - view.refresh().gpu_count(0).execute().await, + view.refresh().total_gpu_count(0).execute().await, Err(Error::NotSupported { .. }) )); assert!(matches!( diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index f17bcc2b0..b44d6e26f 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -823,6 +823,33 @@ impl Database for RemoteDatabase { if let Some(seconds) = request.auto_refresh_interval_seconds { options.push(format!("auto_refresh_interval_seconds = {seconds}")); } + if request.total_cpu_millis == Some(0) || request.total_memory_bytes == Some(0) { + return Err(Error::InvalidInput { + message: "total_cpu_millis and total_memory_bytes must be positive integers".into(), + }); + } + for (key, value) in [ + ("total_cpu_millis", request.total_cpu_millis), + ("total_memory_bytes", request.total_memory_bytes), + ("total_gpu_count", request.total_gpu_count.map(u64::from)), + ] { + if let Some(value) = value { + options.push(format!("{key} = {value}")); + } + } + + if let Some(class) = &request.gpu_class { + crate::function::validate_gpu_class_name(class)?; + options.push(format!("gpu_class = '{class}'")); + } + if let Some(count) = request.gpu_count { + if count == 0 { + return Err(Error::InvalidInput { + message: "gpu_count must be positive".into(), + }); + } + options.push(format!("gpu_count = {count}")); + } let name = request.name.replace('"', "\"\""); let options = if options.is_empty() { String::new() @@ -5137,6 +5164,12 @@ mod tests { for seconds in [0.0, -1.0, f64::NAN, f64::INFINITY] { let result = db .create_materialized_view_async(CreateMaterializedViewRequest { + gpu_class: Default::default(), + gpu_count: Default::default(), + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + exist_ok: false, name: "adults".into(), namespace_path: vec![], diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 7f1767ff1..7d7ac2d4a 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -1253,17 +1253,38 @@ async fn remote_create_uses_sql_and_preserves_options_and_namespace() { panic!("CREATE must use SQL, not REST: {}", request.url().path()); }) .with_sql_client(sql_client.clone()); - for (enabled, interval, expected) in [ - (None, None, ""), - (Some(true), None, " WITH (auto_refresh_enabled = true)"), + for (enabled, interval, cpu, gpu, expected) in [ + (None, None, None, None, ""), + ( + Some(true), + None, + None, + None, + " WITH (auto_refresh_enabled = true)", + ), ( Some(false), Some(0.5), + None, + None, " WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 0.5)", ), + ( + None, + None, + Some(8000), + Some(0), + " WITH (total_cpu_millis = 8000, total_gpu_count = 0)", + ), ] { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + gpu_class: Default::default(), + gpu_count: Default::default(), + total_cpu_millis: cpu, + total_memory_bytes: None, + total_gpu_count: gpu, + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], @@ -1292,7 +1313,7 @@ async fn remote_create_uses_sql_and_preserves_options_and_namespace() { ); } assert_eq!(count.load(Ordering::SeqCst), 0); - assert_eq!(statements.lock().unwrap().len(), 3); + assert_eq!(statements.lock().unwrap().len(), 4); assert!( headers .lock() @@ -1347,6 +1368,12 @@ async fn remote_create_returns_the_registry_job_from_the_early_status_row() { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + gpu_class: Default::default(), + gpu_count: Default::default(), + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], @@ -1410,6 +1437,12 @@ async fn remote_create_if_not_exists_accepts_a_completed_noop_without_a_registry .with_sql_client(client); let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + gpu_class: Default::default(), + gpu_count: Default::default(), + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + exist_ok: true, name: "adults".into(), namespace_path: vec!["team".into()], @@ -1497,6 +1530,12 @@ async fn remote_create_registry_handle_reopens_describes_and_cancels() { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + gpu_class: Default::default(), + gpu_count: Default::default(), + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], @@ -1731,10 +1770,11 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { let third = view .refresh() .full(true) - .cpu_millis(8000) - .memory_bytes(16 << 30) - .gpu_count(2) + .total_cpu_millis(8000) + .total_memory_bytes(16 << 30) + .total_gpu_count(2) .gpu_class("h100") + .gpu_count(2) .execute_async() .await .unwrap() @@ -1742,9 +1782,8 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { .await .unwrap(); for invalid in [ - view.refresh().cpu_millis(1), view.refresh().gpu_class("H200:8"), - view.refresh().gpu_count(0).gpu_class("h100"), + view.refresh().total_gpu_count(0).gpu_class("h100"), ] { assert!(matches!( invalid.execute_async().await, @@ -1772,7 +1811,7 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { "DESCRIBE MATERIALIZED VIEW \"view\"", "REFRESH MATERIALIZED VIEW \"view\"", "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true)", - "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true, cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2, gpu_class = 'h100')", + "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true, total_cpu_millis = 8000, total_memory_bytes = 17179869184, total_gpu_count = 2, gpu_class = 'h100', gpu_count = 2)", ] ); assert!( @@ -3236,6 +3275,9 @@ async fn function_creation_and_description_use_sql_query_handles() { let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); request_json["batch_size"] = serde_json::json!(2); request_json["max_concurrency"] = serde_json::json!(4); + request_json["total_cpu_millis"] = serde_json::json!(8000); + request_json["total_memory_bytes"] = serde_json::json!(17179869184_u64); + request_json["total_gpu_count"] = serde_json::json!(0); request_json["row_timeout_seconds"] = serde_json::json!(0.75); request_json["secret_bindings"] = serde_json::json!([{ "kind": "env", @@ -3244,6 +3286,9 @@ async fn function_creation_and_description_use_sql_query_handles() { }]); let mut version_json: serde_json::Value = serde_json::from_str(VERSION).unwrap(); version_json["batch_size"] = serde_json::json!(12); + for field in ["total_cpu_millis", "total_memory_bytes", "total_gpu_count"] { + version_json[field] = request_json[field].clone(); + } version_json["max_concurrency"] = serde_json::json!(4); version_json["row_timeout_seconds"] = serde_json::json!(8.0); version_json["result_stability"] = serde_json::json!("input_and_context"); @@ -3322,6 +3367,9 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(created.name(), "embed"); assert_eq!(created.version(), "1"); assert_eq!(created.batch_size(), Some(12)); + assert_eq!(created.total_cpu_millis(), Some(8000)); + assert_eq!(created.total_memory_bytes(), Some(17179869184)); + assert_eq!(created.total_gpu_count(), Some(0)); assert_eq!(created.max_concurrency(), Some(4)); assert_eq!(created.row_timeout_seconds(), Some(8.0)); assert_eq!(created.result_stability(), Some("input_and_context")); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 6b46c45fc..3793612c6 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4490,8 +4490,20 @@ impl BaseTable for RemoteTable { if let Some(interval) = options.auto_refresh_interval_seconds { body["auto_refresh_interval_seconds"] = serde_json::json!(interval); } - if let Some(budget) = options.auto_refresh_resource_budget { - body["auto_refresh_resource_budget"] = serde_json::json!(budget); + for (key, value) in [ + ("total_cpu_millis", options.total_cpu_millis), + ("total_memory_bytes", options.total_memory_bytes), + ("total_gpu_count", options.total_gpu_count.map(u64::from)), + ] { + if let Some(value) = value { + body[key] = serde_json::json!(value); + } + } + if let Some(class) = &options.gpu_class { + body["gpu_class"] = serde_json::json!(class); + } + if let Some(count) = options.gpu_count { + body["gpu_count"] = serde_json::json!(count); } self.apply_branch_body(&mut body); let request = self @@ -11310,9 +11322,13 @@ mod tests { .add_columns() .computed("doubled", "x * 2") .computed_options(crate::table::computed_columns::ComputedColumnOptions { + gpu_class: Default::default(), + gpu_count: Default::default(), auto_refresh_enabled: false, auto_refresh_interval_seconds: interval, - auto_refresh_resource_budget: None, + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, }) .execute() .await @@ -11899,11 +11915,11 @@ mod tests { )) .unwrap(); expected["auto_refresh_enabled"] = serde_json::json!(true); - expected["auto_refresh_resource_budget"] = serde_json::json!({ - "cpu_millis": 8_000, - "memory_bytes": 17_179_869_184_u64, - "gpu_count": 2, - }); + expected["total_cpu_millis"] = serde_json::json!(8000); + expected["total_memory_bytes"] = serde_json::json!(17179869184_u64); + expected["total_gpu_count"] = serde_json::json!(2); + expected["gpu_class"] = serde_json::json!("any"); + expected["gpu_count"] = serde_json::json!(2); assert_eq!(actual, expected); http::Response::builder() .status(200) @@ -11932,12 +11948,13 @@ mod tests { .add_columns() .function(application) .computed_options(crate::table::computed_columns::ComputedColumnOptions { + gpu_class: Some("any".into()), + gpu_count: Some(2), auto_refresh_enabled: true, auto_refresh_interval_seconds: None, - auto_refresh_resource_budget: Some( - crate::table::FunctionWorkerResourceBudget::new(8_000, 17_179_869_184) - .with_gpu_count(2), - ), + total_cpu_millis: Some(8000), + total_memory_bytes: Some(17179869184), + total_gpu_count: Some(2), }) .execute() .await @@ -12142,7 +12159,7 @@ mod tests { serde_json::json!({ "column": "quality", "gpu_class": "a10g", - "gpu_count": 2, + "total_gpu_count": 2, }) ); http::Response::builder() @@ -12152,7 +12169,7 @@ mod tests { }); let options = RefreshColumnOptions::default() .gpu_class("a10g") - .gpu_count(2); + .total_gpu_count(2); let job = table .refresh_column_async_with_options("quality", options) .await @@ -12165,7 +12182,7 @@ mod tests { #[case(Some(2), 2)] #[tokio::test] async fn test_refresh_column_async_resource_budget( - #[case] gpu_count: Option, + #[case] total_gpu_count: Option, #[case] expected_gpu_count: u32, ) { use crate::table::{FunctionWorkerResourceBudget, RefreshColumnOptions}; @@ -12176,11 +12193,9 @@ mod tests { request_body_json(&request), serde_json::json!({ "column": "quality", - "resource_budget": { - "cpu_millis": 8_000, - "memory_bytes": 17_179_869_184_u64, - "gpu_count": expected_gpu_count, - }, + "total_cpu_millis": 8_000, + "total_memory_bytes": 17_179_869_184_u64, + "total_gpu_count": expected_gpu_count, }) ); http::Response::builder() @@ -12189,13 +12204,16 @@ mod tests { .unwrap() }); let mut budget = FunctionWorkerResourceBudget::new(8_000, 17_179_869_184); - if let Some(gpu_count) = gpu_count { - budget = budget.with_gpu_count(gpu_count); + if let Some(total_gpu_count) = total_gpu_count { + budget = budget.with_total_gpu_count(total_gpu_count); } let job = table .refresh_column_async_with_options( "quality", - RefreshColumnOptions::default().resource_budget(budget), + RefreshColumnOptions::default() + .total_cpu_millis((budget).total_cpu_millis) + .total_memory_bytes((budget).total_memory_bytes) + .total_gpu_count((budget).total_gpu_count), ) .await .unwrap(); @@ -12453,22 +12471,23 @@ mod tests { RefreshColumnOptions::default().gpu_class("-a10g"), "gpu_class", ), - (RefreshColumnOptions::default().gpu_count(0), "gpu_count"), ( RefreshColumnOptions::default() - .resource_budget(FunctionWorkerResourceBudget::new(0, 1)), - "resource_budget.cpu_millis", + .total_cpu_millis((FunctionWorkerResourceBudget::new(0, 1)).total_cpu_millis) + .total_memory_bytes( + (FunctionWorkerResourceBudget::new(0, 1)).total_memory_bytes, + ) + .total_gpu_count((FunctionWorkerResourceBudget::new(0, 1)).total_gpu_count), + "total_cpu_millis", ), ( RefreshColumnOptions::default() - .resource_budget(FunctionWorkerResourceBudget::new(1, 0)), - "resource_budget.memory_bytes", - ), - ( - RefreshColumnOptions::default() - .resource_budget(FunctionWorkerResourceBudget::new(1, 1)) - .gpu_count(1), - "gpu_count cannot be combined with resource_budget", + .total_cpu_millis((FunctionWorkerResourceBudget::new(1, 0)).total_cpu_millis) + .total_memory_bytes( + (FunctionWorkerResourceBudget::new(1, 0)).total_memory_bytes, + ) + .total_gpu_count((FunctionWorkerResourceBudget::new(1, 0)).total_gpu_count), + "total_memory_bytes", ), ] { let error = table diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 3ad3d0c24..8ad9a0d65 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -2364,10 +2364,10 @@ impl Table { /// [`RefreshColumnOptions::publication_interval_rows()`] sets an opt-in /// row-count publication threshold for completed Function outputs; unset /// keeps whole-fragment publication. - /// [`RefreshColumnOptions::resource_budget()`] sets the aggregate CPU, + /// [`RefreshColumnOptions::total_memory_bytes()`] sets the aggregate CPU, /// memory, and GPU budget for a Function refresh. /// [`RefreshColumnOptions::gpu_class()`] selects a GPU pool and - /// [`RefreshColumnOptions::gpu_count()`] sets the aggregate GPU budget + /// [`RefreshColumnOptions::total_gpu_count()`] sets the aggregate GPU budget /// without changing the deployment's CPU and memory defaults. /// Batch-size and GPU options have no effect on expression-backed columns /// in LanceDB Embedded; a resource budget and publication threshold are @@ -2432,9 +2432,9 @@ impl Table { /// [`RefreshColumnOptions::publication_interval_rows()`] to publish /// completed Function outputs at a row-count threshold; unset keeps /// whole-fragment publication. Set - /// [`RefreshColumnOptions::resource_budget()`] to pass a complete aggregate + /// [`RefreshColumnOptions::total_memory_bytes()`] to pass a complete aggregate /// CPU, memory, and GPU budget for a Function refresh. The standalone - /// [`RefreshColumnOptions::gpu_count()`] shorthand and + /// [`RefreshColumnOptions::total_gpu_count()`] shorthand and /// [`RefreshColumnOptions::gpu_class()`] placement remain available; a /// resource budget cannot be combined with the gpu-count shorthand. Unset /// values use the Function and server defaults; invalid counts and malformed @@ -2474,7 +2474,7 @@ impl Table { /// RefreshColumnOptions::default() /// .batch_size(8) /// .gpu_class("a10g") - /// .gpu_count(2), + /// .total_gpu_count(2), /// ).await?; /// let result = job.wait().await?; /// # Ok(()) diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index a76c0d043..1e859ea90 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -180,9 +180,13 @@ impl AddColumnsBuilder { /// # async fn declare(table: &Table) -> lancedb::Result<()> { /// table.add_columns().computed("doubled", "x * 2") /// .computed_options(ComputedColumnOptions { + /// gpu_class: Default::default(), + /// gpu_count: Default::default(), /// auto_refresh_enabled: true, /// auto_refresh_interval_seconds: Some(300), - /// auto_refresh_resource_budget: None, + /// total_cpu_millis: None, + /// total_memory_bytes: None, + /// total_gpu_count: None, /// }).execute().await?; /// # Ok(()) /// # } @@ -202,7 +206,7 @@ impl AddColumnsBuilder { read_columns, options, } = self; - if let Some(options) = options { + if let Some(options) = &options { options.validate()?; if computed.is_empty() && function.is_none() { return Err(Error::InvalidInput { @@ -210,11 +214,9 @@ impl AddColumnsBuilder { .into(), }); } - if options.auto_refresh_resource_budget.is_some() && function.is_none() { + if options.has_resource_defaults() && function.is_none() { return Err(Error::InvalidInput { - message: - "auto_refresh_resource_budget requires a registered Function declaration" - .into(), + message: "total_* resources require a registered Function declaration".into(), }); } } @@ -297,14 +299,18 @@ mod tests { let table = table_with_two_columns("options").await; let version = table.version().await.unwrap(); let options = ComputedColumnOptions { + gpu_class: Default::default(), + gpu_count: Default::default(), auto_refresh_enabled: false, auto_refresh_interval_seconds: Some(300), - auto_refresh_resource_budget: None, + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, }; let result = table .add_columns() .computed("doubled", "x * 2") - .computed_options(options) + .computed_options(options.clone()) .execute() .await .unwrap(); @@ -320,7 +326,7 @@ mod tests { for interval in [0, u64::MAX] { let invalid = ComputedColumnOptions { auto_refresh_interval_seconds: Some(interval), - ..options + ..options.clone() }; assert!( table @@ -339,7 +345,7 @@ mod tests { "once".into(), "x".into() )])) - .computed_options(options) + .computed_options(options.clone()) .execute() .await .is_err() @@ -391,11 +397,13 @@ mod tests { .add_columns() .computed("doubled", "x * 2") .computed_options(ComputedColumnOptions { + gpu_class: Default::default(), + gpu_count: Default::default(), auto_refresh_enabled: true, auto_refresh_interval_seconds: None, - auto_refresh_resource_budget: Some( - crate::table::FunctionWorkerResourceBudget::new(1_000, 1_024), - ), + total_cpu_millis: Some(1000), + total_memory_bytes: Some(1024), + total_gpu_count: Some(0), }) .execute() .await diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index a87c38f3c..d1ec7d237 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -42,7 +42,6 @@ use serde_json::Value; use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding, OutputMapping}; use crate::materialized_view::without_declarations; -use crate::table::FunctionWorkerResourceBudget; use crate::utils::resolve_arrow_field_path; use crate::{Error, Result}; @@ -62,13 +61,9 @@ pub const INPUTS_META_KEY: &str = "computed_column.inputs"; pub const AUTO_REFRESH_ENABLED_META_KEY: &str = "computed_column.auto_refresh_enabled"; /// Minimum interval between successful automatic refreshes, in seconds. pub const AUTO_REFRESH_INTERVAL_META_KEY: &str = "computed_column.auto_refresh_interval_seconds"; -/// Aggregate worker-resource budget for automatic Function refreshes. -pub const AUTO_REFRESH_RESOURCE_BUDGET_META_KEY: &str = - "computed_column.auto_refresh_resource_budget"; - /// Scheduling settings persisted on each computed output. LanceDB Embedded /// stores these settings; automatic scheduling requires LanceDB Enterprise. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct ComputedColumnOptions { /// Permit automatic refresh. Manual refresh is always available. @@ -77,10 +72,22 @@ pub struct ComputedColumnOptions { /// When omitted, the server determines when to refresh. #[serde(skip_serializing_if = "Option::is_none")] pub auto_refresh_interval_seconds: Option, - /// Aggregate worker-resource budget for automatic Function refreshes. - /// This option requires a registered Function output. + /// Default total CPU budget in millicores for manual and automatic refreshes. + /// Requires a registered Function output. #[serde(skip_serializing_if = "Option::is_none")] - pub auto_refresh_resource_budget: Option, + pub total_cpu_millis: Option, + /// Default total memory budget in bytes for manual and automatic refreshes. + #[serde(skip_serializing_if = "Option::is_none")] + pub total_memory_bytes: Option, + /// Default total GPU budget for manual and automatic refreshes. + #[serde(skip_serializing_if = "Option::is_none")] + pub total_gpu_count: Option, + /// GPU pool used by each Function worker unless overridden at refresh. + #[serde(skip_serializing_if = "Option::is_none")] + pub gpu_class: Option, + /// Positive number of GPUs per worker, independent of the total budget. + #[serde(skip_serializing_if = "Option::is_none")] + pub gpu_count: Option, } impl Default for ComputedColumnOptions { @@ -88,12 +95,24 @@ impl Default for ComputedColumnOptions { Self { auto_refresh_enabled: true, auto_refresh_interval_seconds: None, - auto_refresh_resource_budget: None, + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + gpu_class: None, + gpu_count: None, } } } impl ComputedColumnOptions { + pub fn has_resource_defaults(&self) -> bool { + self.total_cpu_millis.is_some() + || self.total_memory_bytes.is_some() + || self.total_gpu_count.is_some() + || self.gpu_class.is_some() + || self.gpu_count.is_some() + } + /// Reject intervals that cannot be represented by the server scheduler. pub fn validate(&self) -> Result<()> { if self @@ -104,8 +123,28 @@ impl ComputedColumnOptions { message: "auto_refresh_interval_seconds must be a positive integer no greater than u64::MAX / 1000".into(), }); } - if let Some(budget) = &self.auto_refresh_resource_budget { - budget.validate()?; + if self.total_cpu_millis == Some(0) || self.total_memory_bytes == Some(0) { + return Err(Error::InvalidInput { + message: "total_cpu_millis and total_memory_bytes must be positive integers".into(), + }); + } + if let Some(class) = &self.gpu_class { + crate::function::validate_gpu_class_name(class)?; + } + if self.gpu_count == Some(0) { + return Err(Error::InvalidInput { + message: "gpu_count must be positive".into(), + }); + } + if self + .gpu_count + .zip(self.total_gpu_count) + .is_some_and(|(per_worker, total)| per_worker > total) + || (self.gpu_class.is_some() && self.total_gpu_count == Some(0)) + { + return Err(Error::InvalidInput { + message: "total_gpu_count cannot fit one Function worker".into(), + }); } Ok(()) } @@ -124,15 +163,29 @@ impl ComputedColumnOptions { message: "auto_refresh_interval_seconds must be a positive integer".into(), })?); } - if let Some(value) = metadata.get(AUTO_REFRESH_RESOURCE_BUDGET_META_KEY) { - options.auto_refresh_resource_budget = Some(serde_json::from_str(value).map_err( - |error| Error::InvalidInput { - message: format!( - "auto_refresh_resource_budget must be a valid resource budget: {error}" - ), - }, - )?); + if let Some(value) = metadata.get("computed_column.total_cpu_millis") { + options.total_cpu_millis = Some(value.parse().map_err(|_| Error::InvalidInput { + message: "invalid total_cpu_millis".into(), + })?); } + if let Some(value) = metadata.get("computed_column.total_memory_bytes") { + options.total_memory_bytes = Some(value.parse().map_err(|_| Error::InvalidInput { + message: "invalid total_memory_bytes".into(), + })?); + } + if let Some(value) = metadata.get("computed_column.total_gpu_count") { + options.total_gpu_count = Some(value.parse().map_err(|_| Error::InvalidInput { + message: "invalid total_gpu_count".into(), + })?); + } + options.gpu_class = metadata.get("computed_column.gpu_class").cloned(); + options.gpu_count = metadata + .get("computed_column.gpu_count") + .map(|value| value.parse()) + .transpose() + .map_err(|_| Error::InvalidInput { + message: "invalid gpu_count".into(), + })?; options.validate()?; Ok(options) } @@ -175,13 +228,20 @@ impl ComputedColumnOptions { if let Some(interval) = self.auto_refresh_interval_seconds { metadata.insert(AUTO_REFRESH_INTERVAL_META_KEY.into(), interval.to_string()); } - if let Some(budget) = &self.auto_refresh_resource_budget { - metadata.insert( - AUTO_REFRESH_RESOURCE_BUDGET_META_KEY.into(), - serde_json::to_string(budget).map_err(|error| Error::InvalidInput { - message: format!("failed to encode auto_refresh_resource_budget: {error}"), - })?, - ); + for (key, value) in [ + ("total_cpu_millis", self.total_cpu_millis), + ("total_memory_bytes", self.total_memory_bytes), + ("total_gpu_count", self.total_gpu_count.map(u64::from)), + ] { + if let Some(value) = value { + metadata.insert(format!("computed_column.{key}"), value.to_string()); + } + } + if let Some(class) = &self.gpu_class { + metadata.insert("computed_column.gpu_class".into(), class.clone()); + } + if let Some(count) = self.gpu_count { + metadata.insert("computed_column.gpu_count".into(), count.to_string()); } Ok(metadata) } @@ -2702,68 +2762,70 @@ pub(crate) mod test_support { #[cfg(test)] mod tests { + use arrow_array::{RecordBatch, record_batch}; + use arrow_schema::{DataType, TimeUnit}; + use futures::TryStreamExt; + use lance::dataset::ColumnAlteration; + + use super::*; + use crate::connect; + use crate::query::{ExecutableQuery, QueryBase, Select}; + use crate::{Error, Table}; + #[test] - fn computed_auto_refresh_resource_budget_metadata_round_trips() { - let budget = crate::table::FunctionWorkerResourceBudget::new(8_000, 17_179_869_184) - .with_gpu_count(2); + fn gpu_worker_defaults_round_trip_independently_of_totals() { let options = super::ComputedColumnOptions { - auto_refresh_enabled: true, - auto_refresh_interval_seconds: Some(300), - auto_refresh_resource_budget: Some(budget), + gpu_class: Some("any".into()), + gpu_count: Some(2), + total_gpu_count: Some(8), + ..Default::default() }; - assert_eq!( - super::ComputedColumnOptions::from_metadata(&HashMap::new()).unwrap(), - super::ComputedColumnOptions::default() - ); let metadata = options.metadata().unwrap(); - assert_eq!( - metadata - .get(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY) - .map(String::as_str), - Some(r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":2}"#) - ); + assert_eq!(metadata["computed_column.gpu_count"], "2"); + assert_eq!(metadata["computed_column.total_gpu_count"], "8"); assert_eq!( super::ComputedColumnOptions::from_metadata(&metadata).unwrap(), options ); - - let mut omitted_gpu = metadata.clone(); - omitted_gpu.insert( - super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY.into(), - r#"{"cpu_millis":8000,"memory_bytes":17179869184}"#.into(), + assert!( + super::ComputedColumnOptions { + gpu_count: Some(0), + ..Default::default() + } + .validate() + .is_err() ); - let decoded = super::ComputedColumnOptions::from_metadata(&omitted_gpu).unwrap(); - assert_eq!(decoded.auto_refresh_resource_budget.unwrap().gpu_count, 0); + assert!( + super::ComputedColumnOptions { + gpu_count: Some(4), + total_gpu_count: Some(2), + ..Default::default() + } + .validate() + .is_err() + ); + } + + #[test] + fn computed_default_resource_metadata_round_trips_partial_dimensions() { + let options = super::ComputedColumnOptions { + total_cpu_millis: Some(8000), + total_memory_bytes: None, + total_gpu_count: Some(0), + ..Default::default() + }; + let metadata = options.metadata().unwrap(); + assert_eq!(metadata["computed_column.total_cpu_millis"], "8000"); + assert_eq!(metadata["computed_column.total_gpu_count"], "0"); + assert!(!metadata.contains_key("computed_column.total_memory_bytes")); assert_eq!( - decoded - .metadata() - .unwrap() - .get(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY) - .map(String::as_str), - Some(r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":0}"#) + super::ComputedColumnOptions::from_metadata(&metadata).unwrap(), + options ); - - for invalid in [ - r#"{"memory_bytes":17179869184,"gpu_count":2}"#, - r#"{"cpu_millis":8000,"gpu_count":2}"#, - r#"{"cpu_millis":"8000","memory_bytes":17179869184,"gpu_count":2}"#, - r#"{"cpu_millis":-1,"memory_bytes":17179869184,"gpu_count":2}"#, - r#"{"cpu_millis":18446744073709551616,"memory_bytes":17179869184,"gpu_count":2}"#, - r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":-1}"#, - r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":4294967296}"#, - r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":2,"unknown":1}"#, - r#"{"cpu_millis":0,"memory_bytes":17179869184,"gpu_count":2}"#, - r#"{"cpu_millis":8000,"memory_bytes":0,"gpu_count":2}"#, - ] { - let mut malformed = metadata.clone(); - malformed.insert( - super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY.into(), - invalid.into(), - ); - assert!( - super::ComputedColumnOptions::from_metadata(&malformed).is_err(), - "accepted invalid budget: {invalid}" - ); + for invalid in ["0", "-1", "1.5", "18446744073709551616"] { + let malformed = + HashMap::from([("computed_column.total_cpu_millis".into(), invalid.into())]); + assert!(super::ComputedColumnOptions::from_metadata(&malformed).is_err()); } } @@ -2797,9 +2859,11 @@ mod tests { function_field("assignment", super::FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL), ]); let budget = crate::table::FunctionWorkerResourceBudget::new(8_000, 17_179_869_184) - .with_gpu_count(2); + .with_total_gpu_count(2); let updated = super::ComputedColumnOptions { - auto_refresh_resource_budget: Some(budget), + total_cpu_millis: Some((budget).total_cpu_millis), + total_memory_bytes: Some((budget).total_memory_bytes), + total_gpu_count: Some((budget).total_gpu_count), ..Default::default() } .apply_to_schema(&schema) @@ -2808,8 +2872,8 @@ mod tests { for name in ["first", "second"] { let metadata = updated.field_with_name(name).unwrap().metadata(); assert_eq!( - metadata.get(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY), - Some(&serde_json::to_string(&budget).unwrap()) + metadata.get("computed_column.total_cpu_millis"), + Some(&"8000".to_string()) ); assert_eq!( metadata.get("custom").map(String::as_str), @@ -2821,7 +2885,7 @@ mod tests { .field_with_name("assignment") .unwrap() .metadata() - .contains_key(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY) + .contains_key("computed_column.total_cpu_millis") ); } @@ -2928,16 +2992,6 @@ mod tests { } } - use arrow_array::{RecordBatch, record_batch}; - use arrow_schema::{DataType, TimeUnit}; - use futures::TryStreamExt; - use lance::dataset::ColumnAlteration; - - use super::*; - use crate::connect; - use crate::query::{ExecutableQuery, QueryBase, Select}; - use crate::{Error, Table}; - async fn table_with_ints(name: &str) -> Table { let conn = connect("memory://").execute().await.unwrap(); let batch = record_batch!(("x", Int32, [1, 2, 3])).unwrap(); diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 78530497f..15991dfe8 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -65,39 +65,39 @@ use crate::{Error, Result}; #[serde(deny_unknown_fields)] #[non_exhaustive] pub struct FunctionWorkerResourceBudget { - pub cpu_millis: u64, - pub memory_bytes: u64, + pub total_cpu_millis: u64, + pub total_memory_bytes: u64, /// Aggregate GPU budget across the refresh. Zero is CPU-only. #[serde(default)] - pub gpu_count: u32, + pub total_gpu_count: u32, } impl FunctionWorkerResourceBudget { /// Create a CPU-only aggregate budget. - pub fn new(cpu_millis: u64, memory_bytes: u64) -> Self { + pub fn new(total_cpu_millis: u64, total_memory_bytes: u64) -> Self { Self { - cpu_millis, - memory_bytes, - gpu_count: 0, + total_cpu_millis, + total_memory_bytes, + total_gpu_count: 0, } } /// Set the aggregate GPU budget. - pub fn with_gpu_count(mut self, gpu_count: u32) -> Self { - self.gpu_count = gpu_count; + pub fn with_total_gpu_count(mut self, total_gpu_count: u32) -> Self { + self.total_gpu_count = total_gpu_count; self } /// Require every per-tier resource limit to request at least one unit. pub fn validate(&self) -> Result<()> { - if self.cpu_millis == 0 { + if self.total_cpu_millis == 0 { return Err(Error::InvalidInput { - message: "resource_budget.cpu_millis must be greater than zero".into(), + message: "total_cpu_millis must be greater than zero".into(), }); } - if self.memory_bytes == 0 { + if self.total_memory_bytes == 0 { return Err(Error::InvalidInput { - message: "resource_budget.memory_bytes must be greater than zero".into(), + message: "total_memory_bytes must be greater than zero".into(), }); } Ok(()) @@ -270,7 +270,7 @@ pub struct RefreshColumnOptions { /// Override the registered Function's maximum concurrent user-code calls /// for this logical execution. Must be greater than zero. `None` uses the /// registration default, or disabled when the Function declares none. - /// This is not an account quota and does not change `resource_budget`. + /// This is not an account quota and does not change total resource limits. #[serde(skip_serializing_if = "Option::is_none")] pub max_concurrency: Option, /// Opt-in row-count threshold for publishing completed Function outputs. @@ -281,10 +281,12 @@ pub struct RefreshColumnOptions { /// rejects this option. #[serde(skip_serializing_if = "Option::is_none")] pub publication_interval_rows: Option, - /// Complete aggregate CPU, memory, and GPU budget for a registered - /// Function refresh. Cannot be combined with `gpu_count`. + /// Total CPU budget for this execution, in millicores. #[serde(skip_serializing_if = "Option::is_none")] - pub resource_budget: Option, + pub total_cpu_millis: Option, + /// Total memory budget for this execution, in bytes. + #[serde(skip_serializing_if = "Option::is_none")] + pub total_memory_bytes: Option, /// CPU, memory, and ephemeral-storage limits for the Function refresh /// supervisor pod. Enterprise only. #[serde(skip_serializing_if = "Option::is_none")] @@ -299,12 +301,14 @@ pub struct RefreshColumnOptions { /// when the Function does not declare one. #[serde(skip_serializing_if = "Option::is_none")] pub gpu_class: Option, - /// Positive aggregate GPU budget for Function workers in LanceDB - /// Enterprise. - /// - /// `None` leaves the server's configured budget unchanged. + /// Positive number of GPUs allocated to each Function worker. #[serde(skip_serializing_if = "Option::is_none")] pub gpu_count: Option, + /// Nonnegative total GPU budget for Function workers in LanceDB Enterprise. + /// Omitted values inherit column defaults, then Function defaults, then + /// deployment defaults. + #[serde(skip_serializing_if = "Option::is_none")] + pub total_gpu_count: Option, } impl RefreshColumnOptions { @@ -415,12 +419,15 @@ impl RefreshColumnOptions { self } - /// Set the aggregate worker resource budget for a Function refresh. - /// - /// Use [`FunctionWorkerResourceBudget::new`] for a CPU-only budget, or - /// [`FunctionWorkerResourceBudget::with_gpu_count`] to include GPUs. - pub fn resource_budget(mut self, budget: FunctionWorkerResourceBudget) -> Self { - self.resource_budget = Some(budget); + /// Override the total CPU budget for this refresh. + pub fn total_cpu_millis(mut self, value: u64) -> Self { + self.total_cpu_millis = Some(value); + self + } + + /// Override the total memory budget for this refresh. + pub fn total_memory_bytes(mut self, value: u64) -> Self { + self.total_memory_bytes = Some(value); self } @@ -442,12 +449,18 @@ impl RefreshColumnOptions { self } - /// Request an aggregate GPU budget of `gpu_count`. + /// Set the number of GPUs allocated to each Function worker. pub fn gpu_count(mut self, gpu_count: u32) -> Self { self.gpu_count = Some(gpu_count); self } + /// Request an aggregate GPU budget of `total_gpu_count`. + pub fn total_gpu_count(mut self, total_gpu_count: u32) -> Self { + self.total_gpu_count = Some(total_gpu_count); + self + } + /// The first set option a LanceDB Embedded refresh cannot honor, if any. pub fn enterprise_only_option(&self) -> Option<&'static str> { [ @@ -474,7 +487,9 @@ impl RefreshColumnOptions { "publication_interval_rows", self.publication_interval_rows.is_some(), ), - ("resource_budget", self.resource_budget.is_some()), + ("gpu_count", self.gpu_count.is_some()), + ("total_cpu_millis", self.total_cpu_millis.is_some()), + ("total_memory_bytes", self.total_memory_bytes.is_some()), ("supervisor_resources", self.supervisor_resources.is_some()), ("planning_workers", self.planning_workers.is_some()), ] @@ -564,14 +579,12 @@ impl RefreshColumnOptions { message: "publication_interval_rows must be greater than zero".into(), }); } - if self.resource_budget.is_some() && self.gpu_count.is_some() { + if self.total_cpu_millis == Some(0) || self.total_memory_bytes == Some(0) { return Err(Error::InvalidInput { - message: "gpu_count cannot be combined with resource_budget".into(), + message: "total_cpu_millis and total_memory_bytes must be positive integers".into(), }); } - if let Some(budget) = &self.resource_budget { - budget.validate()?; - } + if let Some(resources) = &self.supervisor_resources { resources.validate("supervisor_resources")?; } @@ -583,9 +596,19 @@ impl RefreshColumnOptions { } if self.gpu_count == Some(0) { return Err(Error::InvalidInput { - message: "gpu_count must be greater than zero".into(), + message: "gpu_count must be positive".into(), }); } + if self + .gpu_count + .zip(self.total_gpu_count) + .is_some_and(|(per_worker, total)| per_worker > total) + { + return Err(Error::InvalidInput { + message: "total_gpu_count cannot fit one Function worker".into(), + }); + } + Ok(()) } } @@ -2803,3 +2826,47 @@ mod tests { assert_eq!(payloads.value(0), payload); } } + +#[cfg(test)] +mod resource_validation_tests { + use super::{FunctionRefreshPlanningConfig, FunctionRefreshPodResources, RefreshColumnOptions}; + + #[test] + fn independent_totals_preserve_placement_and_pod_validation() { + assert!( + RefreshColumnOptions::default() + .total_cpu_millis(1000) + .validate() + .is_ok() + ); + assert!( + RefreshColumnOptions::default() + .total_gpu_count(0) + .validate() + .is_ok() + ); + assert!( + RefreshColumnOptions::default() + .gpu_class("H100:2") + .validate() + .is_err() + ); + assert!( + RefreshColumnOptions::default() + .supervisor_resources(FunctionRefreshPodResources::new(0, 1024, 1024)) + .validate() + .is_err() + ); + assert!( + RefreshColumnOptions::default() + .planning_workers(FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1000, 1024, 1024), + 0, + 1, + 1 + )) + .validate() + .is_err() + ); + } +} diff --git a/rust/lancedb/tests/first_class_function_slice2.rs b/rust/lancedb/tests/first_class_function_slice2.rs index 829486015..10114cbad 100644 --- a/rust/lancedb/tests/first_class_function_slice2.rs +++ b/rust/lancedb/tests/first_class_function_slice2.rs @@ -85,6 +85,9 @@ fn execution_controls_require_their_positive_ranges() { ("max_concurrency", Value::from(4_294_967_296_u64)), ("max_concurrency", Value::from(-1)), ("max_concurrency", Value::from(1.5)), + ("total_cpu_millis", Value::from(0)), + ("total_memory_bytes", Value::from(0)), + ("total_gpu_count", Value::from(4_294_967_296_u64)), ("row_timeout_seconds", Value::from(0)), ("row_timeout_seconds", Value::from(-0.25)), ] { From 08ddcdb7d7e26c79289a298d49edd6f95c84b24b Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Sun, 22 Nov 2026 15:40:22 +0800 Subject: [PATCH 74/78] feat: resume a failed Function refresh from its table (#5153) LanceDB Enterprise users can resume a failed Function refresh from its table with `table.resume_refresh(job_id)`. The synchronous and asynchronous Python APIs return a typed job handle. Waiting on that handle uses the same table freshness tracking as a newly submitted refresh. The request carries the current table identifier and branch to the server. The server decides whether the original attempt can be resumed and supplies the reason when it cannot. The Python refresh methods also accept a positive `max_job_attempts` option for automatic recovery. These features require server support for Function refresh recovery. The PR adds remote request, branch, error propagation, and typed result tests. Python and Rust validation runs in PR CI. --- docs/web/management/function-failures.mdx | 30 ++++++ python/python/lancedb/_lancedb.pyi | 3 + python/python/lancedb/remote/table.py | 7 ++ python/python/lancedb/table.py | 39 ++++++++ python/python/tests/test_remote_db.py | 52 +++++++++++ python/src/table.rs | 19 +++- rust/lancedb/src/remote/table.rs | 109 ++++++++++++++++------ rust/lancedb/src/table.rs | 28 ++++++ rust/lancedb/src/table/refresh.rs | 15 +++ 9 files changed, 270 insertions(+), 32 deletions(-) diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx index b7f554402..793563414 100644 --- a/docs/web/management/function-failures.mdx +++ b/docs/web/management/function-failures.mdx @@ -135,6 +135,36 @@ views, with errors identified by Function invocation and source input. Column retry and upgrade helpers apply to Function columns; use the materialized-view refresh reference for view refresh options. +## Resume a failed refresh job {#resume-refresh} + +Job recovery requires a Python or Rust SDK that exposes `resume_refresh` and +an Enterprise deployment that supports `POST /v1/table/{id}/resume_refresh`. +The `workflow_version` reported by `function_errors` covers row-error +operations. Check your server release for job recovery support separately. + +Open the original table on the branch where the refresh failed. Pass the +failed job ID to get a handle for the successor attempt and wait for its result. + +```python +resumed = table.resume_refresh(failed_job_id) +result = resumed.wait() +``` + +```rust +async fn resume(table: &lancedb::Table, failed_job_id: &str) -> lancedb::Result<()> { + let resumed = table.resume_refresh(failed_job_id).await?; + let result = resumed.wait().await?; + println!("Assigned {} rows", result.rows_assigned); + Ok(()) +} +``` + +The server reuses confirmed outputs. If it reports that an external call may +already have run, check the external result before starting another refresh. +For a Function with external effects, set `max_job_attempts=1` when submitting +the refresh until you have verified replay safety on your deployment. A limit +of `1` counts the initial attempt and disables automatic job retries. + ## Older-deployment recipes {#older-deployments} The following sections describe deployments without workflow version 1. Their diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a1d4c2445..12bd81fdd 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -804,6 +804,7 @@ class Table: row_timeout_seconds: Optional[float] = None, init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, + max_job_attempts: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, retry_errors: bool = False, retry_job_id: Optional[str] = None, @@ -834,6 +835,7 @@ class Table: row_timeout_seconds: Optional[float] = None, init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, + max_job_attempts: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, retry_errors: bool = False, retry_job_id: Optional[str] = None, @@ -842,6 +844,7 @@ class Table: function_version: Optional[str] = None, recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> Job: ... + async def resume_refresh(self, job_id: str) -> Job: ... async def function_errors( self, job_id: Optional[str] = None, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 2b723d0d4..715804e4b 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1237,6 +1237,7 @@ class RemoteTable(Table): row_timeout_seconds: Optional[float] = None, init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, + max_job_attempts: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, retry_errors: bool = False, retry_job_id: Optional[str] = None, @@ -1265,6 +1266,7 @@ class RemoteTable(Table): row_timeout_seconds=row_timeout_seconds, init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, + max_job_attempts=max_job_attempts, max_executor_processes_per_worker=max_executor_processes_per_worker, retry_errors=retry_errors, retry_job_id=retry_job_id, @@ -1296,6 +1298,7 @@ class RemoteTable(Table): row_timeout_seconds: Optional[float] = None, init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, + max_job_attempts: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, retry_errors: bool = False, retry_job_id: Optional[str] = None, @@ -1325,6 +1328,7 @@ class RemoteTable(Table): row_timeout_seconds=row_timeout_seconds, init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, + max_job_attempts=max_job_attempts, max_executor_processes_per_worker=max_executor_processes_per_worker, retry_errors=retry_errors, retry_job_id=retry_job_id, @@ -1336,6 +1340,9 @@ class RemoteTable(Table): ) ) + def resume_refresh(self, job_id: str) -> Job[RefreshColumnResult]: + return Job(LOOP.run(self._table.resume_refresh(job_id))) + def function_errors( self, job_id: Optional[str] = None, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index bcc540517..fad89db49 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -3591,6 +3591,7 @@ class Table(ABC): row_timeout_seconds: Optional[float] = None, init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, + max_job_attempts: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, retry_errors: bool = False, retry_job_id: Optional[str] = None, @@ -3686,6 +3687,9 @@ class Table(ABC): Worker count for an expression column; registered Function columns reject it and set the corresponding ``total_*`` options. LanceDB Enterprise only. + max_job_attempts: int, optional + Total automatic Function refresh attempts, including the initial job. + Set to 1 to disable automatic job recovery. max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. @@ -3737,6 +3741,7 @@ class Table(ABC): row_timeout_seconds: Optional[float] = None, init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, + max_job_attempts: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, retry_errors: bool = False, retry_job_id: Optional[str] = None, @@ -3831,6 +3836,9 @@ class Table(ABC): Worker count for an expression column; registered Function columns reject it and set the corresponding ``total_*`` options. LanceDB Enterprise only. + max_job_attempts: int, optional + Total automatic Function refresh attempts, including the initial job. + Set to 1 to disable automatic job recovery. max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. @@ -3873,6 +3881,16 @@ class Table(ABC): 'finished' """ + def resume_refresh(self, job_id: str) -> Job[RefreshColumnJobResult]: + """Resume a failed Function refresh on this table's current branch. + + Returns the successor job. Call its ``wait()`` method for the refresh + result. Requires LanceDB Enterprise. + """ + raise NotImplementedError( + "resuming a Function refresh requires LanceDB Enterprise" + ) + def retry_failed( self, column: str, @@ -6541,6 +6559,7 @@ class LanceTable(Table): row_timeout_seconds: Optional[float] = None, init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, + max_job_attempts: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, retry_errors: bool = False, retry_job_id: Optional[str] = None, @@ -6572,6 +6591,7 @@ class LanceTable(Table): row_timeout_seconds=row_timeout_seconds, init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, + max_job_attempts=max_job_attempts, max_executor_processes_per_worker=max_executor_processes_per_worker, retry_errors=retry_errors, retry_job_id=retry_job_id, @@ -6605,6 +6625,7 @@ class LanceTable(Table): row_timeout_seconds: Optional[float] = None, init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, + max_job_attempts: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, retry_errors: bool = False, retry_job_id: Optional[str] = None, @@ -6638,6 +6659,7 @@ class LanceTable(Table): row_timeout_seconds=row_timeout_seconds, init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, + max_job_attempts=max_job_attempts, max_executor_processes_per_worker=max_executor_processes_per_worker, retry_errors=retry_errors, retry_job_id=retry_job_id, @@ -9274,6 +9296,7 @@ class AsyncTable: row_timeout_seconds: Optional[float] = None, init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, + max_job_attempts: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, retry_errors: bool = False, retry_job_id: Optional[str] = None, @@ -9369,6 +9392,9 @@ class AsyncTable: Worker count for an expression column; registered Function columns reject it and set the corresponding ``total_*`` options. LanceDB Enterprise only. + max_job_attempts: int, optional + Total automatic Function refresh attempts, including the initial job. + Set to 1 to disable automatic job recovery. max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. @@ -9423,6 +9449,7 @@ class AsyncTable: row_timeout_seconds=row_timeout_seconds, init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, + max_job_attempts=max_job_attempts, max_executor_processes_per_worker=max_executor_processes_per_worker, retry_errors=retry_errors, retry_job_id=retry_job_id, @@ -9433,6 +9460,13 @@ class AsyncTable: gpu_count=gpu_count, ) + async def resume_refresh(self, job_id: str) -> AsyncJob[RefreshColumnJobResult]: + """Resume a failed Enterprise Function refresh on this table and branch.""" + return _typed_job( + await self._inner.resume_refresh(job_id), + RefreshColumnJobResult.from_json, + ) + async def retry_failed( self, column: str, @@ -9652,6 +9686,7 @@ class AsyncTable: row_timeout_seconds: Optional[float] = None, init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, + max_job_attempts: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, retry_errors: bool = False, retry_job_id: Optional[str] = None, @@ -9746,6 +9781,9 @@ class AsyncTable: Worker count for an expression column; registered Function columns reject it and set the corresponding ``total_*`` options. LanceDB Enterprise only. + max_job_attempts: int, optional + Total automatic Function refresh attempts, including the initial job. + Set to 1 to disable automatic job recovery. max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. @@ -9817,6 +9855,7 @@ class AsyncTable: row_timeout_seconds=row_timeout_seconds, init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, + max_job_attempts=max_job_attempts, max_executor_processes_per_worker=max_executor_processes_per_worker, retry_errors=retry_errors, retry_job_id=retry_job_id, diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index e72487a41..f8d264e31 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2391,6 +2391,7 @@ def test_remote_create_index_async_returns_job(): "row_timeout_seconds": 30, "init_timeout_seconds": 120, "num_workers": 4, + "max_job_attempts": 4, "max_executor_processes_per_worker": 2, }, ], @@ -2438,6 +2439,7 @@ async def test_remote_refresh_async_returns_typed_terminal_result( "row_timeout_seconds", "init_timeout_seconds", "num_workers", + "max_job_attempts", "max_executor_processes_per_worker", ): if refresh_kwargs.get(key) is not None: @@ -2510,6 +2512,56 @@ async def test_remote_refresh_async_returns_typed_terminal_result( assert result.version == 8 +@pytest.mark.asyncio +@pytest.mark.parametrize("async_table", [True, False]) +async def test_resume_refresh_returns_typed_successor(async_table): + terminal = { + "rows_assigned": 12, + "rows_failed": 0, + "rows_remaining": 0, + "source_version": 7, + "published_version": 8, + } + + 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": 1, "schema": {"fields": []}} + elif request.path == "/v1/table/test/resume_refresh": + assert body == {"job_id": "failed"} + response = {"job_id": "successor"} + elif request.path == "/v1/jobs/describe": + assert body["job_id"] == "successor" + response = { + "job_id": "successor", + "job_type": "function_refresh", + "job_state": "DONE", + "result": terminal, + } + else: + raise AssertionError(f"Unexpected request: {request.path}") + 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") + job = await table.resume_refresh("failed") + result = await job.wait(timeout=timedelta(seconds=30)) + else: + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + job = table.resume_refresh("failed") + result = job.wait(timeout=timedelta(seconds=30)) + + assert job.id() == "successor" + assert isinstance(result, lancedb.RefreshColumnResult) + assert result.model_dump(exclude_defaults=True) == terminal + + def test_remote_refresh_async_forwards_progress_from_submitted_handle(): terminal_result = { "rows_assigned": 12, diff --git a/python/src/table.rs b/python/src/table.rs index a0ca2d73e..63eb45c4e 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -57,6 +57,7 @@ struct RefreshColumnArgs { where_clause: Option, batch_size: Option, max_concurrency: Option, + max_job_attempts: Option, publication_interval_rows: Option, total_cpu_millis: Option, total_memory_bytes: Option, @@ -217,6 +218,7 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult PyResult( self_: PyRef<'py, Self>, @@ -2770,6 +2773,7 @@ impl Table { init_timeout_seconds: Option, num_workers: Option, max_executor_processes_per_worker: Option, + max_job_attempts: Option>, retry_errors: bool, retry_job_id: Option, retry_error_type: Option, @@ -2803,6 +2807,7 @@ impl Table { init_timeout_seconds, num_workers, max_executor_processes_per_worker, + max_job_attempts: positive_u32_integer(max_job_attempts.as_ref(), "max_job_attempts")?, })?; let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -2814,7 +2819,7 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, total_cpu_millis=None, total_memory_bytes=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, total_gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, total_cpu_millis=None, total_memory_bytes=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, total_gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, max_job_attempts=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column_async<'py>( self_: PyRef<'py, Self>, @@ -2838,6 +2843,7 @@ impl Table { init_timeout_seconds: Option, num_workers: Option, max_executor_processes_per_worker: Option, + max_job_attempts: Option>, retry_errors: bool, retry_job_id: Option, retry_error_type: Option, @@ -2871,6 +2877,7 @@ impl Table { init_timeout_seconds, num_workers, max_executor_processes_per_worker, + max_job_attempts: positive_u32_integer(max_job_attempts.as_ref(), "max_job_attempts")?, })?; let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -2882,6 +2889,14 @@ impl Table { }) } + pub fn resume_refresh(self_: PyRef<'_, Self>, job_id: String) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let job = inner.resume_refresh(job_id).await.infer_error()?; + Ok(crate::job::Job::new_typed(job)) + }) + } + #[pyo3(signature = (job_id=None, column=None, limit=None, history=false, page_token=None))] pub fn function_errors( self_: PyRef<'_, Self>, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 3793612c6..3642fb950 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -920,6 +920,45 @@ impl RemoteTable { Ok(job_id) } + async fn submit_refresh( + &self, + operation: &str, + mut body: serde_json::Value, + ) -> Result> { + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/{operation}", self.identifier)) + .json(&body); + let (request_id, response) = self.send(request, true).await?; + // Preserve dependency errors: a deleted bound Function also returns 404. + let response = self + .client + .check_response(&request_id, response) + .await + .inspect_err(|error| self.handle_error_invalidation(error))?; + let body = response.text().await.err_to_http(request_id.clone())?; + + #[derive(serde::Deserialize)] + struct RefreshJobResponse { + job_id: String, + } + let response: RefreshJobResponse = + serde_json::from_str(&body).map_err(|e| Error::Http { + source: format!("Failed to parse {operation} response: {}", e).into(), + request_id, + status_code: None, + })?; + + Ok(Job::new_typed(Box::new(FreshnessJob { + inner: RemoteJob::new(self.client.clone(), response.job_id), + freshness: self.freshness.clone(), + version: self.version.clone(), + tracked_result: TrackedJobResult::RefreshColumn, + freshness_request: self.snapshot_freshness_headers(), + }))) + } + fn index_job(&self, job_id: String) -> Job { Job::new(Box::new(FreshnessJob { inner: RemoteJob::new(self.client.clone(), job_id), @@ -4569,37 +4608,16 @@ impl BaseTable for RemoteTable { message: format!("failed to serialize refresh options: {e}"), })?; body["column"] = serde_json::json!(column); - self.apply_branch_body(&mut body); - let request = self - .client - .post(&format!("/v1/table/{}/backfill_column", self.identifier)) - .json(&body); - let (request_id, response) = self.send(request, true).await?; - // Preserve dependency errors: a deleted bound Function also returns 404. - let response = self - .client - .check_response(&request_id, response) + self.submit_refresh("backfill_column", body).await + } + + async fn resume_refresh( + &self, + job_id: &str, + ) -> Result> { + self.check_mutable().await?; + self.submit_refresh("resume_refresh", serde_json::json!({ "job_id": job_id })) .await - .inspect_err(|error| self.handle_error_invalidation(error))?; - let body = response.text().await.err_to_http(request_id.clone())?; - - #[derive(serde::Deserialize)] - struct BackfillResponse { - job_id: String, - } - let response: BackfillResponse = serde_json::from_str(&body).map_err(|e| Error::Http { - source: format!("Failed to parse backfill_column response: {}", e).into(), - request_id, - status_code: None, - })?; - - Ok(Job::new_typed(Box::new(FreshnessJob { - inner: RemoteJob::new(self.client.clone(), response.job_id), - freshness: self.freshness.clone(), - version: self.version.clone(), - tracked_result: TrackedJobResult::RefreshColumn, - freshness_request: self.snapshot_freshness_headers(), - }))) } async fn function_errors( @@ -12386,6 +12404,10 @@ mod tests { RefreshColumnOptions::default().max_concurrency(0), "max_concurrency", ), + ( + RefreshColumnOptions::default().max_job_attempts(0), + "max_job_attempts", + ), ( RefreshColumnOptions::default().max_executor_processes_per_worker(0), "max_executor_processes_per_worker", @@ -18802,6 +18824,33 @@ mod tests { assert_eq!(branch.current_branch(), Some("exp".to_string())); } + #[tokio::test] + async fn resume_refresh_preserves_the_branch_and_server_rejection() { + let table = Table::new_with_handler("my_table", |request| { + match request.url().path() { + "/v1/table/my_table/branches/list/" => http::Response::builder() + .status(200) + .body(r#"{"branches":{"exp":{"parentBranch":null,"parentVersion":1,"createAt":1,"manifestSize":1}}}"#) + .unwrap(), + "/v1/table/my_table/resume_refresh" => { + let payload: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(payload, json!({"job_id":"failed","branch":"exp"})); + http::Response::builder() + .status(400) + .body("Check the external result before issuing another refresh") + .unwrap() + } + path => panic!("unexpected path {path}"), + } + }); + let branch = table.checkout_branch("exp", None).await.unwrap(); + let error = branch.resume_refresh("failed").await.unwrap_err(); + assert!( + error.to_string().contains("Check the external result"), + "{error}" + ); + } + #[tokio::test] async fn test_checkout_branch_missing() { let table = Table::new_with_handler("my_table", |_| { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 8ad9a0d65..0728484da 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1021,6 +1021,15 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { } self.refresh_column_async(column).await } + /// Resume a failed Function refresh on this table and branch. + async fn resume_refresh( + &self, + _job_id: &str, + ) -> Result> { + Err(Error::NotSupported { + message: "resuming a Function refresh requires LanceDB Enterprise".into(), + }) + } /// The per-row errors Function refreshes recorded on this table; see /// [`Table::function_errors`]. The default returns `NotSupported`. async fn function_errors( @@ -2424,6 +2433,25 @@ impl Table { self.inner.refresh_column_async(column.as_ref()).await } + /// Resume a failed Function refresh on this table and its current branch. + /// Returns the successor attempt. Its result includes the published table version. + /// + /// ``` + /// # use lancedb::Table; + /// # async fn resume(table: &Table, failed_job_id: &str) -> lancedb::Result<()> { + /// let job = table.resume_refresh(failed_job_id).await?; + /// let result = job.wait().await?; + /// println!("assigned {} rows", result.rows_assigned); + /// # Ok(()) + /// # } + /// ``` + pub async fn resume_refresh( + &self, + job_id: impl AsRef, + ) -> Result> { + self.inner.resume_refresh(job_id.as_ref()).await + } + /// Like [`Table::refresh_column_async`], with explicit refresh options. /// /// Set [`RefreshColumnOptions::batch_size()`] to cap the rows each remote diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 15991dfe8..bf0c84e8f 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -233,6 +233,9 @@ pub struct RefreshColumnOptions { /// Only refresh the rows matching this SQL filter. Enterprise only. #[serde(rename = "where", skip_serializing_if = "Option::is_none")] pub where_clause: Option, + /// Total Function refresh attempts, including the initial job. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_job_attempts: Option, /// Override the Function's default user-code retry policy. Enterprise only. #[serde(skip_serializing_if = "Option::is_none")] pub retry_policy: Option, @@ -382,6 +385,12 @@ impl RefreshColumnOptions { self } + /// Set the total job attempt limit for automatic Function refresh recovery. + pub fn max_job_attempts(mut self, attempts: u32) -> Self { + self.max_job_attempts = Some(attempts); + self + } + /// Cap executor processes per Function worker at `processes`. pub fn max_executor_processes_per_worker(mut self, processes: u32) -> Self { self.max_executor_processes_per_worker = Some(processes); @@ -478,6 +487,7 @@ impl RefreshColumnOptions { ("row_timeout_seconds", self.row_timeout_seconds.is_some()), ("init_timeout_seconds", self.init_timeout_seconds.is_some()), ("num_workers", self.num_workers.is_some()), + ("max_job_attempts", self.max_job_attempts.is_some()), ( "max_executor_processes_per_worker", self.max_executor_processes_per_worker.is_some(), @@ -559,6 +569,11 @@ impl RefreshColumnOptions { message: "num_workers must be greater than zero".into(), }); } + if self.max_job_attempts == Some(0) { + return Err(Error::InvalidInput { + message: "max_job_attempts must be greater than zero".into(), + }); + } if self.max_executor_processes_per_worker == Some(0) { return Err(Error::InvalidInput { message: "max_executor_processes_per_worker must be greater than zero".into(), From d9b49e8889ada1f5eed6d6019cf57f0301a5ac60 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Sun, 22 Nov 2026 16:00:50 +0800 Subject: [PATCH 75/78] feat: report capacity waits in function refresh job status (#5154) An Enterprise Function refresh can spend time waiting for execution workers. Applications polling `job.status()` currently see `running` during that wait. Return `waiting_for_capacity` when the server reports that phase for an active Function refresh. The next status request reports `running` when execution resumes. Applications can use `job.wait()` to wait through both states until completion. Rust, Python and Node read the phase from the existing job description response. ## Validation Two HTTP regression tests exercise the public job handle. They cover the wait, work resuming, completion after another wait, a stale phase at completion, queued and paused refreshes, other job types, and servers that omit the phase. The Rust CI remote job runs these tests. --- docs/src/js/classes/Job.md | 4 +- docs/web/basics/jobs.mdx | 13 ++++--- nodejs/lancedb/job.ts | 4 +- nodejs/src/job.rs | 4 +- python/python/lancedb/job.py | 13 ++++--- rust/lancedb/src/job.rs | 21 ++++++++--- rust/lancedb/src/remote/db.rs | 69 +++++++++++++++++++++++++++++++++++ 7 files changed, 104 insertions(+), 24 deletions(-) diff --git a/docs/src/js/classes/Job.md b/docs/src/js/classes/Job.md index 6d30996d2..86c5abc1f 100644 --- a/docs/src/js/classes/Job.md +++ b/docs/src/js/classes/Job.md @@ -449,8 +449,8 @@ Select this exact attempt's pinned successor. Requires backend support. status(): Promise ``` -The operation's current lifecycle state: "running", "finished", "failed", -or "cancelled". +The current status, usually "running", "finished", "failed", or "cancelled". +A Function refresh waiting for execution workers reports "waiting_for_capacity". A point snapshot; unlike [Job.wait](Job.md#wait) it does not block or reject on a terminal failure state. Also refreshes the getters above. diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index cdff84339..80726a5f1 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -106,10 +106,10 @@ print(result, job.spec()) ``` -The four lifecycle strings below are the usual SDK contract; newer server -states may pass through an older client. Do not infer execution progress from -`state` alone. Structured progress methods and queue fields require matching -SDK/server support; see [refresh admission](/feature-engineering/refresh-column#admission). +`job.state()` reports the last observed lifecycle state, usually `running`, +`finished`, `failed`, or `cancelled`. Newer server states may pass through an +older client. For execution progress and queue details, use `job.progress()` +with a supporting SDK and server. See [refresh admission](/feature-engineering/refresh-column#admission). ## Submit and wait for a job {#waiting} @@ -120,11 +120,12 @@ SDK/server support; see [refresh admission](/feature-engineering/refresh-column# result. If it failed or was cancelled, inspect the failure details and any results it committed before stopping. -In Python, `job.status()` returns the current state: +In Python, `job.status()` reports the current status. -| State | Meaning | +| Status | Meaning | | --- | --- | | `running` | The operation is in progress. | +| `waiting_for_capacity` | An Enterprise Function refresh is waiting for execution workers. This status is nonterminal. It returns to `running` when execution resumes. | | `finished` | The operation completed successfully. | | `failed` | The operation failed. | | `cancelled` | The operation was cancelled. | diff --git a/nodejs/lancedb/job.ts b/nodejs/lancedb/job.ts index 49b83477c..a8298c8b9 100644 --- a/nodejs/lancedb/job.ts +++ b/nodejs/lancedb/job.ts @@ -251,8 +251,8 @@ export class Job { } /** - * The operation's current lifecycle state: "running", "finished", "failed", - * or "cancelled". + * The current status, usually "running", "finished", "failed", or "cancelled". + * A Function refresh waiting for execution workers reports "waiting_for_capacity". * * A point snapshot; unlike {@link Job.wait} it does not block or reject on a * terminal failure state. Also refreshes the getters above. diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 0ff4b916b..b76793717 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -106,8 +106,8 @@ impl Job { self.inner.execution_epoch() } - /// The operation's current lifecycle state: "running", "finished", - /// "failed", or "cancelled". + /// The current status, usually "running", "finished", "failed", or "cancelled". + /// A Function refresh waiting for execution workers reports "waiting_for_capacity". /// /// A point snapshot; unlike {@link Job.wait} it does not block or reject /// on a terminal failure state. States a newer server reports that this diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 6bdb026f7..778d44e2b 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -316,8 +316,9 @@ class AsyncJob(Generic[T]): return self._inner.id if self._inner is not None else None async def status(self) -> str: - """The operation's current lifecycle state: "running", "finished", - "failed", or "cancelled". + """Return the current status, usually "running", "finished", "failed", + or "cancelled". A Function refresh waiting for execution workers reports + "waiting_for_capacity". A point snapshot; unlike `wait` it does not block or raise on a terminal failure state. States a newer server reports that this @@ -384,8 +385,7 @@ class AsyncJob(Generic[T]): Queue metadata and counters are included when supplied by the server. Older servers may omit counters, and in-process operations return ``None``. A missing - counter is unknown rather than zero. This is additive to :meth:`status`, - whose string contract is unchanged. + counter is unknown rather than zero. """ if self._inner is None: return None @@ -1070,8 +1070,9 @@ class Job(Generic[T]): return self._inner._id if self._inner is not None else None def status(self) -> str: - """The operation's current lifecycle state: "running", "finished", - "failed", or "cancelled". + """Return the current status, usually "running", "finished", "failed", + or "cancelled". A Function refresh waiting for execution workers reports + "waiting_for_capacity". See :meth:`AsyncJob.status`. """ diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 44928eca7..5485c8905 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -516,17 +516,25 @@ where }; match handle.describe().await { Ok(description) => { - let state = description.state.clone(); let mut cache = self.cache_write(); - cache.state = Some(state.clone()); + cache.state = Some(description.state.clone()); cache.lifecycle_state = Some( description .lifecycle_state .clone() - .unwrap_or_else(|| JobState::from(state.as_str())), + .unwrap_or_else(|| JobState::from(description.state.as_str())), ); + let status = if cache.lifecycle_state == Some(JobState::InProgress) + && description.job_type == "function_refresh" + && description.paused_at_millis.is_none() + && description.phase.as_deref() == Some("waiting_for_capacity") + { + "waiting_for_capacity".to_owned() + } else { + description.state.clone() + }; cache.description = Some(description); - Ok(state) + Ok(status) } // An in-process job knows its own state and nothing more. Err(Error::NotSupported { .. }) => { @@ -540,8 +548,9 @@ where } } - /// The operation's current lifecycle state: "running", "finished", - /// "failed", or "cancelled". + /// The current status, usually "running", "finished", "failed", or "cancelled". + /// A running Function refresh reports "waiting_for_capacity" while it + /// waits for execution workers. [`Job::wait`] continues polling during this wait. /// /// A point snapshot; unlike [`Job::wait`] it does not block, raise on a /// terminal failure state, or retry. States a newer server reports that diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index b44d6e26f..9b26c9f3b 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -5126,6 +5126,75 @@ mod tests { )); } + #[tokio::test] + async fn function_refresh_status_tracks_capacity_without_ending_wait() { + let polls = Arc::new(AtomicUsize::new(0)); + let count = polls.clone(); + let conn = Connection::new_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + // Open, status while waiting, status after admission, another wait + // observed inside wait(), and finally a successful completion. + let (state, phase) = match count.fetch_add(1, Ordering::SeqCst) { + 0 | 1 | 3 => ("IN_PROGRESS", "waiting_for_capacity"), + 2 => ("IN_PROGRESS", "running"), + _ => ("SUCCEEDED", "waiting_for_capacity"), + }; + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id": "job-1", "job_type": "function_refresh", + "job_state": state, "phase": phase, "creation_ms": 1 + }) + .to_string(), + ) + .unwrap() + }); + let job = conn.open_job("job-1").await.unwrap(); + assert_eq!(job.status().await.unwrap(), "waiting_for_capacity"); + assert_eq!(job.state().as_deref(), Some("running")); + assert_eq!(job.status().await.unwrap(), "running"); + job.wait().await.unwrap(); + assert_eq!(job.status().await.unwrap(), "finished"); + assert!(polls.load(Ordering::SeqCst) >= 6); + } + + #[tokio::test] + async fn capacity_status_requires_an_active_function_refresh() { + for (job_type, lifecycle, phase, paused_at) in [ + ( + "create_index", + "in_progress", + Some("waiting_for_capacity"), + None, + ), + ( + "function_refresh", + "in_progress", + Some("waiting_for_capacity"), + Some(42), + ), + ( + "function_refresh", + "queued", + Some("waiting_for_capacity"), + None, + ), + ("function_refresh", "in_progress", None, None), + ] { + let conn = Connection::new_with_handler(move |_| { + http::Response::builder().status(200).body( + serde_json::json!({ + "job_id": "job-1", "job_type": job_type, "job_state": "IN_PROGRESS", + "lifecycle_state": lifecycle, "phase": phase, "paused_at_millis": paused_at + }).to_string() + ).unwrap() + }); + let job = conn.open_job("job-1").await.unwrap(); + assert_eq!(job.status().await.unwrap(), "running"); + } + } + #[tokio::test] async fn test_conn_job_waits_to_done() { let polls = Arc::new(AtomicUsize::new(0)); From b63cec40b41027277276b1ed032f7c5b4ba673a3 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sun, 22 Nov 2026 20:33:57 +0800 Subject: [PATCH 76/78] fix(deps): update url to 2.5.9 for RUSTSEC-2026-0592 (#5158) Updates the lockfile from `url` 2.5.8 to 2.5.9, the first release patched for RUSTSEC-2026-0592, and from `form_urlencoded` 1.2.2 to 1.2.3, which `url` 2.5.9 requires (`^1.2.3`). `main` also locks `url` 2.5.8. The advisory is the cargo-deny failure currently blocking #5157, whose Lance beta.26 bump leaves the same lockfile entry in place. No dependency requirement or advisory ignore changes: `url = "2"` already permits 2.5.9. `url` 2.5.9 declares MSRV 1.63 and `form_urlencoded` 1.2.3 declares 1.51, both below the workspace's 1.95.0. Validation: - `cargo metadata --locked` - `cargo tree -i url@2.5.9 --locked` - `git diff --check` --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8fb71f02a..4b8ea97b7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3737,9 +3737,9 @@ checksum = "ee1b05cbd864bcaecbd3455d6d967862d446e4ebfc3c2e5e5b9841e53cba6673" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -11788,9 +11788,9 @@ dependencies = [ [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", From a09cd6fb8c73e401538071535b5b14ee2a468f4c Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Sun, 22 Nov 2026 06:25:33 -0800 Subject: [PATCH 77/78] chore: update lance dependency to v15.0.0-beta.26 (#5157) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Update the Rust, Java, and Python dependencies to [Lance v15.0.0-beta.26](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.26). Align the transitive Jieba macro version with Lance’s lockfile and fix the Clippy diagnostics exposed by workspace validation. Co-authored-by: Xuanwo --- Cargo.lock | 104 ++++++++++++++++---------------- Cargo.toml | 30 ++++----- java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/src/job.rs | 2 +- python/src/table.rs | 6 +- python/uv.lock | 21 +++---- rust/lancedb/src/job/profile.rs | 2 +- 8 files changed, 83 insertions(+), 86 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4b8ea97b7..863e60d6e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3836,8 +3836,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5141,18 +5141,18 @@ checksum = "9028f49264629065d057f340a86acb84867925865f73bbf8d47b4d149a7e88b8" [[package]] name = "jieba-macros" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46adade69b634535a8f495cf87710ed893cff53e1dbc9dd750c2ab81c5defb82" +checksum = "38fc0f3831de71556de69643b80a08a5c8cd260a23c6b8dbeb7cd923c779cac5" dependencies = [ "phf_codegen 0.13.1", ] [[package]] name = "jieba-rs" -version = "0.10.1" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11b53580aaa8ec8b713da271da434f8947409242c537a9ab3f7b76bdbb19e8a9" +checksum = "bb5bdea4dc241d589e179f39d2a778f31490f3370aa2f626223dbd930ebc5c9d" dependencies = [ "bytecount", "cedarwood", @@ -5315,8 +5315,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arc-swap", "arrow", @@ -5391,8 +5391,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-buffer", @@ -5414,7 +5414,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-buffer", @@ -5428,7 +5428,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-schema", @@ -5437,8 +5437,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrayref", "crunchy", @@ -5448,8 +5448,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-buffer", @@ -5487,8 +5487,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow", "arrow-array", @@ -5519,8 +5519,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow", "arrow-array", @@ -5545,8 +5545,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow", "arrow-array", @@ -5563,8 +5563,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "proc-macro2", "quote", @@ -5573,8 +5573,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-arith", "arrow-array", @@ -5608,8 +5608,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-arith", "arrow-array", @@ -5640,8 +5640,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-schema", @@ -5672,8 +5672,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arc-swap", "arrow", @@ -5746,8 +5746,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-schema", @@ -5770,8 +5770,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow", "arrow-array", @@ -5816,8 +5816,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "byteorder", "ethnum", @@ -5834,8 +5834,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5850,8 +5850,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow", "async-trait", @@ -5865,8 +5865,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arc-swap", "arrow", @@ -5920,8 +5920,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-buffer", @@ -5935,8 +5935,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow", "arrow-array", @@ -5977,8 +5977,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-schema", @@ -5991,8 +5991,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 1b277c625..4ea1d12ac 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.25", default-features = false, "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.25", default-features = false, "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.25", default-features = false, "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.26", default-features = false, "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.26", default-features = false, "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.26", default-features = false, "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/java/pom.xml b/java/pom.xml index 06bfe4687..cd245e179 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.25 + 15.0.0-beta.26 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index 69130e16c..6e43633d6 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b25", + "pylance==15.0.0b26", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/src/job.rs b/python/src/job.rs index ec1f55d32..c5ce9e60b 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -187,7 +187,7 @@ impl Job { pub fn retry(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { - Ok(Job { + Ok(Self { inner: Arc::new(inner.retry().await.infer_error()?), }) }) diff --git a/python/src/table.rs b/python/src/table.rs index 63eb45c4e..c97bc6b15 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -2090,7 +2090,7 @@ impl Table { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let current = inner.checkout_current().await.infer_error()?; - Ok(Table::new(current)) + Ok(Self::new(current)) }) } @@ -3256,8 +3256,8 @@ pub enum LanceVersion { impl From for DeltaRef { fn from(version: LanceVersion) -> Self { match version { - LanceVersion::Version(version) => DeltaRef::Version(version), - LanceVersion::Tag(tag) => DeltaRef::Tag(tag), + LanceVersion::Version(version) => Self::Version(version), + LanceVersion::Tag(tag) => Self::Tag(tag), } } } diff --git a/python/uv.lock b/python/uv.lock index 6b1a96c2e..b5c9fb616 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,7 @@ requires-dist = [ { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b25" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b26" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -4301,24 +4301,21 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b25" +version = "15.0.0b26" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, - { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "pyarrow", version = "25.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_2hpc2R/pylance-15.0.0b25-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:2a0bb8d6b0c55b7a821989759fc0f8f62cb4da621f89eae232cef49bb7ef341e" }, - { url = "https://pypi.fury.io/lance-format/-/ver_4LUKQ/pylance-15.0.0b25-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9b73e6e9373c4d5af3fea51e63c3e55873f470aa1a6d0412c22916f88ff5df88" }, - { url = "https://pypi.fury.io/lance-format/-/ver_11CcHk/pylance-15.0.0b25-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8090d403b2a38cd4ac8eb09de0327bc404cb3bc965d905f2b6a8479891273fae" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1S87Ih/pylance-15.0.0b25-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:7f0a20e8ed41d3e49cd5e0bbba97d18ad684cf337e053641321404c9db34f1a1" }, - { url = "https://pypi.fury.io/lance-format/-/ver_13KmLJ/pylance-15.0.0b25-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:079385a6816a10d42f57bc467d9c822c7207cd31d9a6f768bbf522c0a3007229" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1bTDlQ/pylance-15.0.0b25-cp310-abi3-win_amd64.whl", hash = "sha256:d9b1d713b0d03043a3f5596e909405787f85219f54c427b14437367f0ea7acb9" }, - { url = "https://pypi.fury.io/lance-format/-/ver_j7adN/pylance-15.0.0b25-cp310-abi3-win_arm64.whl", hash = "sha256:4a1c18176ffd6a860c6e66b0deb39fcc9ac1434dba57ee66559b7638ad4a200a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2bYWOD/pylance-15.0.0b26-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:bc68ef8edeb6e29f01542f0bfaa7973978f416a8eeec344427b255dd652db13a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_aF5wV/pylance-15.0.0b26-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:27d4f4c18ab682052931e70c4f5d4491288c99c69f465ed806084f40b3924367" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2axp3c/pylance-15.0.0b26-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fb0b9c33f85ff9c52633488b5b696fa1a35036ae899827aceb94212a2ef746df" }, + { url = "https://pypi.fury.io/lance-format/-/ver_oCJRc/pylance-15.0.0b26-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:7c5ca0afb4988206518b1cb801bb1a1a3cc09527828ae51109b2071e549a4486" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1Lg63I/pylance-15.0.0b26-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:32a986146e7b4f2e7b23974bb8718f293939f43f088e5585c38b1ae5b162d46c" }, + { url = "https://pypi.fury.io/lance-format/-/ver_FOT84/pylance-15.0.0b26-cp310-abi3-win_amd64.whl", hash = "sha256:904fd37f8212f00c1affc917b421e4ac4fc051c4c3d3c98cd7adbb33537a3ce3" }, + { url = "https://pypi.fury.io/lance-format/-/ver_A4Kru/pylance-15.0.0b26-cp310-abi3-win_arm64.whl", hash = "sha256:39dbf4b02b3bbaf916b38f1b924da2a534cdb1e32eb8e3f58fb720ef9b92331a" }, ] [[package]] diff --git a/rust/lancedb/src/job/profile.rs b/rust/lancedb/src/job/profile.rs index d8e409948..05cdd9d08 100644 --- a/rust/lancedb/src/job/profile.rs +++ b/rust/lancedb/src/job/profile.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; use crate::error::{Error, Result}; -pub(crate) fn validate_profile_id(profile_id: &str) -> Result<()> { +pub(super) fn validate_profile_id(profile_id: &str) -> Result<()> { if profile_id.is_empty() || profile_id.len() > 256 { return Err(Error::InvalidInput { message: "profile_id must contain between 1 and 256 bytes".into(), From 21f074cb02a682ab883c24dc319c61d6914471c7 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 22 Nov 2026 14:26:38 +0000 Subject: [PATCH 78/78] =?UTF-8?q?Bump=20version:=200.42.0-beta.21=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.22?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 1f88ee40e..5a9826d7b 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.21" +current_version = "0.42.0-beta.22" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 863e60d6e..827baf266 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6005,7 +6005,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.21" +version = "0.42.0-beta.22" dependencies = [ "ahash", "anyhow", @@ -6116,7 +6116,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.21" +version = "0.42.0-beta.22" dependencies = [ "anyhow", "arrow-array", @@ -6159,7 +6159,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.21" +version = "0.42.0-beta.22" dependencies = [ "arrow-array", "arrow-buffer", @@ -6185,7 +6185,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.21" +version = "0.42.0-beta.22" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 237f00cde..86faf0a61 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.21 + 0.42.0-beta.22 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index e8b214d9f..59a9179bb 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.20 + 0.42.0-beta.22 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index cd245e179..83b707a25 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.20 + 0.42.0-beta.22 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 1c5033c73..b32c683a5 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.21" +version = "0.42.0-beta.22" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index b528fc57d..dd7e563e1 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.21", + "version": "0.42.0-beta.22", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index a69f8e6c3..d9aa4fc34 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.21", + "version": "0.42.0-beta.22", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 6b97d7e5d..ebe6345fb 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.21", + "version": "0.42.0-beta.22", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index f7591e824..3f921c91a 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.21", + "version": "0.42.0-beta.22", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index 2e6abc68a..217ae7e36 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.21", + "version": "0.42.0-beta.22", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index ebf2cd55b..ddffdf695 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.21", + "version": "0.42.0-beta.22", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 8b89322e0..6f71ba0e6 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.21", + "version": "0.42.0-beta.22", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 8dd8fcb52..91d833236 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.21", + "version": "0.42.0-beta.22", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 23da1099c..2c9458112 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.21" +version = "0.42.0-beta.22" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 371b41beb..272c9af52 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.21" +version = "0.42.0-beta.22" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 534b2b570..6dc6bea71 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.21" +version = "0.42.0-beta.22" edition = "2021" license.workspace = true repository.workspace = true