Skip to content

Add method on SessionContext to add all extensions from one library - #1679

Draft
timsaucer wants to merge 12 commits into
mainfrom
feat/ffi-with-extensions
Draft

Add method on SessionContext to add all extensions from one library#1679
timsaucer wants to merge 12 commits into
mainfrom
feat/ffi-with-extensions

Conversation

@timsaucer

@timsaucer timsaucer commented Aug 7, 2026

Copy link
Copy Markdown
Member

Which issue does this PR close?

Part 3 of 3 in the split of #1672. These are enabled as a github stack so you should be able to swab between the 3 PRs in github interface (above, next to the "Open" oval).

Rationale for this change

Working on the Ballista integration showed that chaining the low-level with_* methods is easy to get wrong. FFI codecs and planners carry a weak task-context provider, and a query planner is built against whatever codec chains exist at the moment it is installed — so installing a codec afterwards leaves the planner encoding through a chain that is missing a library, and the caller is responsible for an ordering rule nothing enforces. SessionContext.with_extensions makes the whole installation one step so there is no "afterwards".

What changes are included in this PR?

  • SessionContext.with_extensions(*extensions) installs one or more extension bundles atomically. Each bundle implements the new __datafusion_session_extension__(ctx) protocol: it receives the session it is being installed on, creates fresh components bound to that session, and returns them as a SessionExtensionComponents (new public dataclass; SessionExtensionExportable is the matching typing protocol).
  • Internally the factories bind against the receiving context, all codecs are installed, and only then is a planner bound against the final chains. The chains belong to the returned handle rather than to SessionState, so a codec-only install onto a session with no FFI planner writes no state at all; when there is a planner to bind — one a bundle supplied, or one already installed that has to be rebuilt against the new chains — that is a single write through the session's own state_ref(). There is one Arc<SessionContext> per session, so every weak provider a factory creates stays valid for as long as any handle on that session is alive.
  • Like the individual with_* methods, the returned context is a handle on the same session as the receiver: catalogs, tables, registered functions, and configuration are the one session, and the planner is installed on that shared session even if the returned handle is discarded. Only the Python-side codec chains belong to the returned handle.
  • Nothing is written to the session until every factory has returned and every capsule has been validated, so a failing factory leaves the session as it was. The exception is a factory that mutates the context it is handed — a registration made during binding is not rolled back — which is why bundle objects must be configuration-only.
  • If no bundle supplies a planner, an existing FFI planner is rebound to the new codec chains; at most one bundle may supply a planner.
  • A codec handed over as a bare PyCapsule is named after the bundle that contributed it. A capsule carries no type of its own, so it previously fell through to anon:<uuid4> — an id private to the installing session, which makes the plans it writes undecodable anywhere else. A bundle is a plain object, so its module.QualName is library-owned and exactly as stable across processes as an exporting codec class's, which id resolution already trusts. This matters for a distributed engine, whose plans have to decode in another process: the bundle writes ballista.BallistaExtension and the scheduler installs a codec under that same id. Resolution goes through derive_codec_id itself, so a bundle can pin its id with __datafusion_codec_id__ against a later class rename, and an id declared on the handed-over object — or that object's own class — still wins.
  • The ownership contract is documented and tested: the session owns the installed components' providers, and a DataFrame outliving every handle on it fails with a clean out-of-scope error rather than crashing.
  • MyPlannerExtension in the example crate is a complete Rust implementation of the protocol, including extracting the host's task-context provider from the supplied context. Its codecs record the config value they resolve through the weak provider, letting tests prove the provider resolves against the session that runs the query.
  • docs/source/contributor-guide/ffi.md documents with_extensions as the preferred API for extension bundles, keeps low-level chaining as advanced usage, and includes a full three-library registration recipe. docs/source/user-guide/upgrade-guides.md points at it from the planner-install section.
  • Rule 6 of .ai/skills/ffi-capsule-protocol/SKILL.md — "a session keeps one Arc<SessionContext> for life" — now calls out with_extensions as where that rule is easiest to get wrong, since "bind the components to the context you are about to return" reads like an instruction to derive one first.

Are there any user-facing changes?

New public APIs: SessionContext.with_extensions, SessionExtensionComponents, and the SessionExtensionExportable / __datafusion_session_extension__ protocol. The context-outlives-DataFrame ownership contract is now documented. No breaking changes to existing APIs.

Review notes

