mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
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.
This commit is contained in:
@@ -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`
|
||||
|
||||
@@ -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)>
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
<CodeGroup>
|
||||
```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.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
<CodeGroup>
|
||||
```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?;
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
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}
|
||||
|
||||
|
||||
@@ -333,7 +333,7 @@ too slow or too expensive:
|
||||
<CodeGroup>
|
||||
```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)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
@@ -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:
|
||||
|
||||
<CodeGroup>
|
||||
```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();
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
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`.
|
||||
|
||||
<CodeGroup>
|
||||
```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(
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
`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.
|
||||
|
||||
<Note>
|
||||
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.
|
||||
</Note>
|
||||
|
||||
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}
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
<CodeGroup>
|
||||
```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,
|
||||
});
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
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}
|
||||
|
||||
@@ -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 |
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
|
||||
@@ -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 |
|
||||
|
||||
|
||||
@@ -155,3 +155,23 @@ same underlying job as dropping any table, `drop_table` or `drop_object`.
|
||||
How a refresh works, in LanceDB Enterprise.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
### 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);
|
||||
```
|
||||
|
||||
@@ -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.
|
||||
<CodeGroup>
|
||||
```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)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
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
|
||||
|
||||
@@ -14,8 +14,8 @@ A LanceDB extension with no DataFusion equivalent.
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
REFRESH MATERIALIZED VIEW <name>
|
||||
[WITH (full = <boolean>, cpu_millis = <integer>, memory_bytes = <integer>,
|
||||
gpu_count = <integer>, gpu_class = '<class>')]
|
||||
[WITH (full = <boolean>, total_cpu_millis = <integer>, total_memory_bytes = <integer>,
|
||||
total_gpu_count = <integer>, gpu_class = '<class>')]
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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}',
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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<MaterializedView>;
|
||||
|
||||
@@ -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<MaterializedView> {
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -60,7 +60,6 @@ export {
|
||||
FunctionRefreshPlanningConfig,
|
||||
FunctionRefreshPodResources,
|
||||
FunctionRetryPolicy,
|
||||
FunctionWorkerResourceBudget,
|
||||
RefreshColumnResult,
|
||||
FunctionErrors,
|
||||
FunctionErrorsOptions,
|
||||
|
||||
@@ -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<RefreshMaterializedViewResult> {
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+28
-20
@@ -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<RefreshMaterializedViewResult>;
|
||||
|
||||
/** @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<RefreshMaterializedViewResult> {
|
||||
return await this.inner.refreshMaterializedView(sourceVersion, full);
|
||||
return await this.inner.refreshMaterializedView(
|
||||
sourceVersion,
|
||||
full,
|
||||
totalCpuMillis,
|
||||
totalMemoryBytes,
|
||||
totalGpuCount,
|
||||
gpuClass,
|
||||
gpuCount,
|
||||
);
|
||||
}
|
||||
|
||||
async materializedViewDefinition(): Promise<string> {
|
||||
|
||||
@@ -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<String>,
|
||||
limit: Option<i64>,
|
||||
with_no_data: bool,
|
||||
total_cpu_millis: Option<f64>,
|
||||
total_memory_bytes: Option<f64>,
|
||||
total_gpu_count: Option<f64>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<f64>,
|
||||
) -> napi::Result<Table> {
|
||||
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()))
|
||||
|
||||
+62
-45
@@ -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<i64>,
|
||||
full: Option<bool>,
|
||||
total_cpu_millis: Option<f64>,
|
||||
total_memory_bytes: Option<f64>,
|
||||
total_gpu_count: Option<f64>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<f64>,
|
||||
) -> napi::Result<RefreshMaterializedViewResult> {
|
||||
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<String>,
|
||||
}
|
||||
|
||||
/// 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<f64>,
|
||||
}
|
||||
|
||||
/// 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<u64> {
|
||||
Ok(value as u64)
|
||||
}
|
||||
|
||||
fn resource_budget_gpu_count(value: Option<f64>) -> napi::Result<u32> {
|
||||
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<f64>, name: &str) -> napi::Result<Option<u32>> {
|
||||
value
|
||||
.map(|value| {
|
||||
@@ -2020,8 +2025,7 @@ fn positive_u32(value: Option<f64>, name: &str) -> napi::Result<Option<u32>> {
|
||||
|
||||
/// 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<f64>,
|
||||
/// GPU class for Function workers.
|
||||
pub gpu_class: Option<String>,
|
||||
/// Complete aggregate CPU and memory budget for a registered Function
|
||||
/// refresh. `gpuCount` inside the budget defaults to zero.
|
||||
pub resource_budget: Option<FunctionWorkerResourceBudget>,
|
||||
/// Positive GPU count allocated to each Function worker.
|
||||
pub gpu_count: Option<f64>,
|
||||
/// Override the total CPU budget in millicores for this refresh.
|
||||
pub total_cpu_millis: Option<f64>,
|
||||
/// Override the total memory budget in bytes for this refresh.
|
||||
pub total_memory_bytes: Option<f64>,
|
||||
/// CPU, memory, and ephemeral-storage limits for the refresh supervisor.
|
||||
pub supervisor_resources: Option<FunctionRefreshPodResources>,
|
||||
/// Resources and sizing for the refresh planning fleet.
|
||||
pub planning_workers: Option<FunctionRefreshPlanningConfig>,
|
||||
/// Positive aggregate GPU budget for Function workers.
|
||||
pub gpu_count: Option<u32>,
|
||||
/// Nonnegative total GPU budget for Function workers.
|
||||
pub total_gpu_count: Option<f64>,
|
||||
/// Override retries of failed user-code calls for this refresh.
|
||||
pub retry_policy: Option<FunctionRetryPolicy>,
|
||||
/// `"fail"` (default) stops on a row error; `"skip"` writes null and
|
||||
@@ -2083,17 +2090,14 @@ impl TryFrom<RefreshColumnOptions> 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<RefreshColumnOptions> 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 {
|
||||
|
||||
@@ -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: ...
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
+153
-87
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"):
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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}]
|
||||
|
||||
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -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<bool>,
|
||||
auto_refresh_interval_seconds: Option<f64>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
total_memory_bytes: Option<u64>,
|
||||
total_gpu_count: Option<u32>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<u32>,
|
||||
|
||||
query: Option<String>,
|
||||
exist_ok: bool,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
@@ -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<bool>,
|
||||
auto_refresh_interval_seconds: Option<f64>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
total_memory_bytes: Option<u64>,
|
||||
total_gpu_count: Option<u32>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<u32>,
|
||||
|
||||
query: Option<String>,
|
||||
exist_ok: bool,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
+86
-112
@@ -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<i64>,
|
||||
max_concurrency: Option<u32>,
|
||||
publication_interval_rows: Option<i64>,
|
||||
resource_budget: Option<FunctionWorkerResourceBudget>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
total_memory_bytes: Option<u64>,
|
||||
supervisor_resources: Option<FunctionRefreshPodResources>,
|
||||
planning_workers: Option<FunctionRefreshPlanningConfig>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<i64>,
|
||||
gpu_count: Option<u32>,
|
||||
total_gpu_count: Option<i64>,
|
||||
retry_policy: Option<String>,
|
||||
error_policy: Option<String>,
|
||||
max_failed_fraction: Option<f64>,
|
||||
@@ -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<u64> {
|
||||
if value.is_none() || value.is_instance_of::<PyBool>() {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"resource_budget.{name} must be an integer"
|
||||
)));
|
||||
}
|
||||
let parsed = value
|
||||
.extract::<u64>()
|
||||
.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<Option<FunctionWorkerResourceBudget>> {
|
||||
let Some(budget) = budget else {
|
||||
return Ok(None);
|
||||
};
|
||||
for key in budget.keys() {
|
||||
let key = key
|
||||
.extract::<String>()
|
||||
.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<u64> {
|
||||
if value.is_none() || value.is_instance_of::<PyBool>() {
|
||||
return Err(PyValueError::new_err(format!("{name} must be an integer")));
|
||||
@@ -275,11 +218,13 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOpti
|
||||
batch_size,
|
||||
max_concurrency,
|
||||
publication_interval_rows,
|
||||
resource_budget,
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
supervisor_resources,
|
||||
planning_workers,
|
||||
gpu_class,
|
||||
gpu_count,
|
||||
total_gpu_count,
|
||||
retry_policy,
|
||||
error_policy,
|
||||
max_failed_fraction,
|
||||
@@ -333,20 +278,19 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOpti
|
||||
options.max_concurrency = max_concurrency;
|
||||
options.publication_interval_rows =
|
||||
positive_count(publication_interval_rows, "publication_interval_rows")?;
|
||||
options.resource_budget = resource_budget;
|
||||
options.total_cpu_millis = total_cpu_millis;
|
||||
options.total_memory_bytes = total_memory_bytes;
|
||||
options.supervisor_resources = supervisor_resources;
|
||||
options.planning_workers = planning_workers;
|
||||
options.gpu_class = gpu_class;
|
||||
options.gpu_count = gpu_count
|
||||
options.gpu_count = gpu_count;
|
||||
options.total_gpu_count = total_gpu_count
|
||||
.map(|count| {
|
||||
u32::try_from(count)
|
||||
.ok()
|
||||
.filter(|count| *count > 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<bool>,
|
||||
auto_refresh_interval_seconds: Option<u64>,
|
||||
auto_refresh_resource_budget: Option<Bound<'py, PyDict>>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
total_memory_bytes: Option<u64>,
|
||||
total_gpu_count: Option<u32>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<u32>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
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<String>,
|
||||
auto_refresh_enabled: Option<bool>,
|
||||
auto_refresh_interval_seconds: Option<u64>,
|
||||
auto_refresh_resource_budget: Option<Bound<'py, PyDict>>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
total_memory_bytes: Option<u64>,
|
||||
total_gpu_count: Option<u32>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<u32>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
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<i64>,
|
||||
max_concurrency: Option<Bound<'py, PyAny>>,
|
||||
publication_interval_rows: Option<i64>,
|
||||
resource_budget: Option<Bound<'py, PyDict>>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
total_memory_bytes: Option<u64>,
|
||||
supervisor_resources: Option<Bound<'py, PyDict>>,
|
||||
planning_workers: Option<Bound<'py, PyDict>>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<i64>,
|
||||
gpu_count: Option<u32>,
|
||||
total_gpu_count: Option<i64>,
|
||||
retry_policy: Option<String>,
|
||||
error_policy: Option<String>,
|
||||
max_failed_fraction: Option<f64>,
|
||||
@@ -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<i64>,
|
||||
max_concurrency: Option<Bound<'py, PyAny>>,
|
||||
publication_interval_rows: Option<i64>,
|
||||
resource_budget: Option<Bound<'py, PyDict>>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
total_memory_bytes: Option<u64>,
|
||||
supervisor_resources: Option<Bound<'py, PyDict>>,
|
||||
planning_workers: Option<Bound<'py, PyDict>>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<i64>,
|
||||
gpu_count: Option<u32>,
|
||||
total_gpu_count: Option<i64>,
|
||||
retry_policy: Option<String>,
|
||||
error_policy: Option<String>,
|
||||
max_failed_fraction: Option<f64>,
|
||||
@@ -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<u64>,
|
||||
full: bool,
|
||||
cpu_millis: Option<u64>,
|
||||
memory_bytes: Option<u64>,
|
||||
gpu_count: Option<u32>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
total_memory_bytes: Option<u64>,
|
||||
total_gpu_count: Option<u32>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<u32>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
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<u64>,
|
||||
full: bool,
|
||||
cpu_millis: Option<u64>,
|
||||
memory_bytes: Option<u64>,
|
||||
gpu_count: Option<u32>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
total_memory_bytes: Option<u64>,
|
||||
total_gpu_count: Option<u32>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<u32>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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<String, String>,
|
||||
/// Operator-defined GPU class; absent uses the deployment default.
|
||||
/// Operator-defined GPU class; absent accepts any eligible configured class.
|
||||
gpu_class: Option<String>,
|
||||
/// GPUs allocated together to each worker.
|
||||
gpus_per_worker: Option<std::num::NonZeroU32>,
|
||||
},
|
||||
/// 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<Value>,
|
||||
python_version: String,
|
||||
environment: PythonEnvironmentSpec,
|
||||
#[serde(default)]
|
||||
@@ -388,6 +404,8 @@ struct PythonRuntimeV1Wire {
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PythonRuntimeV2Wire {
|
||||
#[serde(default)]
|
||||
gpus_per_worker: Option<std::num::NonZeroU32>,
|
||||
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<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
gpu_class: Option<&'a str>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
gpus_per_worker: Option<std::num::NonZeroU32>,
|
||||
}
|
||||
|
||||
#[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<u32>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "deserialize_total_cpu_millis"
|
||||
)]
|
||||
total_cpu_millis: Option<u64>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "deserialize_total_memory_bytes"
|
||||
)]
|
||||
total_memory_bytes: Option<u64>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "deserialize_total_gpu_count"
|
||||
)]
|
||||
total_gpu_count: Option<u32>,
|
||||
/// Per-call deadline in seconds.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
row_timeout_seconds: Option<RowTimeoutSeconds>,
|
||||
@@ -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<u64> {
|
||||
self.total_cpu_millis
|
||||
}
|
||||
|
||||
/// Default total memory budget for executions of this pinned Function.
|
||||
pub fn total_memory_bytes(&self) -> Option<u64> {
|
||||
self.total_memory_bytes
|
||||
}
|
||||
|
||||
/// Default aggregate GPU budget, independent of the per-worker device count.
|
||||
pub fn total_gpu_count(&self) -> Option<u32> {
|
||||
self.total_gpu_count
|
||||
}
|
||||
|
||||
/// Default maximum rows in one callable batch, when declared.
|
||||
pub fn batch_size(&self) -> Option<u32> {
|
||||
self.batch_size
|
||||
@@ -900,6 +962,44 @@ where
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn deserialize_total_cpu_millis<'de, D>(
|
||||
deserializer: D,
|
||||
) -> std::result::Result<Option<u64>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let value = Option::<u64>::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<Option<u64>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let value = Option::<u64>::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<Option<u32>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Option::<u32>::deserialize(deserializer)
|
||||
.map_err(|error| de::Error::custom(format!("total_gpu_count: {error}")))
|
||||
}
|
||||
|
||||
fn deserialize_max_concurrency<'de, D>(
|
||||
deserializer: D,
|
||||
) -> std::result::Result<Option<u32>, D::Error>
|
||||
@@ -970,6 +1070,27 @@ pub struct FunctionRegistrationRequest {
|
||||
deserialize_with = "deserialize_max_concurrency"
|
||||
)]
|
||||
pub max_concurrency: Option<u32>,
|
||||
/// 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<u64>,
|
||||
/// 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<u64>,
|
||||
/// 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<u32>,
|
||||
/// 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::<Value>(&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::<PythonRuntimeSpec>(value).is_err());
|
||||
}
|
||||
|
||||
for invalid in [
|
||||
r#"{"kind":"python","python_version":"3.12","environment":{"kind":"pip"},"gpu":true}"#,
|
||||
|
||||
@@ -301,6 +301,11 @@ pub struct CreateMaterializedViewRequest {
|
||||
pub auto_refresh_enabled: Option<bool>,
|
||||
/// Refresh interval in seconds. When absent, the server determines when to refresh.
|
||||
pub auto_refresh_interval_seconds: Option<f64>,
|
||||
pub total_cpu_millis: Option<u64>,
|
||||
pub total_memory_bytes: Option<u64>,
|
||||
pub total_gpu_count: Option<u32>,
|
||||
pub gpu_class: Option<String>,
|
||||
pub gpu_count: Option<u32>,
|
||||
}
|
||||
|
||||
/// 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<bool>,
|
||||
auto_refresh_interval_seconds: Option<f64>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
total_memory_bytes: Option<u64>,
|
||||
total_gpu_count: Option<u32>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<u32>,
|
||||
}
|
||||
|
||||
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<String>) -> 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<u64>,
|
||||
pub memory_bytes: Option<u64>,
|
||||
pub gpu_count: Option<u32>,
|
||||
pub total_cpu_millis: Option<u64>,
|
||||
pub total_memory_bytes: Option<u64>,
|
||||
pub total_gpu_count: Option<u32>,
|
||||
pub gpu_class: Option<String>,
|
||||
pub gpu_count: Option<u32>,
|
||||
}
|
||||
|
||||
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<String>) -> 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!(
|
||||
|
||||
@@ -823,6 +823,33 @@ impl<S: HttpSend> Database for RemoteDatabase<S> {
|
||||
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![],
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -4490,8 +4490,20 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
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<u32>,
|
||||
#[case] total_gpu_count: Option<u32>,
|
||||
#[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
|
||||
|
||||
@@ -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(())
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<u64>,
|
||||
/// 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<FunctionWorkerResourceBudget>,
|
||||
pub total_cpu_millis: Option<u64>,
|
||||
/// Default total memory budget in bytes for manual and automatic refreshes.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub total_memory_bytes: Option<u64>,
|
||||
/// Default total GPU budget for manual and automatic refreshes.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub total_gpu_count: Option<u32>,
|
||||
/// GPU pool used by each Function worker unless overridden at refresh.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub gpu_class: Option<String>,
|
||||
/// Positive number of GPUs per worker, independent of the total budget.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub gpu_count: Option<u32>,
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
@@ -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<u32>,
|
||||
/// 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<u64>,
|
||||
/// 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<FunctionWorkerResourceBudget>,
|
||||
pub total_cpu_millis: Option<u64>,
|
||||
/// Total memory budget for this execution, in bytes.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub total_memory_bytes: Option<u64>,
|
||||
/// 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<String>,
|
||||
/// 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<u32>,
|
||||
/// 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<u32>,
|
||||
}
|
||||
|
||||
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()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)),
|
||||
] {
|
||||
|
||||
Reference in New Issue
Block a user