Introducing a new way to review your PRs.

Read the announcement

eventual-inc / daft

High-performance data engine for AI and multimodal workloads. Process images, audio, video, and structured data at any scale

View on GitHub

19 documents · Updated Nov 11, 2026

docs / udfs-and-aggregations

UDFs and aggregations

Daft user-defined functions (UDFs) let Python code run as part of a lazy DataFrame query. A UDF declares the shape and type of its work. Daft then plans that work for local workers or distributed workers. Aggregate UDFs extend the same model to reduce rows into one result per group or table. This page is part of Extensibility and custom compute; see Local execution and Distributed execution for the wider runners.

UDF execution model

A UDF call with a DataFrame expression creates a lazy expression. Daft carries the function, its input expressions, output type, resource needs, and execution options into the query plan. A call with no expression inputs can run directly against a local class instance instead. The surrounding query controls when expression-based UDF work runs and which rows reach it.

The main UDF choices are:

Work shapeDefinitionResult behavior
Scalar@daft.func or a @daft.cls methodOne value per input row
Vectorized@daft.func.batch or @daft.method.batchA column result for each input batch
Actor-poolA stateful class with concurrency or resource needsReuses initialized state across many calls
Aggregate@daft.udafOne result per group or for the full input

The public model uses @daft.func, @daft.cls, and @daft.udaf. These interfaces are exported from the daft.udf package and from the top-level daft API.

References: daft/…/__init__.py• L8-10 daft/…/__init__.py• L355-580 daft/…/udf_v2.py• L51-69 daft/…/udf_v2.py• L270-303 docs/…/udf.md• L1-7

Scalar UDFs

Scalar UDFs apply ordinary Python logic to individual rows. Daft evaluates the input expressions before the call and supplies the resulting values to the function. Type hints or return_dtype define the result type before the query runs.

Scalar functions can also be asynchronous. Async row work overlaps I/O and can use a concurrency limit. A generator function is a scalar-style variant that can produce several output rows for one input row. Daft then expands the result and broadcasts selected companion columns to the new rows. A scalar function can also unnest a struct result when its output type declares a struct.

Use a stateful class when the function needs a model, client, or other costly setup. The class stores constructor arguments in the expression and creates its local instance when a worker first needs it. That instance is reused instead of being created for every row.

References: docs/…/func.md• L33-46 docs/…/func.md• L165-204 docs/…/func.md• L202-245 docs/…/cls.md• L1-45 daft/…/udf_v2.py• L175-201 daft/…/udf_v2.py• L243-268 daft/…/udf_v2.py• L323-347 daft/…/udf_v2.py• L393-396

Vectorized UDFs

Vectorized UDFs process a batch of column data at one time. Daft presents each input as a Series, so the function can use column-aware libraries or send a group of values to a model service. The function returns columnar data with the declared output type.

Batch work trades per-row call overhead for larger units of work. A declared batch size can guide how many rows Daft sends in one call. The function must declare its return type because Daft cannot use a scalar return annotation to infer the full batch contract.

The same batch model is available on stateful class methods. This combines vectorized input with reusable worker-local state, which is useful for batch model inference and similar bulk operations.

References: docs/…/func.md• L33-42 docs/…/cls.md• L38-59 docs/…/cls.md• L269-300 daft/…/__init__.py• L251-274 daft/…/__init__.py• L526-568 daft/…/udf_v2.py• L243-268 daft/…/udf_v2.py• L349-369 daft/…/execution.py• L73-99

Actor-pool UDFs

An actor-pool UDF gives a stateful UDF a set of long-lived execution instances. Daft uses the pool when the UDF requests class-level concurrency, Ray options, or resources such as CPUs, GPUs, or memory. The pool spreads calls across instances while each instance keeps its initialized state.

Actor pools are most useful when startup is expensive or when a UDF needs a resource boundary. Resource requests affect placement and the number of instances that can run at once. For @daft.func, max_concurrency applies to async functions. A synchronous function must use a stateful class for actor-pool concurrency. Async max_concurrency limits concurrent coroutines instead and does not by itself create an actor pool.

In distributed execution, the pool starts on the Ray cluster. Daft waits for usable actors before sending work and tears them down after the dependent tasks finish. A pool can be smaller than requested when cluster resources cannot support every requested instance.

References: docs/…/cls.md• L62-97 daft/…/__init__.py• L358-405 daft/…/udf_v2.py• L103-107 daft/…/udf_v2.py• L175-201 daft/…/udf_v2.py• L305-321 daft/…/udf_v2.py• L443-498 daft/…/ray_actor_pool_udf.py• L24-31 daft/…/ray_actor_pool_udf.py• L79-165 src/…/actor_udf.rs• L40-57

UDF data and worker lifecycle

Daft separates expression construction from UDF evaluation. At construction time it validates the type and serialization boundary. At execution time a worker evaluates the input expressions, invokes the Python code, converts the result to a Daft column, and returns it to the surrounding plan.

This diagram shows the common path from a DataFrame expression to local or distributed UDF work.

flowchart LR
    A[DataFrame expressions] --> B[UDF expression and type contract]
    B --> C{Execution runner}
    C -->|Local| D[Local worker]
    C -->|Distributed| E[Ray task or actor pool]
    D --> F[Evaluate input batches]
    E --> F
    F --> G[Run Python UDF]
    G --> H[Build output column and metrics]
    H --> I[Continue query plan]

Serialization boundary

Expression-based UDFs must be serializable because the function definition and its call state can cross from the driver to a worker. The current UDF model checks both the function method and its class wrapper when an expression is built. Non-serializable resources should not be captured in a function or class object that Daft sends with the plan. A stateful class should create those resources during worker setup instead.

The output type is part of the same boundary. Daft uses a type hint or explicit declaration to build the plan, then checks that the returned value or batch can form that type. Changes to value shape also change the downstream contract: a generator expands rows, while a batch or scalar UDF preserves the input row count.

References: daft/…/udf_v2.py• L42-48 daft/…/udf_v2.py• L243-268 daft/…/udf_v2.py• L291-303 daft/…/udaf.py• L116-157 docs/…/cls.md• L28-36 daft/…/execution.py• L73-99

Local worker execution

Local execution evaluates UDFs inside the local execution pipeline. Daft assigns work to worker states, evaluates each input micropartition in batches, and appends the UDF result to any columns that must pass through the projection.

By default, local workers can run the UDF in the process that owns the query. A UDF can request process isolation when its code needs a separate Python process. For Arrow-compatible inputs and outputs, actor-pool or process settings can select an isolated worker path. Python-object data remains on the compatible local path.

See Local execution for the wider local runner and operator flow.

References: src/…/udf.rs• L278-323 src/…/udf.rs• L345-407 src/…/udf.rs• L438-475 src/…/udf.rs• L29-63

Isolated Python workers

When process execution is selected, Daft starts a Python worker for the UDF. The parent sends the planned expression and each input batch through a private local connection. Shared memory carries the serialized batch data, and the worker returns a serialized result with execution metrics.

The worker initializes UDF state after its handshake, evaluates repeated input batches in an event loop, and reports Python errors back to the parent. The parent also drains worker output so user logs do not block result delivery. This gives UDF failures and output a clear boundary without changing the lazy query interface.

References: daft/…/udf.py• L33-55 daft/…/udf.py• L58-113 daft/…/udf.py• L134-191 daft/…/udf_worker.py• L27-74 daft/…/udf_worker.py• L75-103

Distributed worker execution

Distributed execution keeps the UDF expression in the distributed plan and places the work after its input tasks. Ordinary UDF work becomes a local physical step inside distributed tasks. Actor-pool UDFs add a shared set of Ray actors and attach those actors to the tasks that process the input.

The distributed runner gathers UDF runtime statistics from worker nodes and presents them under the UDF plan node. Resource requests and actor readiness therefore affect scheduling before the UDF receives data. A failure to start a required actor prevents the dependent UDF work from proceeding.

See Distributed execution for task orchestration, Ray resources, and worker coordination.

References: src/…/udf.rs• L106-160 src/…/udf.rs• L216-240 src/…/actor_udf.rs• L175-233 src/…/actor_udf.rs• L237-294

Aggregate UDFs

An aggregate UDF reduces many rows into one result per group or for the full input. @daft.udaf defines the reduction as a three-stage contract so Daft can calculate partial results near the input and merge them later.

The aggregate class declares both the final output type and the type of its intermediate state. The state can be one value or several named fields. The same UDAF can be used with groupby().agg() or with a global agg() operation.

Aggregate stages

The aggregation lifecycle has a fixed relationship between input rows, intermediate state, and final output:

  1. aggregate consumes the input Series values for one group or input partition and returns a partial state.
  2. combine merges partial states from separate partitions into one state.
  3. finalize converts the merged state into the declared result value.

The combine operation must be associative and commutative. Daft does not promise the order in which partitions arrive. An order-dependent merge can produce different results on different runs or cluster layouts.

References: daft/…/udaf.py• L16-58 docs/…/udaf.md• L39-53 src/…/python_udaf.rs• L28-57

Aggregate state

State is the contract that connects the three aggregate stages. A single-state UDAF receives a Series of state values during combination. A multi-state UDAF uses a named mapping of Series values and must return the same named fields from its aggregate and combine steps.

Daft carries this typed state through the plan rather than treating it as an opaque Python value. The planner can then split a UDAF into partial and final work. This reduces data movement for distributed grouped and global aggregation while keeping finalize responsible for the user-facing result.

References: daft/…/udaf.py• L50-58 daft/…/agg_execution.py• L31-46 daft/…/agg_execution.py• L49-100 src/…/python_udaf.rs• L34-45 src/…/agg.rs• L354-415

Grouped and global aggregation

The DataFrame operation supplies the scope of an aggregate UDF. A grouped aggregation hashes rows by its group keys and returns one result for each key. A global aggregation has one result for the full input and does not need group keys.

For grouped work, Daft can aggregate before partitioning when that reduces the data volume. It can instead partition first when group cardinality is high. UDF aggregations that cannot be split into partial and final stages must keep each full group together and run after partitioning.

References: docs/…/udaf.md• L3-4 docs/…/udaf.md• L148-166 src/…/grouped_aggregate.rs• L34-109 src/…/grouped_aggregate.rs• L177-217 src/…/grouped_aggregate.rs• L347-417

UDF metrics

UDF metrics make custom work visible without requiring the UDF to manage a separate metrics system. During each UDF call Daft provides a metrics context. The UDF can increment named counters. Daft attaches those counters to the UDF operator along with input, output, time, task, and byte measures.

Custom counters are useful for domain results such as cache hits, service calls, or model tokens. A counter call outside an active UDF execution is not recorded. Local execution keeps the counters with its runtime statistics. Distributed execution collects worker snapshots and adds them to the distributed UDF node.

References: daft/…/metrics.py• L14-65 daft/…/execution.py• L42-70 src/…/udf.rs• L48-97 src/…/udf.rs• L124-151 src/…/udf.rs• L28-104

Error and retry behavior

UDF calls can define retry and final-error behavior as part of their execution contract. The default is to raise after the configured retries. Other modes can log the final failure or ignore it and emit a null result. These choices apply to the UDF call boundary. They do not make a non-repeatable side effect safe to retry.

Python exceptions cross an isolated worker boundary with an error message and traceback when possible. Actor pools also have restart and task retry limits at the Ray boundary. A resource or readiness failure occurs before user code can process the input.

References: docs/…/cls.md• L62-97 daft/…/__init__.py• L21-63 daft/…/udf_v2.py• L175-201 daft/…/udf_v2.py• L349-369 daft/…/udf.py• L160-193 daft/…/ray_actor_pool_udf.py• L24-31 daft/…/ray_actor_pool_udf.py• L109-160

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the UDF output type, row shape, and batch contract aligned across the Python decorator, expression schema, and local execution path.
  • Keep serialization assumptions aligned with worker setup. Move new non-serializable resources into stateful worker initialization rather than captured expression state.
  • Keep actor-pool resource requests aligned across UDF properties, Ray actor creation, and distributed task placement.
  • Keep aggregate state names and types identical across aggregate, combine, finalize, planner stages, and state packing.
  • Preserve associative and commutative aggregate combination when changing the partial or final aggregation plan.
  • Preserve metric names and attributes across Python collection, local snapshots, and distributed worker aggregation.

Important failure modes

TriggerConsequenceGuard
A UDF has no return type hint or explicit return typeDaft cannot build the output schemaAdd a return annotation or return_dtype; batch UDFs require an explicit type
A synchronous @daft.func receives max_concurrencyExpression construction fails because coroutine concurrency does not applyUse an async function for coroutine concurrency or @daft.cls for an actor pool
A function or captured class state is not serializableExpression construction fails before worker executionCapture only serializable values and create external clients or models during worker setup
A batch UDF returns data with the wrong length or typeThe batch cannot become the declared output columnReturn one column result for the input batch and match return_dtype
An actor requests resources that no node can provideThe actor pool cannot start and dependent tasks failRequest resources that fit one node and size concurrency for cluster capacity
An aggregate combine depends on partition orderGrouped or global results can be incorrect or unstableMake state merging associative and commutative
Aggregate state fields differ between stagesState packing or finalization failsKeep state names, types, and returned fields aligned
A custom metric is incremented outside UDF executionThe counter is dropped and a warning is emittedIncrement counters from the UDF function or class method
A retryable UDF performs a non-repeatable side effectA retry can duplicate the side effectMake the side effect idempotent or disable retries for that operation

Key files

FileWhy to read it
docs/…/func.mdUser-facing view of scalar, async, generator, and batch UDF choices
docs/…/cls.mdUser-facing view of stateful classes, worker reuse, resources, and concurrency
docs/…/udaf.mdUser-facing view of aggregate stages, state, grouped scope, and global scope
daft/…/__init__.pyPublic decorators for functions, classes, methods, batch methods, metrics, and aggregate UDFs
daft/…/udf_v2.pyCurrent UDF contract and the conversion from decorated calls to lazy expressions
daft/…/execution.pyPython call boundary for scalar, async, and batch execution
daft/…/udaf.pyPython aggregate definition and typed state declaration
daft/…/agg_execution.pyPython aggregate stage boundary and state reuse
daft/…/udf.pyIsolated Python worker transport and error return path
daft/…/udf_worker.pyWorker event loop for repeated UDF batch evaluation
daft/…/ray_actor_pool_udf.pyRay actor-pool startup, resource placement, readiness, and teardown
src/…/udf.rsLocal UDF scheduling, worker state, batching, and runtime metrics
src/…/grouped_aggregate.rsGrouped aggregation strategy and final state reduction
src/…/actor_udf.rsDistributed actor-pool lifecycle and task attachment
src/…/udf.rsDistributed UDF plan node and worker metric collection
src/…/agg.rsPlanner split between partial, combine, and final aggregate stages