Two things changed during review that are worth calling out, since the earlier revision reads differently.

The installation no longer derives a separate context. It used to — _derive_for_extensions, using SessionContext::new_with_state(self.ctx.state()) — and bound the factories against that. Because new_with_state carries the session id over while minting a fresh Arc<RwLock<SessionState>>, that produced two live sessions reporting one session_id() with independent state: configuration and the function registry diverged, catalogs stayed shared, and both handles reported the same __datafusion_codec_id__, which is session:<session_id> and exists precisely to tell codec chains apart.

The fork also bought nothing. It was meant to stop components binding to an intermediate context that could later be collected, but with one Arc<SessionContext> per session there is no such intermediate — deriving one is what creates the hazard, which is why Rule 6 of the capsule-protocol skill already said to mutate SessionState in place rather than derive a replacement. _derive_for_extensions is gone and the factories are handed the receiver. test_with_extensions_provider_targets_returned_context was vacuous once the session is shared and has been replaced by test_with_extensions_shares_the_session_with_the_source, which asserts matching session ids and that a SET issued through the source after installation is visible to the provider the bundle bound. Reintroducing the fork fails it.

Bare capsules from a bundle are named rather than randomized, as described above. This closes the gap that made the natural shape for a distributed engine — a Rust bundle handing over capsules, which is what MyPlannerExtension does — the one shape that could not produce portable plans. Two bare capsules of one kind from one bundle collide on that single id and are refused: numbering them by position would be exactly the kind of id codec.rs rejects for anon:, one another library can mint the same value from, and it would break stored plans the first time a bundle reordered what it returns. The collision message now names both routes to a distinct identity; it previously offered only codec_id=, which is unreachable from with_extensions.

I considered adding explicit id fields to SessionExtensionComponents instead. Once bundle-derived ids exist that would only serve the two-capsules-of-one-kind case, which an author already solves by wrapping the capsule in an object declaring __datafusion_codec_id__ — not worth a permanent field on a public dataclass.

