Enterprise only
Use a SQL expression for a value derived from existing columns when SQL can
express the calculation. Use a Python Function for models, media decoding,
external services, or other code that SQL cannot express. Both declare stored
columns that a refresh fills.
For a Function that calls an external service, follow the
Python Secrets walkthrough to create a
credential, grant access, fill a column, and alter the Secret value.
Use the Function signature matrix
before choosing input/output schemas. The Function type grammar is narrower
than a table’s Arrow schema: it names scalar primitives, lists, structs, maps
and decimals, and a timestamp or duration declares its unit (plus an optional
timezone for a timestamp) through the SQL spelling or exact Arrow JSON. See
timestamp and duration values and
map and decimal values. Blob v2 can be
top-level or nested in a struct; list/large-list Blob values are output-only on
matching releases, and row-ID fetch helpers do not fetch Blob payloads inside
lists.
For module-level OUT_TYPE or other constants, see
supported global captures. Scalar literals and
nested tuples can be captured; Arrow schemas/types, mutable containers and
NumPy arrays must be constructed inside the Function body or a class’s
__init__. Decorator schema arguments are handled separately as the signature.
The improved unsupported-global error is not additional serialization support.
Model placement, query-time initialization and refresh queue behavior are
covered in Function operations. Functions
can load models once per instance, but a cached image does not guarantee an
initialized model for the next SQL query. For interactive search, prefer an
already initialized query-embedding model.
Prefer SQL for expressions over existing columns
Arithmetic, comparisons, casts, and built-in SQL functions do not need a registered Python Function. SQL computed columns avoid the Python environment and Function worker overhead. See the available SQL functions. For an existing Enterprise table with an integervalue column:
computed= saves the expression and declares an empty column. This example
disables automatic refresh so that the explicit refresh_column_async job fills it.
Automatic refresh is enabled by default where the deployment supports it.
To compute existing rows immediately in one call, use an eager SQL transform
instead:
computed= declaration
retains the expression for later refreshes. See
Create a computed column and
Refresh a column.
Declare Function bindings
These declarations apply to ordinary tables. A materialized view’s definingSELECT owns its schema; put the Function call in that query, compute it on
the source table first, or create an independent ordinary table. Do not attach
a separate Function binding to the view with view.table.add_columns(...).
See materialized-view alternatives.
A Function binding applies one registered Function version to its inputs.
With a Python SDK and Enterprise server that support batch declaration, pass
several applications in one mapping. The table gains every binding in one
schema version. If any application is invalid, the whole declaration fails.
computed= mapping
for SQL-expression columns.
One binding can still produce several output columns: return a named struct
from one Function and pass its application directly to add_columns to expand
the fields. See the
multi-output Function example. Function columns
start empty and need a refresh, just like SQL computed columns.
Reuse stored Function results in SQL
Available in the next server release.
NULL results are reused too. Rows with missing or stale
results are computed during the query.
EXPLAIN includes stored_rows and computed_rows for the pinned table
snapshot. For 800 current rows and 10 newly appended rows, these counts are
800 and 10. Filters and limits can reduce the work performed during execution;
the counts describe the snapshot’s reuse eligibility. Query-time computation
does not fill the stored column; use a column refresh to persist those results.
Calls with different inputs or initialization values, bindings that store only
selected result fields, Secret-dependent Functions, and Functions with side
effects continue to compute their results. Reuse currently applies to direct
table reads and column projections or aliases; WAL-backed reads retain their
existing execution behavior.
Preview UDFs with per-row error handling
A UDF error fails its query by default. Submit a distributed job witherror_policy = 'skip' to keep successful results and return NULL for each
failing scalar UDF input:
SUBMIT JOB returns a job ID immediately. EXECUTE JOB 'job-id' waits for that
job and reads its saved result. To submit and wait in one statement, use:
ON clause, the job uses the deployment’s configured SQL job
compute. CPU or GPU job execution must be enabled for the UDF’s compute class.
Named clusters and compute integrations retain their existing placement options
and native CPU query restrictions.
Put the policy before AS; it applies to UDF calls in the job’s projection,
filters, aggregates, CTEs, and subqueries. NULLs follow normal SQL semantics:
COUNT(fn(x)) counts successful non-NULL results, and a NULL filter condition
excludes the row. A failing UDTF input produces no output rows. Worker startup,
transport, and other statement-level failures still fail the job.
The default is error_policy = 'fail'. Unknown and duplicate job options are
rejected. The policy and UDF versions are saved with the job, so worker
replanning and result retrieval use the submitted execution contract. These
query jobs do not persist skipped-row diagnostics for SHOW ERRORS;
materialized view refresh and computed column refresh manage their own error
records.
Return struct values by field name
A struct output keeps the named-struct pattern: each field declares its own nullability and the struct column itself is non-nullable. A single value can also be a nullable scalar; see nullable scalar outputs. See the type matrix and the failure-handling workflow. For a struct output, return a Python dictionary with exactly the declared field names. This also applies to structs nested inside structs or lists. For example, an output declared asstruct<precision: float64, recall: float64> accepts:
(0.9, 0.1) and lists of field-value pairs
are rejected. Convert a named tuple with _asdict() or a dataclass instance
with dataclasses.asdict() before returning it.
Vectorized Functions can return a sequence of dictionaries, one per input row,
or a typed Arrow array or RecordBatch matching the declared output schema.
Typed Arrow struct scalars are also accepted as row values. None is accepted
where the declared output is nullable. Tuples remain supported for list-valued
outputs.
Declare a nullable scalar output
A scalar output declares its nullability explicitly. Python uses a nullable annotation such as-> float | None or pa.field("$value", pa.float64(), nullable=True); SQL appends NULL to RETURNS <type>. A returned None then
becomes a computed NULL that the refresh assigns, so SHOW COLUMN STATUS
reports the row as fresh. A row that has not been refreshed, was deferred
because a required input was null, or was skipped by error_policy = 'skip'
stays unassigned. Leaving the declaration out keeps the non-nullable contract,
where a NULL return is a row error instead of a value.
Declare map and decimal values
The Python declaration forms below require the SDK support introduced in lancedb/lancedb#5031. The SDK revision currently pinned by this server does not include that support; use the SQL declaration forms until an SDK package containing it is available. Maps use canonical Arrow map JSON; Python declarations useentries, key,
and value child names, while explicit Arrow schemas may preserve custom child
names. The key must be non-null utf8; the value field keeps its declared
nullability. For example, map<utf8, int64> in SQL produces a map whose value is
nullable. The SDK preserves the value nullability from dict[str, T] and
dict[str, Optional[T]].
keys_sorted=true and Blob v2 nested inside a map are not supported.
Decimals require an explicit precision and scale. SQL accepts
decimal128(precision, scale) and decimal256(precision, scale) (and
decimal(...) as a decimal128 spelling); the SDK uses an explicit
pa.decimal128/pa.decimal256 schema or an Annotated[Decimal, ...] type.
Canonical Arrow JSON encodes the pair as length = precision * 1000 + scale,
including negative scales. A bare Decimal annotation is not a valid
declaration.
Declare timestamp and duration values
A timestamp carries a unit and optionally a timezone; a duration carries a unit. The bare names are the legacy microsecond, no-timezone spellings. SQL uses the existing Lance precision spellingtimestamp(0|3|6|9) for seconds,
milliseconds, microseconds, and nanoseconds, and accepts bare timestamp and
duration:
NULL modifier makes the returned None an assigned value rather than a
row error; see nullable scalar outputs.
An explicit timezone, or a duration unit other than microseconds, has no SQL
spelling. Declare it with exact Arrow JSON through the SDK’s explicit
output_schema/Annotated form or a registration request:
-
means no timezone. The declared unit is part of the type: a nanosecond column
is not coerced to microseconds, and a unit or timezone mismatch is rejected at
binding rather than converted. SQL rejects timestamp(<precision>, '<tz>')
and duration(<unit>) instead of guessing either parameter.
Read a field from a Function result in SQL
For a registered Functionego_activity_label that returns a struct with an
activity field, select that field directly:
models.ego_activity_label(embedding).activity.
Bracket access and get_field also work without a CTE:
ego_activity_label(embedding)."Activity Label".
Stream a Blob v2 output with BlobWriter
Use BlobWriter when a Function can produce a large value in chunks. The
LanceDB Python SDK declares the output and a compatible Enterprise server
provides the writer during computed column refresh.
write(data=...) accepts bytes-like data and returns
its accepted byte count. Leaving the context normally seals the value, including
an empty Blob. Leaving it with an exception aborts the write. Return the sealed
writer once, from the same Function invocation.
Use BlobWriter.field("preview") in the Function’s output_schema to mark
an output field within a named result, including a list or large-list item.
A marked field also accepts ordinary bytes and accepts None when nullable.
A Function with a writer-capable result schema runs through computed column
refresh. Use REFRESH COLUMN in SQL to materialize it. An ordinary bytes
result declared with lancedb.blob(...) can also be used in SELECT.
Read the byte size of a Blob in SQL
UseBYTE_LENGTH for binary and Blob values:
LENGTH,
OCTET_LENGTH, and BIT_LENGTH do not accept Blob descriptors; use
BYTE_LENGTH(mp4). A descriptor’s mp4.size field exposes its stored size,
which can be unknown for an external Blob reference. BYTE_LENGTH resolves
unknown external sizes for stored Blob columns.
Allocate multiple GPUs to one Function worker
Use@function(gpu=True, gpu_class="h100", gpu_count=2) to allocate two
GPUs together to each Function worker. SQL registration uses
CREATE FUNCTION ... WITH (gpu = true, gpu_class = 'h100', gpu_count = 2).
gpu_count defaults to one. Omitting gpu_class is equivalent to
gpu_class="any": either accepts any eligible configured pool. Set
gpu_class="default" to select the deployment’s default pool explicitly.
Omit gpu or set gpu=False for CPU execution; gpu_class and gpu_count
require gpu=True.
Class names identify operator-configured pools and must be lowercase. For an
any request, selection uses configured per-worker limits and stays fixed for
the worker cohort. An any Function may share a SQL job with a Function pinned
to a class; the job uses that class and the largest required GPU count.
Configure the model’s tensor parallelism separately.
Inspect the deployment with db.list_gpu_classes() or SHOW GPU CLASSES.
These report the configured model, memory per GPU, and
max_gpu_count_per_worker. Limits and available node shapes depend on the
deployment; an unset cap does not imply unlimited hardware. Requests above a
configured cap are rejected. Initialization failures caused by CUDA memory
exhaustion include device memory and advice on GPU sizing when available.
The refresh total_gpu_count is an aggregate budget across workers. It must be at
least the Function’s per-worker count. For example, a budget of four GPUs can
fit two workers that each require two. Adaptive sizing preserves the declared
GPU count while adjusting CPU, memory, and the number of workers.
Choose video decoding for the access pattern
GPU decoding is not always faster. Choose the decoder for the frames the Function actually reads:
Benchmark representative clips with the same codec, resolution, and sampling
pattern as the production workload. Include seeks and transfers in the
measurement. A GPU inference stage can still use software decoding to sample
its input frames.
GPU Functions can use NVIDIA’s NVDEC and NVENC driver libraries on deployments
and GPU classes that support video decoding and encoding.
gpu=True requests
a GPU; it does not select a hardware decoder. Your decoding library must also
support the codec and GPU backend. See
GPU Function configuration.
Choose FFmpeg dependencies for the decoding library
PyAV binary wheels bundle FFmpeg. Declare a wheel version in the Function’spip dependencies, such as
pip=["av==18.1.0"]. Software decoding through that wheel does not require a
system ffmpeg installation. Installing PyAV only in the client environment
does not install it on Function workers.
PyAV’s bundled libraries do not supply an ffmpeg command or the system shared
libraries that another package may load:
With a supporting SDK and Enterprise server, declare Debian packages with
apt=["ffmpeg"] on @function, or WITH (apt = 'ffmpeg', ...) in SQL
CREATE FUNCTION. System packages can accompany
pip dependencies. Alternatively, use conda and conda_channels to provide
FFmpeg and the Python packages in one environment; pip and conda are mutually
exclusive dependency declarations.
Match the FFmpeg version to the decoding library’s requirements. GPU decoding
also needs a decoding library and FFmpeg build with the required hardware
support; installing FFmpeg alone does not enable NVDEC. A PyAV source build,
instead of a binary wheel, needs its own FFmpeg build dependencies.
Inspect a Function worker’s environment
Function workers automatically collect a bounded environment report before loading your Function or delivering its bound Secrets. Inspect a finished SQL or refresh job, including a failed job; no probe Function or image rebuild is needed:description document; TEXT is the default.
With FORMAT JSON, parse that column to read the full reports, library paths,
and worker, executor-slot, and Function-version mappings in
function_environments when recorded. TEXT renders the same fields as labeled
metadata.
The separate job.stats() report and the console’s Stats tab group identical
environments under Function environments. Differences in GPU hardware,
drivers, libraries, or packages appear as separate environments. Collection
timestamps and Function code versions do not split an otherwise identical
environment. Environment details are not repeated in SHOW JOB EVENTS.
Reports remain available after initialization fails. A warm worker’s retained
environment is included when it serves another job.
The report includes:
- OS, architecture, Python version, and the immutable Function version.
- Library search directories and up to four matching paths for each of CUDA, NVML, NVDEC, NVENC, cuDNN, CUDA runtime, FFmpeg codec, and FFmpeg utility libraries.
- Installed versions of common GPU and video Python packages, read from package metadata without importing PyTorch, PyAV, or TorchCodec.
- Availability of
nvidia-smiandldconfigon the Function’s command path. - NVIDIA driver version, the maximum CUDA API version supported by that driver, and CUDA-visible GPU models and total memory, when the driver can be queried.
nvidia-smi is absent. It runs in a separate process with a two-second deadline;
a missing driver, tool, or failed query is diagnostic information and does not
fail the Function. The CUDA API version describes driver compatibility, not an
installed toolkit version. Library paths establish file presence, not that the
library and all its dependencies can be loaded. The report uses a bounded set
of common directories; an empty list does not prove a library is absent from
every possible location. It does not dump environment variables or credentials.
The standard Function base is Ubuntu 24.04 with Python and dependencies installed
for each Function. GPU driver interfaces come from the worker’s allocated GPUs;
CUDA runtime and cuDNN packages come from the Function’s dependencies. FFmpeg is
not installed by default: declare the system or conda packages your decoding
library needs, as described above. Custom images can provide a different base
and additional native libraries. Reports require a server release that supports
these diagnostics; older jobs do not acquire reports retroactively.
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.
Each resource resolves independently in this order:
- The refresh’s
total_*value. - The column or materialized view’s
total_*value. - The registered Function’s
total_*value. - The deployment default.
gpu_count=2 still allocates two devices together to every Function worker.
The total_* and total_* values are ceilings for the whole worker
fleet. CPU and memory can limit the fleet before it reaches its GPU ceiling.