mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat(functions): declare multiple bindings in one add_columns call (#5202)
Allow Python callers to pass several registered Function applications to `add_columns`. Rust callers can use `function_bindings` to submit the same atomic declaration. An application can consume another output in the mapping, including one declared later. The SDK checks the Enterprise server's batch-declaration capability before sending the mutation. Single-binding callers continue to use the existing request shape. This change covers declaration only. Coverage includes Python mapping validation, the Rust HTTP request with dependent bindings, and older servers with missing or unknown capability values. Correctness tests run in CI.
This commit is contained in:
@@ -775,8 +775,7 @@ class Table:
|
||||
) -> AddColumnsResult: ...
|
||||
async def add_function_columns(
|
||||
self,
|
||||
application_json: str,
|
||||
output_name: Optional[str],
|
||||
bindings: list[tuple[str, Optional[str]]],
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[int] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
|
||||
@@ -3480,10 +3480,11 @@ class Table(ABC):
|
||||
new columns with the specified data types. The new columns will
|
||||
be initialized with null values.
|
||||
|
||||
A mapping with one ``FunctionApplication`` value keeps its scalar
|
||||
or named-struct result in the named table column. A bare
|
||||
named-struct application expands its ordered result fields as one
|
||||
atomic binding; aliases come from ``rename(columns=...)``.
|
||||
A mapping of column names to ``FunctionApplication`` values declares
|
||||
all bindings in one schema commit. Each column holds its scalar
|
||||
or entire named-struct result. A bare named-struct application expands
|
||||
its ordered result fields as one atomic binding. Set field aliases
|
||||
with ``rename(columns=...)``.
|
||||
Function columns are supported only in LanceDB
|
||||
Enterprise.
|
||||
|
||||
@@ -9110,10 +9111,11 @@ class AsyncTable:
|
||||
Alternatively, you can pass a pyarrow field or schema to add
|
||||
new columns with NULLs.
|
||||
|
||||
A mapping with one ``FunctionApplication`` value keeps its scalar
|
||||
or named-struct result in the named table column. A bare
|
||||
named-struct application expands its ordered result fields as one
|
||||
atomic binding; aliases come from ``rename(columns=...)``.
|
||||
A mapping of column names to ``FunctionApplication`` values declares
|
||||
all bindings in one schema commit. Each column holds its scalar
|
||||
or entire named-struct result. A bare named-struct application expands
|
||||
its ordered result fields as one atomic binding. Set field aliases
|
||||
with ``rename(columns=...)``.
|
||||
Function columns are supported only in LanceDB
|
||||
Enterprise.
|
||||
|
||||
@@ -9207,31 +9209,30 @@ class AsyncTable:
|
||||
or gpu_class is not None
|
||||
or gpu_count is not None
|
||||
)
|
||||
function_application = None
|
||||
function_output_name = None
|
||||
bindings: list[tuple[FunctionApplication, str | None]] = []
|
||||
if isinstance(transforms, FunctionApplication):
|
||||
function_application = transforms
|
||||
bindings.append((transforms, None))
|
||||
elif isinstance(transforms, Mapping) and any(
|
||||
isinstance(value, FunctionApplication) for value in transforms.values()
|
||||
):
|
||||
if len(transforms) != 1 or not all(
|
||||
isinstance(value, FunctionApplication) for value in transforms.values()
|
||||
):
|
||||
raise ValueError(
|
||||
"one add_columns call declares exactly one Function binding"
|
||||
)
|
||||
function_output_name, function_application = next(iter(transforms.items()))
|
||||
for name, application in transforms.items():
|
||||
if not isinstance(application, FunctionApplication):
|
||||
raise ValueError(
|
||||
"add_columns cannot mix Function applications and SQL "
|
||||
"expressions"
|
||||
)
|
||||
bindings.append((application, name))
|
||||
|
||||
if function_application is not None:
|
||||
if bindings:
|
||||
if computed:
|
||||
raise ValueError(
|
||||
"add_columns cannot mix a Function application with SQL "
|
||||
"computed columns"
|
||||
)
|
||||
function_application._ensure_declarable()
|
||||
for application, _ in bindings:
|
||||
application._ensure_declarable()
|
||||
return await self._inner.add_function_columns(
|
||||
function_application.to_canonical_json(),
|
||||
function_output_name,
|
||||
[(app.to_canonical_json(), name) for app, name in bindings],
|
||||
auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds,
|
||||
total_cpu_millis,
|
||||
|
||||
@@ -611,8 +611,7 @@ class _FunctionDeclarationInner:
|
||||
|
||||
async def add_function_columns(
|
||||
self,
|
||||
application_json,
|
||||
output_name,
|
||||
bindings,
|
||||
auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds,
|
||||
total_cpu_millis,
|
||||
@@ -623,8 +622,7 @@ class _FunctionDeclarationInner:
|
||||
):
|
||||
self.calls.append(
|
||||
(
|
||||
json.loads(application_json),
|
||||
output_name,
|
||||
[(json.loads(app), name) for app, name in bindings],
|
||||
auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds,
|
||||
total_cpu_millis,
|
||||
@@ -654,8 +652,9 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
|
||||
mapping_type({"features": application._copy(update={"columns": {}})})
|
||||
)
|
||||
assert result == "declared"
|
||||
assert inner.calls[-1][1] == "features"
|
||||
assert inner.calls[-1][2:] == (None, None, None, None, None)
|
||||
[(_, name)], *options = inner.calls[-1]
|
||||
assert name == "features"
|
||||
assert options == [None, None, None, None, None]
|
||||
|
||||
bare = application._copy(update={"columns": {}}).rename(
|
||||
columns={"normalized_text": "search_text"}
|
||||
@@ -668,19 +667,30 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
|
||||
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, 8000, None, 0)
|
||||
[(payload, name)], *options = inner.calls[-1]
|
||||
assert name is None
|
||||
assert payload["columns"] == {"normalized_text": "search_text"}
|
||||
assert options == [False, 300, 8000, None, 0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_columns_rejects_multiple_bindings_and_unknown_newer_application():
|
||||
async def test_add_columns_routes_multiple_bindings_in_one_call():
|
||||
inner = _FunctionDeclarationInner()
|
||||
table = AsyncTable(inner)
|
||||
application = known_application()._copy(update={"columns": {}})
|
||||
assert await table.add_columns({"a": application, "b": application}) == "declared"
|
||||
assert len(inner.calls) == 1
|
||||
assert [name for _, name in inner.calls[0][0]] == ["a", "b"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_columns_rejects_mixed_bindings_and_unknown_newer_application():
|
||||
inner = _FunctionDeclarationInner()
|
||||
table = AsyncTable(inner)
|
||||
application = known_application()
|
||||
|
||||
with pytest.raises(ValueError, match="exactly one Function binding"):
|
||||
await table.add_columns({"a": application, "b": application})
|
||||
with pytest.raises(ValueError, match="cannot mix Function applications"):
|
||||
await table.add_columns({"a": application, "b": "1+1"})
|
||||
|
||||
future = json.loads(fixture("remote_function_application.json"))
|
||||
application = FunctionApplication(**future)
|
||||
|
||||
+14
-10
@@ -2708,12 +2708,11 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
#[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))]
|
||||
#[pyo3(signature = (bindings, 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>,
|
||||
bindings: Vec<(String, Option<String>)>,
|
||||
auto_refresh_enabled: Option<bool>,
|
||||
auto_refresh_interval_seconds: Option<u64>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
@@ -2722,8 +2721,15 @@ impl Table {
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<u32>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let application =
|
||||
lancedb::function::FunctionApplication::from_json(&application_json).infer_error()?;
|
||||
let bindings = bindings
|
||||
.into_iter()
|
||||
.map(|(json, name)| {
|
||||
Ok((
|
||||
lancedb::function::FunctionApplication::from_json(&json).infer_error()?,
|
||||
name,
|
||||
))
|
||||
})
|
||||
.collect::<PyResult<Vec<_>>>()?;
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let options = ComputedColumnOptions {
|
||||
auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true),
|
||||
@@ -2736,11 +2742,9 @@ impl Table {
|
||||
};
|
||||
options.validate().infer_error()?;
|
||||
future_into_py(self_.py(), async move {
|
||||
let builder = match output_name {
|
||||
Some(name) => inner.add_columns().function_as(name, application),
|
||||
None => inner.add_columns().function(application),
|
||||
};
|
||||
let result = builder
|
||||
let result = inner
|
||||
.add_columns()
|
||||
.function_bindings(bindings)
|
||||
.computed_options(options)
|
||||
.execute()
|
||||
.await
|
||||
|
||||
Reference in New Issue
Block a user