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:
Jack Ye
2026-11-21 15:04:34 -08:00
committed by GitHub
parent e3e55844bc
commit 2b1b2a29dd
50 changed files with 2110 additions and 946 deletions
+28 -1
View File
@@ -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 () => {
+29 -58
View File
@@ -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}',
),
]);
});
+3 -2
View File
@@ -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: {
+35
View File
@@ -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));
}
-1
View File
@@ -60,7 +60,6 @@ export {
FunctionRefreshPlanningConfig,
FunctionRefreshPodResources,
FunctionRetryPolicy,
FunctionWorkerResourceBudget,
RefreshColumnResult,
FunctionErrors,
FunctionErrorsOptions,
+28
View File
@@ -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
View File
@@ -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> {
+45
View File
@@ -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
View File
@@ -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 {