Related follow-ups, neither of which this PR needs: enable_url_table is now once again the only method that mints a second Arc<SessionContext> for a session, and it forks state while keeping the session id (#1708); an agent skill for extension authors, as suggested in review, is #1707.

@ntjohnson1 ntjohnson1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have a fully coherent thought here. IIUC this is mostly to manage life times across the FFI boundary. I do wonder if there is a slightly cleaner way to mange this but this seems fine for now to provide a safer avenue.

I wonder if it makes sense to have a todo for some datafusion python extension skill/s. Being able to generate the 3 library example from the skill might be a nice smoke test to verify. I suspect after getting things setup for ballista/datafusion-distributed keeping it up to date shouldn't be too bad but I do suspect it will require some guidance to make sure they are doing it safely.

Comment thread python/datafusion/context.py Outdated
Comment thread python/datafusion/context.py

@milenkovicm milenkovicm left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks @timsaucer
i guess the only open point is chaining of codecs raised in previous pr

@milenkovicm

Copy link
Copy Markdown
Contributor

Following up on comment apache/datafusion-ballista#2252 (review) and follow up on this PR. FFILogicalCodec::encode|decode_file_format break our intent to have fully working distributed execution.

I might be wrong but encode|decode_file_format might not be an easy fix, at least not in short term and not in datafusion 55 timeframe, hence i have a proposal to make.

DistributedExec in ballista is nothing but a GRPC wrapper, it takes a logical plan, calls grpc endpoint and returns a stream of record batches. Would it make sense to create a CallbackPlanner (we might need a CallbackExec) in datafusion-py which would take a python closure LogicalPlan -> Stream<RecordBatches> (or LogicalPlanBlob -> Stream<RecordBatches>). Ballista would provide a closure which implements grcp logic in python code.

As CallbackPlanner have same library marker as df python FFILogicalCodec will not be triggered and we should have possibility to fully integrate distributed execution.

Basically we could implement query planner in python (limited but working)

wdyt @timsaucer and @ntjohnson1 ?

@timsaucer
timsaucer force-pushed the feat/ffi-with-extensions branch 2 times, most recently from e95bc43 to 4f16fa6 Compare September 4, 2026 17:11
@timsaucer

Copy link
Copy Markdown
Member Author

Thanks for chasing this down — the write_* failures are real, but I think the fix is much smaller than a new planner API, and it is not in this PR.

Where it actually breaks. FFI_LogicalExtensionCodec has no vtable entries for file formats at all. Both hooks are hardcoded stubs in datafusion-ffi (src/proto/logical_extension_codec.rs, try_decode_file_format / try_encode_file_formatnot_impl_err!("FFI does not support ...")). So any codec that crosses the FFI boundary loses file-format support, and df.write_csv/write_parquet/write_json build a LogicalPlan::Copy that carries a FileFormatFactory. That is the whole failure.

This PR already survives it on the datafusion-python side. PythonLogicalCodec::try_{encode,decode}_file_format go through chain_encode/chain_decode, which collect a chained codec's error and fall through to the terminal DefaultLogicalExtensionCodec. Built-in formats encode and decode fine there. The direction that fails is the mirror image: Ballista holds an FFI_LogicalExtensionCodec wrapping the Python session's codec and calls it directly, with no Default fallback behind it.

Two fixes, both much cheaper than a new API:

  1. Ballista side, today, no upstream change. Compose the FFI codec you get from Python with a DefaultLogicalExtensionCodec fallback on the two file-format hooks — the same shape PythonLogicalCodec uses here. One file, unblocks DF 55.

  2. Upstream datafusion-ffi, ~8 lines. Make those two hooks delegate to a local DefaultLogicalExtensionCodec instead of returning not_impl_err!. No new vtable entries, so no ABI break, so it can ship in a 55.x patch. It works because built-in file formats are fully self-describing protobuf and nothing has to cross the boundary: DefaultLogicalExtensionCodec::try_encode_file_format in datafusion-proto covers csv/json/arrow/avro/parquet by downcasting the factory locally. What is left unsupported is a custom FileFormatFactory owned by the foreign library, and I agree that one needs a real FFI_FileFormatFactory and will not make the 55 window — but it is also not what is breaking write_*.

On CallbackPlanner. I do not think the concept holds up, and I want to be concrete about why rather than just deferring it.

A QueryPlanner returning a CallbackExec leaf replaces the entire plan with one opaque node: no children, no partitioning DataFusion can see, no pushdown, no repartition, no limit, no statistics. That is not planning, it is interception at the root. It is coherent for exactly one architecture — thin client, full delegation — which is what Ballista's DistributedExec already is; the local plan is degenerate because none of the work is local. But it has no answer for a hybrid plan, a local table joined against a remote one, because there is nothing left to split on. All or nothing.

It also buys very little over what already ships:

plan_bytes = df.logical_plan().to_bytes(ctx)
batches = my_grpc_client.execute(plan_bytes)   # your gRPC logic, in Python
result = ctx.from_arrow(batches)               # any __arrow_c_stream__ object

All three exist today, no new API. The only thing CallbackPlanner adds on top is transparency — the user keeps writing ctx.sql(...).collect() and never sees the interception. That is real, but it is a thin return for a permanent public API, and a second planner mechanism sitting next to the FFI query planner means two ways to do one thing.

If the goal is partial delegation rather than whole-plan delegation, the design that answers it already exists: a table provider exported from Python (__datafusion_table_provider__, see docs/source/user-guide/io/table_provider.md). Remote data appears as a table, DataFusion plans around it, filter and projection pushdown work, and local and remote sources mix in one query. That composes; a root-level callback does not.

The part that makes me most hesitant is the stated rationale: "As CallbackPlanner have same library marker as df python, FFILogicalCodec will not be triggered." That shapes a public API around which cdylib the code is compiled into, in order to route around an eight-line gap in datafusion-ffi. Fixing the gap is the smaller and more durable change.

One genuinely open question, independent of all of the above — and I think it is the same "chaining of codecs" point you flagged. Once Ballista's codec is installed on the Python session it becomes a chain entry, and chain entries write a framed payload (DFPYCHN + codec id) rather than bare bytes. A plain Rust BallistaCodec in the scheduler will not strip that envelope. So how does the scheduler decode — does it link PythonLogicalCodec, or does Ballista's codec stay off the chain? I am happy to add whatever hook makes the first option workable; I would rather solve that than work around it.

Proposal: keep #1679 as is, since the file-format gap predates it and is orthogonal, and I will open the upstream issue for (2). If you still want the callback route after the above, let us give it its own issue so the design can be argued on its own terms.

Base automatically changed from feat/ffi-composable-codecs to main September 4, 2026 18:07
timsaucer and others added 8 commits September 4, 2026 14:07
Installing FFI extension codecs and query planners by chaining the
existing with_* methods can bind task-context providers to intermediate
contexts that are later collected, breaking the weak provider reference
over the FFI boundary. with_extensions creates one destination context,
passes it to each extension factory so components bind to that exact
context, and installs everything in a single state write.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
MyPlannerExtension in the query-planner example crate implements the
__datafusion_session_extension__ protocol from Rust: it extracts the
destination context's task-context provider, binds fresh observing
codecs and a planner to it, and returns SessionExtensionComponents. Its
codecs record the max_rows config value resolved through the weak
provider, letting tests prove the provider targets the returned context
rather than the source. Documents with_extensions as the preferred API
in the FFI guide.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
A DataFrame does not keep its SessionContext alive. FFI components hold
a weak task-context provider, so operations that reach an FFI codec
after the context is collected fail with a clean out-of-scope error
rather than crashing. Lock that behavior in with a test and document
the ownership contract in the FFI guide and with_extensions docstring.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Single-underscore methods on internal pyo3 classes (such as
SessionContext._install_extensions) are private support methods for the
Python wrappers and do not require a public wrapper.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
A codec-only bundle installed on a context that already holds an FFI
planner must rebind that planner to the new chains, so the planner
decodes through the bundle's codecs.

Codec ids are derived from the exporting class, so two bundles shipping
the same codec class collide and the install is refused. Declaring
__datafusion_codec_id__ on the object a bundle hands over resolves it,
and both chains then install.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The docs build runs Sphinx with --fail-on-warning. SessionExtensionComponents
documented its fields in both a napoleon `Attributes:` section and the dataclass
class-body annotations, so autoapi emitted each field twice and the build failed
with six "duplicate object description" warnings.

Move each field's description to a per-field docstring under its annotation so
autoapi renders exactly one entry per field.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
QueryPlannerExportable, SessionExtensionComponents, and
SessionExtensionExportable describe how an extension library plugs into a
session, not how a SessionContext behaves. Give them their own module so
context.py does not keep absorbing the extension surface as it grows.

extensions.py imports SessionContext, the codec protocols, and CapsuleType
under TYPE_CHECKING only, so context.py can import from it at runtime
without a cycle. All three names remain importable from datafusion and
datafusion.context; QueryPlannerExportable stays out of the top-level
__all__ as before.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The example was marked `+SKIP` because the main suite has no built FFI
extension to import, which is exactly how such an example rots. Parse the
statements out of the live docstring in the query-planner example suite,
drop the skip, and execute each one against a real extension bundle. Only
names are redirected: `my_extension` resolves to a stand-in combining this
repository's provider codecs and planner, and `SessionContext` supplies the
config that planner reads. A renamed method, a changed signature, or a wrong
expected output now fails CI, which already runs this suite.

Also drop the `extensions` Args entry's restatement of the type hint and
say instead what the hint does not: install order is chain order.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
timsaucer and others added 4 commits September 4, 2026 15:43
`_derive_for_extensions` minted a new `Arc<SessionContext>` via
`new_with_state(self.ctx.state())`. Every other `with_*` method shares
`Arc::clone(&self.ctx)`, and `new_with_state` carries the session id over, so
`with_extensions` returned a second live session claiming the same
`session_id()` as the source while holding independent `SessionState`.
Configuration and the function registry diverged, catalogs stayed shared, and
both handles reported the same `__datafusion_codec_id__` — which is
`session:<session_id>` and exists precisely to distinguish codec chains, so
installing both on a third session was refused as a duplicate id.

The fork also bought nothing. It was introduced to keep components from binding
to an intermediate context that could be collected, but there is one
`Arc<SessionContext>` per session, so no such intermediate exists; deriving one
is what creates the hazard. Rule 6 of the ffi-capsule-protocol skill already
said to mutate `SessionState` in place rather than derive a replacement.

Delete `_derive_for_extensions` and hand the receiver to the extension
factories. `_install_extensions` already returned a handle sharing
`Arc::clone(&slf.borrow().ctx)`, so removing the fork upstream of it is the
whole change. Atomicity is unaffected: both codec chains are built as locals and
state is written exactly once, at the end, in `set_session_query_planner`.

Replace `test_with_extensions_provider_targets_returned_context`, which is
vacuous once the session is shared, with
`test_with_extensions_shares_the_session_with_the_source`. It asserts matching
session ids and that a `SET` issued through the source after installation is
visible to the provider the bundle bound. Reintroducing the fork fails it.

Update the prose that described the fork-era design: the `with_extensions`
docstring and `SessionExtensionComponents` / `SessionExtensionExportable` in
`datafusion.extensions`, the `with_extensions` and "What a derived context
shares" sections of the FFI guide, the query planner example's README and
`extension.rs` comments, and two test docstrings. Note the shared-session
mechanism in Rule 6 of the skill, since `with_extensions` is where it is
easiest to get wrong.

`enable_url_table` is once again the only method that mints a second
`Arc<SessionContext>` for a session; its comment, the FFI guide, and the skill
now also record that it forks state while keeping the session id, tracked as a
bug in #1708.

Also add the missing doctest to `SessionExtensionComponents` and a pointer to
`with_extensions` from the upgrade guide, which described only the low-level
install path.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A codec handed to `with_extensions` as a bare `PyCapsule` fell through to
`anon:<uuid4>`, an id private to the session that installed it. Plans written
through it are undecodable anywhere else, and `with_extensions` accepts no
`codec_id=` to override that — so the workaround was to wrap the capsule in an
object declaring `__datafusion_codec_id__`, which nothing documented. A
distributed engine has to decode its plans in another process, so the shape it
would naturally ship — a Rust bundle handing over capsules, as
`MyPlannerExtension` does — was the one shape that could not work.

The bundle is the stable name that was missing. It is a plain Python object, so
its `module.QualName` is library-owned and exactly as stable across processes as
an exporting codec class's, which arm 3 of `derive_codec_id` already trusts. The
capsule was unnameable only because a capsule carries no type of its own, not
because nothing stable was in reach.

Resolve a capsule's id through the contributing bundle, using `derive_codec_id`
itself so the bundle inherits the same `__datafusion_codec_id__` escape hatch
against a class rename. The fallback applies only where randomness would have:
an id declared on the handed-over object, or that object's own class, still
wins, so an extension can name a codec directly.

Two bare capsules of one kind from one bundle collide and are refused. Numbering
them by position would be exactly the id `codec.rs` rejects for `anon:` — one
another library can mint the same value from — and would break stored plans the
first time the bundle reordered what it returns.

`resolve_codec_id` gains the bundle argument, `_install_extensions` takes
(codec, bundle) pairs, and the collision message now names both routes to a
distinct identity; it previously offered only `codec_id=`, which is unreachable
from `with_extensions`.

Covered in `python/tests/test_context.py`, which reaches every arm without a
built extension library: the bundle-derived name, an extension pinning its own
id, an id on the handed-over object winning, an exporting object keeping its
own, and the two-capsule collision. The cross-FFI case is pinned in the query
planner example, where a Rust bundle's capsules must report
`datafusion_ffi_query_planner_example.MyPlannerExtension` and no id may be
`anon:`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The doc comment said "the final state is written through this context's own
`state_ref()`", which overstates it. `set_session_query_planner` returns early
when there is no planner to bind, and the codec chains live on the returned
`PySessionContext` fields rather than in `SessionState` — so a codec-only
install onto a session with no FFI planner writes nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Mark `SessionExtensionExportable` `@runtime_checkable` and have
`with_extensions` check it with `isinstance` rather than `hasattr`, so the
annotation and the runtime check are the same statement, and callers can ask
the question too. Covered by a doctest on the protocol.

Replace the leading-underscore skip in `test_wrapper_coverage` with a named
allowlist. The pattern also excused `DataFrame._repr_html_`, which a wrapper
does have to provide, so a two-method need was weakening coverage for every
private name. Removing `_install_extensions` from the allowlist fails the test,
so the entry is load-bearing rather than decorative.

Say in `_CodecOnlyExtension` that retaining the context is what the protocol
tells real extensions not to do, and that it is kept only so a test can assert
which context the factory was handed.

Let the docstring-example shim in the query planner example accept a config
positionally, the way the real constructor does. Editing the docstring to
`SessionContext(config)` now fails as a doctest diff rather than as a
`TypeError` inside the harness.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@timsaucer
timsaucer marked this pull request as draft September 4, 2026 20:31
@timsaucer timsaucer changed the title Add atomic SessionContext.with_extensions API Add method on SessionContext to add all extensions from one library Sep 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants