Skip to content

[Prototype] Serialize stateful functions without a codec - #28009

Draft
adriangb wants to merge 11 commits into
apache:mainfrom
adriangb:proto-udf-registry-prototype
Draft

adriangb wants to merge 11 commits into
apache:mainfrom
adriangb:proto-udf-registry-prototype

Conversation

@adriangb

@adriangb adriangb commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

  • Prototype for #28006. It does not close the issue.

This PR is a draft to support the design discussion. It is not ready to merge.

Rationale for this change

The problem

A function with fields cannot be rebuilt from its name. Take a UDF that multiplies by a factor:

struct ScaleBy { name: String, factor: i64, signature: Signature }

ScalarUDF::new_from_impl(ScaleBy::new("scale_by_7", 7));

datafusion-proto writes the name scale_by_7. The receiving node has no way to learn the 7. Today the only fix is a PhysicalExtensionCodec that knows ScaleBy:

impl PhysicalExtensionCodec for MyCodec {
    fn try_encode_udf(&self, udf: &ScalarUDF, buf: &mut Vec<u8>) -> Result<()> {
        if let Some(f) = udf.inner().downcast_ref::<ScaleBy>() { /* write f.factor */ }
        // ... and one branch for every other stateful function in the system
        Ok(())
    }
    fn try_decode_udf(&self, name: &str, buf: &[u8]) -> Result<Arc<ScalarUDF>> { /* ... */ }
}

One codec must know every stateful function of every crate in the process. Two libraries that each ship a codec cannot be combined without a third codec that wraps both.

Plans, physical expressions, data sources, file sources and sinks already left this model: each type writes itself and registers a decoder in the ProtoDecoderRegistry of the session. Stateful functions are the remaining gap.

The proposal

The function writes its own state. The session holds the decoder. No codec.

// Encode side: datafusion-expr, no feature flag.
impl ScalarUDFImpl for ScaleBy {
    fn try_encode_state(&self) -> Result<Option<UDFState>> {
        Ok(Some(UDFState {
            type_name: Self::NAME,
            payload: self.factor.to_le_bytes().to_vec(),
        }))
    }
    // ...
}

// Decode side: datafusion-execution, behind the new `proto` feature.
impl ScalarUdfFromProto for ScaleBy {
    const NAME: &'static str = "my_crate.ScaleBy";

    fn try_from_proto(payload: &[u8], name: &str, _ctx: &TaskContext) -> Result<Arc<ScalarUDF>> {
        let factor = i64::from_le_bytes(payload.try_into().unwrap());
        Ok(Arc::new(ScalarUDF::new_from_impl(ScaleBy::new(name, factor))))
    }
}

// The receiving session registers the decoder once.
config.update_extension(ScaleBy::register_proto)?;

// No codec on either side.
let bytes = physical_plan_to_bytes(plan)?;
let plan = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?;

This prototype checks that the pattern works for all four function kinds that PhysicalExtensionCodec handles:

Function kind Codec methods today Encode hook Decoder trait
Scalar try_encode_udf / try_decode_udf ScalarUDFImpl::try_encode_state ScalarUdfFromProto
Aggregate try_encode_udaf / try_decode_udaf AggregateUDFImpl::try_encode_state AggregateUdfFromProto
Window try_encode_udwf / try_decode_udwf WindowUDFImpl::try_encode_state WindowUdfFromProto
Higher-order try_encode_higher_order_function / try_decode_higher_order_function HigherOrderUDFImpl::try_encode_state HigherOrderUdfFromProto

What changes are included in this PR?

How the pieces fit

flowchart LR
    subgraph enc["Encoding process"]
        F["ScaleBy { factor: 7 }<br/>registered as scale_by_7"]
        H["try_encode_state()<br/><i>datafusion-expr</i>"]
        F --> H
    end

    subgraph wire["Proto node"]
        N["name = scale_by_7"]
        T["fun_type_name = my_crate.ScaleBy<br/><b>new field</b>"]
        D["fun_definition = payload bytes"]
    end

    subgraph dec["Decoding process"]
        R["ProtoDecoderRegistry<br/>in SessionConfig"]
        P["ScaleBy::try_from_proto(payload, name, ctx)<br/><i>datafusion-execution</i>"]
        G["ScaleBy { factor: 7 }<br/>named scale_by_7"]
        R --> P --> G
    end

    H -- "UDFState.type_name" --> T
    H -- "UDFState.payload" --> D
    T -- "selects the decoder" --> R
    D --> P
    N --> P
Loading

The wire has two names on purpose:

Name Example Identifies Used for
name scale_by_7 One registered instance The SQL name of the rebuilt function
fun_type_name my_crate.ScaleBy The implementing type The registry key of the decoder

One type can back many instances (scale_by_7, scale_by_3), so the SQL name cannot be the registry key.

Who decodes a function node

fun_type_name also tells the reader who wrote fun_definition. The rule is the same for all four kinds:

flowchart TD
    A{"fun_type_name present?"}
    A -- yes --> B{"decoder registered<br/>under that name?"}
    B -- yes --> C["Registry decoder.<br/>Error if the result has another SQL name."]
    B -- no --> E["Error that lists the registered type names.<br/>No codec fallback."]
    A -- no --> F{"fun_definition present?"}
    F -- yes --> G["PhysicalExtensionCodec, as today"]
    F -- no --> H["Lookup by name in the session, as today"]
Loading

On encode, the state of the function wins over the codec. A function that returns Ok(None) (the default) takes the codec path as before.

The plan channel

Scalar and higher-order functions are expression nodes that only datafusion-proto encodes. Aggregate and window functions are different: AggregateExec and the window plans encode them through ExecutionPlanEncodeCtx, whose methods return bytes only.

 // datafusion_physical_plan::proto
 ctx.encode_udaf(udaf)?;                  // -> Option<Vec<u8>>, no slot for a type name
+ctx.encode_udaf_definition(udaf)?;       // -> EncodedFunction { payload, type_name }

 ctx.decode_udaf(name, payload)?;
+ctx.decode_udaf_definition(name, payload, type_name)?;
 // the same pair for udwf
Method Function has no state Function wrote its own state
encode_udaf, encode_udwf, encode_udf (bytes only) Codec bytes, as today Not-implemented error. The state is never dropped silently.
encode_udaf_definition, encode_udwf_definition Codec bytes, no type name The state and its type name

How to review

The commits are ordered so that the first three change no behavior and the next two only add API. Each commit builds and passes its tests.

Commit Kind Content
1 Mechanical Adds optional string fun_type_name to the four function nodes. Every writer sets None. pbjson.rs and prost.rs are generated.
2 Refactor Moves the codec call and the "empty bytes mean by name" rule into one encode_* helper per function kind. No behavior change.
3 Refactor Adds EncodedFunction and the *_definition methods to the plan channel. AggregateExec and the window plans use them. The type name is always None. No behavior change.
4 API Adds UDFState and try_encode_state to the four function traits and their wrappers. Nothing calls the hook.
5 API Adds the proto feature of datafusion-execution with the four *FromProto decoder traits. Nothing decodes with them.
6 Change The provided encode_udaf_definition and encode_udwf_definition ask the function for its state first.
7 Change Scalar UDFs: encode, decode, the shared decode_self_encoded helper and its errors. Tests in udf_registry.rs.
8 Change Aggregate UDFs. Tests in udaf_registry.rs.
9 Change Window UDFs. Tests in udwf_registry.rs.
10 Change Higher-order functions. Tests in hof_registry.rs.
11 Tests Unit tests with a codec that writes bytes for every function.

The four "Change" commits for the function kinds have the same shape. Read the scalar one closely and skim the other three.

New public items

Crate Items
datafusion-expr UDFState. try_encode_state on ScalarUDFImpl, AggregateUDFImpl, WindowUDFImpl, HigherOrderUDFImpl (provided methods, default Ok(None)) and on ScalarUDF, AggregateUDF, WindowUDF, HigherOrderUDF.
datafusion-execution The proto feature. In datafusion_execution::proto: ScalarUdfFromProto, AggregateUdfFromProto, WindowUdfFromProto, HigherOrderUdfFromProto, and scalar_udf_names, aggregate_udf_names, window_udf_names, higher_order_udf_names. Hidden, for internal use only: decode_scalar_udf, decode_aggregate_udf, decode_window_udf, decode_higher_order_udf.
datafusion-physical-plan proto::EncodedFunction and impl From<UDFState> for EncodedFunction. encode_udaf_definition and encode_udwf_definition on ExecutionPlanEncodeCtx. decode_udaf_definition and decode_udwf_definition on ExecutionPlanDecodeCtx.
datafusion-proto-models The fun_type_name field on PhysicalScalarUdfNode, PhysicalAggregateExprNode, PhysicalWindowExprNode and PhysicalHigherOrderUdfNode.

Open questions

Topic State in this PR
Logical plans The logical serde is unchanged. A stateful function in a logical plan still needs a codec.
Wrappers A wrapper that does not forward try_encode_state loses the state. The alias wrappers and AsyncScalarUDF forward it. AsyncScalarUDF also needs the decoder to wrap the function again.
FFI The foreign function wrappers need an ABI slot to forward the hook.
API surface Four decoder traits and four hooks. One generic trait is an alternative.
Crate placement The encode hook is in datafusion-expr. The decoder traits are in datafusion-execution, because the decoder takes a TaskContext.

What is the testing strategy for this PR?

The core test, in udf_registry.rs: one type, two instances, no codec, and the decoding session does not have the functions registered by name.

let plan = project(vec![
    ScalarUDF::new_from_impl(ScaleBy::new("scale_by_7", 7)),
    ScalarUDF::new_from_impl(ScaleBy::new("scale_by_3", 3)),
])?;
let bytes = physical_plan_to_bytes(plan)?;

let ctx = registry_session()?; // only `ScaleBy::register_proto`
let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?;
assert_eq!(run(decoded, &ctx).await?, vec![vec![7, 14, 21], vec![3, 6, 9]]);

Four files in datafusion/proto/tests/cases/plans/ hold 23 round-trip tests that assert exact output values:

Case Scalar Aggregate Window Higher-order
Stateful function round-trips through a real plan ProjectionExec AggregateExec WindowAggExec ProjectionExec
One type under two SQL names keeps both states yes yes yes
Aliased function keeps its state yes yes yes yes
Unregistered type name is an error yes yes yes yes
Function with no state still decodes by name yes yes yes yes
Definition that a codec wrote still decodes with the codec yes yes yes yes
Decoder that returns another SQL name is an error yes
Async wrapper keeps the state yes
Aggregate used as a window function keeps the state yes

Unit tests in datafusion-proto and datafusion-physical-plan cover the plan channel:

  • The bytes-only encode_udf, encode_udaf and encode_udwf reject a self-encoded function with an exact message.
  • The state of a function wins over a codec that also writes bytes.
  • The provided definition methods keep the state on encode and reject a type name on decode.

Known gap: the state in the higher-order test does not change the query output. The test checks the decoded state directly.

Are there any user-facing changes?

Yes, all additive: the public items listed above.

Question Answer
Do existing serialized plans still decode? Yes. An absent fun_type_name keeps the current behavior.
Do existing codecs still work? Yes. A function that does not implement try_encode_state takes the codec path.
What is hard to undo after a release? The fun_type_name field numbers and the try_encode_state signature.

🤖 Generated with Claude Code

@github-actions github-actions Bot added logical-expr Logical plan and expressions execution Related to the execution crate proto Related to proto crate physical-plan Changes to the physical-plan crate labels Dec 4, 2026
@adriangb adriangb changed the title [Prototype] Serialize stateful scalar UDFs without a codec [Prototype] Serialize stateful functions without a codec Dec 5, 2026
adriangb and others added 11 commits December 4, 2026 22:48
A function that serializes its own state needs a place on the wire for the
key of the decoder that rebuilds it. The existing `fun_definition` bytes
belong to the `PhysicalExtensionCodec`, so a reader cannot tell who wrote
them.

Add `optional string fun_type_name` to `PhysicalScalarUdfNode`,
`PhysicalHigherOrderUdfNode`, `PhysicalAggregateExprNode` and
`PhysicalWindowExprNode`. Every writer sets it to `None` and the scalar
reader ignores it, so this commit changes no behavior.

Mechanical: `pbjson.rs` and `prost.rs` are regenerated from
`datafusion.proto`.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Three call sites in `to_proto.rs` and three in `ConverterPlanEncoder` each
repeat the codec call and the "empty bytes mean by name" rule. The
self-encoded state added later needs one place per function kind to take
precedence over the codec.

Move that logic into `encode_scalar_udf`, `encode_aggregate_udf`,
`encode_window_udf` and `encode_higher_order_udf`. Each returns
`(fun_definition, fun_type_name)`. The type name is always `None` here, so
the wire output does not change.

Refactor: no behavior change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
`AggregateExec` and the window operators encode their functions through
`ExecutionPlanEncodeCtx::encode_udaf` and `encode_udwf`, which return only
bytes. A self-encoded function also needs its decoder type name written to
and read from the plan node.

Add `EncodedFunction` (payload plus type name) and the
`encode_udaf_definition`, `encode_udwf_definition`,
`decode_udaf_definition` and `decode_udwf_definition` methods to the
encode and decode traits and contexts. The aggregate and window nodes use
them. The provided encoders write no type name, and the provided decoders
reject one, so every existing plan round-trips as before.

Refactor: no behavior change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A function that carries per-instance state (a model path, a compiled
regex, a config value) cannot be rebuilt from its name. Today the only way
to ship that state is a `PhysicalExtensionCodec` that knows every such
function.

Add `UDFState { type_name, payload }` and a `try_encode_state` hook to
`ScalarUDFImpl`, `AggregateUDFImpl`, `WindowUDFImpl` and
`HigherOrderUDFImpl`. The default returns `Ok(None)`. The `ScalarUDF`,
`AggregateUDF`, `WindowUDF` and `HigherOrderUDF` wrappers, the alias
wrappers and `AsyncScalarUDF` forward to the inner function.

Nothing calls the hook yet.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The decoding side needs a typed way to turn a `UDFState` payload back into
a function. The decoder takes a `TaskContext`, so it cannot live in
`datafusion-expr`.

Add the `proto` feature and module to `datafusion-execution`, with
`ScalarUdfFromProto`, `AggregateUdfFromProto`, `WindowUdfFromProto` and
`HigherOrderUdfFromProto`. Each registers a constructor in the session's
`ProtoDecoderRegistry` under `NAME`. The hidden `decode_*` functions and
the `*_names` functions are the lookups that `datafusion-proto` uses.
`datafusion-proto` and the `proto` feature of `datafusion-physical-plan`
turn the feature on.

Nothing decodes with these yet.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…oders

An `ExecutionPlanEncode` implementation that only writes bytes would drop
the state of a function that implements `try_encode_state`. The decoder
would then resolve the function by name and build the wrong instance.

Make the provided `encode_udaf_definition` and `encode_udwf_definition`
ask the function for its state first and fall back to the bytes-only
method. Add `impl From<UDFState> for EncodedFunction`.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A scalar UDF with per-instance state needs a `PhysicalExtensionCodec`
that knows it. The function now has `try_encode_state` and the session has
`ScalarUdfFromProto` decoders, but the serializer uses neither.

Encode: `encode_scalar_udf` asks the function for its state before the
codec and writes the type name to `fun_type_name`. The bytes-only
`ExecutionPlanEncode::encode_udf` has no slot for the type name, so it
returns a not-implemented error for such a function.

Decode: a node with `fun_type_name` goes to the `ProtoDecoderRegistry` of
the session. An unregistered type name is an error that lists the
registered names. A decoder that returns a function with another SQL name
is an error. A node without `fun_type_name` decodes as before.

`udf_registry.rs` holds the round-trip tests.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Apply the scalar UDF design to aggregate UDFs.

Encode: `encode_aggregate_udf` asks the function for its state before the codec. The bytes-only
`ExecutionPlanEncode::encode_udaf` returns a not-implemented error for a
self-encoded function and points to `encode_udaf_definition`.

Decode: `ConverterPlanDecoder` overrides `decode_udaf_definition`. This covers
`AggregateExec` and aggregates used as window functions. A node with `fun_type_name` goes to the `AggregateUdfFromProto` decoder in
the session's `ProtoDecoderRegistry`, with the same errors as the scalar
path. A node without it decodes as before.

`udaf_registry.rs` holds the round-trip tests.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Apply the scalar UDF design to window UDFs.

Encode: `encode_window_udf` asks the function for its state before the codec. The bytes-only
`ExecutionPlanEncode::encode_udwf` returns a not-implemented error for a
self-encoded function and points to `encode_udwf_definition`.

Decode: `ConverterPlanDecoder` overrides `decode_udwf_definition`. A node with `fun_type_name` goes to the `WindowUdfFromProto` decoder in
the session's `ProtoDecoderRegistry`, with the same errors as the scalar
path. A node without it decodes as before.

`udwf_registry.rs` holds the round-trip tests.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Apply the scalar UDF design to higher-order functions.

Encode: `encode_higher_order_udf` asks the function for its state before the codec.

Decode: Higher-order functions are expressions, so the expression decoder
handles them and the plan channel does not change. A node with `fun_type_name` goes to the `HigherOrderUdfFromProto` decoder in
the session's `ProtoDecoderRegistry`, with the same errors as the scalar
path. A node without it decodes as before.

`hof_registry.rs` holds the round-trip tests.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…bytes

The round-trip tests use the default codec, which writes nothing for a
function. They do not show what happens when a codec and a function both
want to write the definition.

Add unit tests with `PayloadCodec`, which writes bytes for every function:
the bytes-only encoders reject a self-encoded function with an exact
message, and the definition encoders prefer the function's state over the
codec bytes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@adriangb
adriangb force-pushed the proto-udf-registry-prototype branch from 65db2e5 to dffd0e9 Compare December 5, 2026 04:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

execution Related to the execution crate logical-expr Logical plan and expressions physical-plan Changes to the physical-plan crate proto Related to proto crate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant