You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by ti...@apache.org on 2026/09/15 14:25:54 UTC

(datafusion-python) 01/01: feat: let extension bundles declare catalog providers

This is an automated email from the ASF dual-hosted git repository.

timsaucer pushed a commit to branch feat/bundle-catalogs
in repository https://gitbox.apache.org/repos/asf/datafusion-python.git

commit 04a96500c7c8c2d18a63734da6fc57646ad8ce7b
Author: Tim Saucer <ti...@gmail.com>
AuthorDate: Tue Sep 15 10:25:44 2026 -0400

    feat: let extension bundles declare catalog providers
    
    `SessionExtensionComponents.catalog_providers` completes the set #1676 asked
    for, minus object stores, which have no FFI type upstream and are tracked
    separately in #1737.
    
    `register_catalog_provider` had its import and its insert in one function with
    no split point, so the import half moves to a shared `resolve_catalog_provider`
    that both it and the new `_resolve_extension_catalogs` call. Both therefore
    accept exactly the same shapes, and the bundle path gets the same treatment as
    tables: imported against the handle carrying the finished codec chains, since
    the getter is handed the logical codec its provider will serialize through.
    
    Catalogs replace rather than collide. `register_catalog` returns whichever
    provider it displaced, and the default `datafusion` catalog always exists, so a
    library backing a session with its own metadata has to be able to replace one.
    Only two bundles claiming a name in the same call is refused. That is the
    opposite of tables, where a duplicate is an error, and both now say so where a
    reader meets them.
    
    `_install_extension_catalogs` returns `()`: nothing is left that can fail once
    the providers are imported.
    
    Rules 2 and 6 of the capsule-protocol skill now carry the two conventions the
    stack established — which components a bundle hands over unwrapped and why, and
    that a new component means a new resolve step rather than a fallible commit
    step.
    
    Closes #1676.
    
    Co-Authored-By: Claude Opus 5 (1M context) <no...@anthropic.com>
---
 .ai/skills/ffi-capsule-protocol/SKILL.md           |  31 ++++++
 crates/core/src/context.rs                         | 118 +++++++++++++++-----
 docs/source/extension-guide/bundles.md             |  14 +--
 docs/source/extension-guide/table-providers.md     |  14 +++
 .../python/tests/_test_session_extension.py        |  37 +++++++
 examples/datafusion-ffi-example/src/extension.rs   |  41 +++++++
 examples/datafusion-ffi-example/src/lib.rs         |   3 +-
 python/datafusion/context.py                       |  14 +++
 python/datafusion/extensions.py                    |  13 +++
 python/tests/test_context.py                       | 119 +++++++++++++++++++++
 python/tests/test_wrapper_coverage.py              |   3 +
 11 files changed, 371 insertions(+), 36 deletions(-)

diff --git a/.ai/skills/ffi-capsule-protocol/SKILL.md b/.ai/skills/ffi-capsule-protocol/SKILL.md
index 37be0bc9..ab14dc73 100644
--- a/.ai/skills/ffi-capsule-protocol/SKILL.md
+++ b/.ai/skills/ffi-capsule-protocol/SKILL.md
@@ -76,6 +76,25 @@ receiver had — the same session, and the same task-context provider, but not
 this call's codecs, not even your own. Read the host's codec chains in the
 planner hook, never in the extension hook.
 
+**That is why a bundle declares unresolved components, not wrapped ones.** The
+components it returns split by what their getter asks for:
+
+- Getters taking no argument — the three function kinds,
+  `__datafusion_physical_optimizer_rule__` — have nothing session-scoped to
+  bind, so a bundle may hand over either the raw exportable or an
+  already-wrapped object.
+- Getters taking the session or a codec — `__datafusion_table_function__`,
+  `__datafusion_table_provider__`, `__datafusion_catalog_provider__` — must be
+  handed over **unwrapped**, with a name. Wrapping one inside the components
+  hook would call its getter with the `ctx` that hook received, capturing a
+  chain missing every library in the call. The host wraps these itself, against
+  the handle carrying the final chains, which is the only place that chain
+  exists.
+
+`RecordingTableFunction` in `examples/datafusion-ffi-example/src/extension.rs`
+records the ids it was resolved against, so the difference is asserted rather
+than described.
+
 A *codec* must always be handed over as an object implementing its getter, never
 as the bare capsule the getter returns; `with_extensions` refuses a capsule.
 A codec's wire id — the string a payload names on decode, which has to mean the
@@ -187,6 +206,18 @@ an instruction to derive one first. It is not: the factories are handed the
 receiver, and the returned handle shares its allocation. There is nothing to
 keep alive separately and nothing to garbage-collect out from under a provider.
 
+It is also the one place where sharing an allocation has a cost, and the cost
+shapes how a component is added to it. Because the returned handle *is* the
+receiver's session, a failure part-way through has nothing to roll back to. So
+`with_extensions` does every fallible thing first — importing capsules,
+resolving names, running the planner hooks — and only then writes. **Adding a
+new kind of component means adding a resolve step, never a fallible commit
+step:** a `_resolve_extension_*` that returns an opaque carrier and an
+`_install_extension_*` that takes it and returns `()`. The one exception is
+table registration, whose insert goes through a `SchemaProvider` that a foreign
+library may implement; it is committed first so nothing else is written behind
+it. Do not add a second exception without the same justification.
+
 `SessionContext.enable_url_table` is the one method that mints a second
 allocation for a session. Its result must not outlive the receiver, and it also
 forks the session's `SessionState` while keeping its id, so two handles report
diff --git a/crates/core/src/context.rs b/crates/core/src/context.rs
index 63126b05..fe7ea762 100644
--- a/crates/core/src/context.rs
+++ b/crates/core/src/context.rs
@@ -842,35 +842,9 @@ impl PySessionContext {
     pub fn register_catalog_provider(
         &self,
         name: &str,
-        mut provider: Bound<'_, PyAny>,
+        provider: Bound<'_, PyAny>,
     ) -> PyDataFusionResult<()> {
-        if provider.hasattr("__datafusion_catalog_provider__")? {
-            let py = provider.py();
-            let ffi = self.ffi_logical_codec();
-            let codec_capsule = create_logical_extension_capsule(py, ffi.as_ref())?;
-            provider = call_capsule_getter(
-                provider,
-                "__datafusion_catalog_provider__",
-                CapsuleGetterArg::LogicalCodec(&codec_capsule),
-            )?;
-        }
-
-        let provider = if let Ok(capsule) = provider.cast::<PyCapsule>() {
-            let data: NonNull<FFI_CatalogProvider> = capsule
-                .pointer_checked(Some(c"datafusion_catalog_provider"))?
-                .cast();
-            let provider = unsafe { data.as_ref() };
-            let provider: Arc<dyn CatalogProvider> = provider.into();
-            provider
-        } else {
-            match provider.extract::<PyCatalog>() {
-                Ok(py_catalog) => py_catalog.catalog,
-                Err(_) => Arc::new(RustWrappedPyCatalogProvider::new(
-                    provider.into(),
-                    self.ffi_logical_codec(),
-                )) as Arc<dyn CatalogProvider>,
-            }
-        };
+        let provider = self.resolve_catalog_provider(provider)?;
 
         let _ = self.ctx.register_catalog(name, provider);
 
@@ -1828,6 +1802,42 @@ impl PySessionContext {
         Ok(())
     }
 
+    /// Resolve the catalogs a `with_extensions` call declared.
+    ///
+    /// The fallible half. Each provider is imported against `self` — the handle
+    /// carrying the completed codec chains, since
+    /// `__datafusion_catalog_provider__` is handed the logical codec it will
+    /// serialize through.
+    ///
+    /// No name is refused here. `register_catalog` replaces rather than
+    /// rejects, and `datafusion` — the default catalog — always exists, so a
+    /// bundle replacing a catalog is ordinary rather than a mistake. Two
+    /// bundles claiming one name in the same call is refused on the Python
+    /// side, where both can be named.
+    ///
+    /// **Writes nothing.**
+    pub fn _resolve_extension_catalogs<'py>(
+        &self,
+        catalogs: Vec<(String, Bound<'py, PyAny>)>,
+    ) -> PyDataFusionResult<PyResolvedCatalogs> {
+        let catalogs = catalogs
+            .into_iter()
+            .map(|(name, provider)| Ok((name, self.resolve_catalog_provider(provider)?)))
+            .collect::<PyDataFusionResult<Vec<_>>>()?;
+        Ok(PyResolvedCatalogs { catalogs })
+    }
+
+    /// Commit the catalogs for a `with_extensions` call.
+    ///
+    /// Nothing here can fail: the providers were imported by
+    /// [`Self::_resolve_extension_catalogs`], and `register_catalog` returns
+    /// whichever provider it displaced rather than refusing.
+    pub fn _install_extension_catalogs(&self, resolved: PyRef<'_, PyResolvedCatalogs>) {
+        for (name, provider) in &resolved.catalogs {
+            let _ = self.ctx.register_catalog(name, Arc::clone(provider));
+        }
+    }
+
     /// Import the physical optimizer rules a `with_extensions` call declared.
     ///
     /// The fallible half of installing them, run while the call can still fail
@@ -1900,6 +1910,14 @@ struct ResolvedTable {
     provider: Arc<dyn TableProvider>,
 }
 
+/// Catalog providers imported for a `with_extensions` call.
+///
+/// Opaque to Python, like [`PyResolvedTables`] and [`PyPhysicalOptimizerRules`].
+#[pyclass(name = "ResolvedCatalogs", module = "datafusion._internal")]
+pub struct PyResolvedCatalogs {
+    catalogs: Vec<(String, Arc<dyn CatalogProvider>)>,
+}
+
 /// Physical optimizer rules imported for a `with_extensions` call.
 ///
 /// Opaque to Python, and deliberately not added to the module: it exists only
@@ -1912,6 +1930,50 @@ pub struct PyPhysicalOptimizerRules {
 }
 
 impl PySessionContext {
+    /// Turn whatever a caller offered as a catalog provider into one.
+    ///
+    /// The fallible half of registering a catalog, shared by
+    /// [`Self::register_catalog_provider`] and
+    /// [`Self::_resolve_extension_catalogs`] so both accept exactly the same
+    /// shapes: an object exposing `__datafusion_catalog_provider__`, a bare
+    /// capsule, a [`PyCatalog`], or a Python object implementing the provider
+    /// interface.
+    ///
+    /// The getter is handed **this context's** logical codec, so which handle
+    /// this is called on decides what the provider will serialize through.
+    fn resolve_catalog_provider(
+        &self,
+        mut provider: Bound<'_, PyAny>,
+    ) -> PyDataFusionResult<Arc<dyn CatalogProvider>> {
+        if provider.hasattr("__datafusion_catalog_provider__")? {
+            let py = provider.py();
+            let ffi = self.ffi_logical_codec();
+            let codec_capsule = create_logical_extension_capsule(py, ffi.as_ref())?;
+            provider = call_capsule_getter(
+                provider,
+                "__datafusion_catalog_provider__",
+                CapsuleGetterArg::LogicalCodec(&codec_capsule),
+            )?;
+        }
+
+        Ok(if let Ok(capsule) = provider.cast::<PyCapsule>() {
+            let data: NonNull<FFI_CatalogProvider> = capsule
+                .pointer_checked(Some(c"datafusion_catalog_provider"))?
+                .cast();
+            let provider = unsafe { data.as_ref() };
+            let provider: Arc<dyn CatalogProvider> = provider.into();
+            provider
+        } else {
+            match provider.extract::<PyCatalog>() {
+                Ok(py_catalog) => py_catalog.catalog,
+                Err(_) => Arc::new(RustWrappedPyCatalogProvider::new(
+                    provider.into(),
+                    self.ffi_logical_codec(),
+                )) as Arc<dyn CatalogProvider>,
+            }
+        })
+    }
+
     /// Write the session's query planner, in place.
     ///
     /// Pass `Some(planner)` to install one, or `None` to rebuild whichever
diff --git a/docs/source/extension-guide/bundles.md b/docs/source/extension-guide/bundles.md
index ac25193d..2a3114a5 100644
--- a/docs/source/extension-guide/bundles.md
+++ b/docs/source/extension-guide/bundles.md
@@ -336,13 +336,13 @@ where the host can resolve them:
 - **Getters taking no argument** — the three function kinds and physical
   optimizer rules. Nothing is session-scoped, so a bundle may hand over either
   a wrapped object or the raw exportable.
-- **Getters taking the session or a codec** — table functions and table
-  providers. These are resolved by the host against the *finished* handle, in
-  step 3, which is why you hand over the unwrapped value and a name rather than
-  a {py:class}`~datafusion.user_defined.TableFunction` you built yourself.
-  Wrapping one inside your components hook binds it to the context that hook
-  received, which has none of the call's codecs — so it would capture a chain
-  missing every library in the call, including your own.
+- **Getters taking the session or a codec** — table functions, table providers,
+  and catalog providers. These are resolved by the host against the *finished*
+  handle, in step 3, which is why you hand over the unwrapped value and a name
+  rather than a {py:class}`~datafusion.user_defined.TableFunction` you built
+  yourself. Wrapping one inside your components hook binds it to the context
+  that hook received, which has none of the call's codecs — so it would capture
+  a chain missing every library in the call, including your own.
 
 (extension_bundles_collisions)=
 
diff --git a/docs/source/extension-guide/table-providers.md b/docs/source/extension-guide/table-providers.md
index 700ca195..9e09e6a8 100644
--- a/docs/source/extension-guide/table-providers.md
+++ b/docs/source/extension-guide/table-providers.md
@@ -51,6 +51,20 @@ wrapped: `__datafusion_table_provider__` takes the session, and the one your
 components hook receives has none of the call's codecs yet. The host resolves
 it against the finished handle. See {ref}`extension_bundles_binding`.
 
+Catalogs work the same way, as `catalog_providers`:
+
+```python
+return SessionExtensionComponents(catalog_providers=(("engine", MyCatalog()),))
+```
+
+with one difference worth knowing. A declared **table** name that is already
+registered is an error, because DataFusion refuses a duplicate table rather
+than replacing it. A **catalog** name is not: `register_catalog` returns
+whichever provider it displaced, and the default `datafusion` catalog always
+exists — so replacing one is the usual way a library backs a session with its
+own metadata. Only two bundles claiming the same catalog name in one call is
+refused.
+
 Start with a table provider. Reach for the schema and catalog levels when your
 data source has its own namespace that should be browsable rather than
 registered table by table, and for the provider list only when your library is
diff --git a/examples/datafusion-ffi-example/python/tests/_test_session_extension.py b/examples/datafusion-ffi-example/python/tests/_test_session_extension.py
index 02f7ddd3..bf1c3653 100644
--- a/examples/datafusion-ffi-example/python/tests/_test_session_extension.py
+++ b/examples/datafusion-ffi-example/python/tests/_test_session_extension.py
@@ -23,6 +23,7 @@ import pyarrow as pa
 import pytest
 from datafusion import SessionContext, SessionExtensionComponents
 from datafusion_ffi_example import (
+    MyCatalogExtension,
     MyDataExtension,
     MyFunctionExtension,
     MyLogicalExtensionCodec,
@@ -237,6 +238,42 @@ def test_a_table_name_already_registered_is_refused():
         ctx.udf("my_custom_is_null")
 
 
+def test_a_declared_catalog_is_queryable():
+    """A catalog declared by a bundle is reachable by its qualified name."""
+    ctx = SessionContext().with_extensions(MyCatalogExtension())
+
+    assert "declared_catalog" in ctx.catalog_names()
+    result = ctx.sql("SELECT * FROM declared_catalog.my_schema.my_table").collect()
+    assert result[0].num_rows > 0
+
+
+def test_four_libraries_install_in_one_call():
+    """The whole point, across a real FFI boundary.
+
+    Four independently declared bundles — functions, rules, a table and a table
+    function, a catalog — in one call, and a single query that touches three of
+    them while the fourth counts the planning it did.
+    """
+    rules = MyRuleExtension()
+    ctx = SessionContext().with_extensions(
+        MyFunctionExtension(),
+        rules,
+        MyDataExtension(),
+        MyCatalogExtension(),
+    )
+
+    result = ctx.sql(
+        'SELECT my_custom_is_null("A") AS n FROM declared_table '
+        "UNION ALL "
+        "SELECT my_custom_is_null(units) AS n "
+        "FROM declared_catalog.my_schema.my_table"
+    ).collect()
+
+    assert sum(batch.num_rows for batch in result) > 0
+    assert rules.first_calls() > 0
+    assert rules.second_calls() > 0
+
+
 def test_the_hook_returns_the_components_type():
     """The bundle builds a real dataclass, not a duck-typed stand-in.
 
diff --git a/examples/datafusion-ffi-example/src/extension.rs b/examples/datafusion-ffi-example/src/extension.rs
index 85d8a5ad..1a51d0ee 100644
--- a/examples/datafusion-ffi-example/src/extension.rs
+++ b/examples/datafusion-ffi-example/src/extension.rs
@@ -21,6 +21,7 @@ use pyo3::prelude::*;
 use pyo3::types::{PyCapsule, PyDict};
 
 use crate::aggregate_udf::MySumUDF;
+use crate::catalog_provider::MyCatalogProvider;
 use crate::physical_optimizer::MyPhysicalOptimizerRule;
 use crate::scalar_udf::IsNullUDF;
 use crate::table_function::MyTableFunction;
@@ -230,3 +231,43 @@ impl MyDataExtension {
         components.call((), Some(&kwargs))
     }
 }
+
+/// A bundle contributing a catalog.
+///
+/// `__datafusion_catalog_provider__` takes the session and pulls the host's
+/// logical codec off it, so like a table provider it is handed over unresolved
+/// and the host binds it to the finished handle.
+#[pyclass(
+    from_py_object,
+    name = "MyCatalogExtension",
+    module = "datafusion_ffi_example",
+    subclass
+)]
+#[derive(Debug, Clone, Default)]
+pub(crate) struct MyCatalogExtension {}
+
+#[pymethods]
+impl MyCatalogExtension {
+    #[new]
+    fn new() -> Self {
+        Self {}
+    }
+
+    fn __datafusion_session_components__<'py>(
+        &self,
+        py: Python<'py>,
+        ctx: Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, PyAny>> {
+        let _ = ctx;
+
+        let components = py
+            .import("datafusion")?
+            .getattr("SessionExtensionComponents")?;
+        let kwargs = PyDict::new(py);
+        kwargs.set_item(
+            "catalog_providers",
+            (("declared_catalog", Py::new(py, MyCatalogProvider::new()?)?),),
+        )?;
+        components.call((), Some(&kwargs))
+    }
+}
diff --git a/examples/datafusion-ffi-example/src/lib.rs b/examples/datafusion-ffi-example/src/lib.rs
index 25ebb2f3..a7dceb3e 100644
--- a/examples/datafusion-ffi-example/src/lib.rs
+++ b/examples/datafusion-ffi-example/src/lib.rs
@@ -20,7 +20,7 @@ use pyo3::prelude::*;
 use crate::aggregate_udf::MySumUDF;
 use crate::catalog_provider::{FixedSchemaProvider, MyCatalogProvider, MyCatalogProviderList};
 use crate::config::MyConfig;
-use crate::extension::{MyDataExtension, MyFunctionExtension, MyRuleExtension};
+use crate::extension::{MyCatalogExtension, MyDataExtension, MyFunctionExtension, MyRuleExtension};
 use crate::logical_extension_codec::MyLogicalExtensionCodec;
 use crate::name_only_codec::{NameOnlyFunction, NameOnlyUdfCodec};
 use crate::physical_extension_codec::MyPhysicalExtensionCodec;
@@ -68,5 +68,6 @@ fn datafusion_ffi_example(m: &Bound<'_, PyModule>) -> PyResult<()> {
     m.add_class::<MyFunctionExtension>()?;
     m.add_class::<MyRuleExtension>()?;
     m.add_class::<MyDataExtension>()?;
+    m.add_class::<MyCatalogExtension>()?;
     Ok(())
 }
diff --git a/python/datafusion/context.py b/python/datafusion/context.py
index 475d3ce8..5054e65e 100644
--- a/python/datafusion/context.py
+++ b/python/datafusion/context.py
@@ -231,6 +231,7 @@ def _collect_contributions(
         "udwfs": [],
         "udtfs": [],
         "table_providers": [],
+        "catalog_providers": [],
         "physical_optimizer_rules": [],
     }
     for extension in extensions:
@@ -2198,6 +2199,18 @@ class SessionContext:
                 )
             ]
         )
+        # Bound to `new` for the same reason: the catalog getter is handed the
+        # logical codec its provider will serialize through. Unlike a table a
+        # catalog may replace one the session holds, so only names claimed
+        # twice within the call are refused.
+        resolved_catalogs = new.ctx._resolve_extension_catalogs(
+            [
+                pair
+                for _, pair in _reject_repeated_names(
+                    declared["catalog_providers"], "catalog"
+                )
+            ]
+        )
         # Rules accumulate, so there is no name to check and nothing to refuse
         # -- only the capsules to import while failing is still free.
         resolved_rules = new.ctx._resolve_extension_physical_optimizer_rules(
@@ -2250,6 +2263,7 @@ class SessionContext:
             new.register_udwf(function)
         for table_function in resolved_udtfs:
             new.register_udtf(table_function)
+        new.ctx._install_extension_catalogs(resolved_catalogs)
         new.ctx._install_extension_physical_optimizer_rules(resolved_rules)
         return new
 
diff --git a/python/datafusion/extensions.py b/python/datafusion/extensions.py
index 0aa9ee81..8a389c4d 100644
--- a/python/datafusion/extensions.py
+++ b/python/datafusion/extensions.py
@@ -327,6 +327,19 @@ class SessionExtensionComponents:
     replacing it, so unlike a function a table cannot shadow one.
     """
 
+    catalog_providers: tuple[tuple[str, Any], ...] = _components("catalog")
+    """Catalogs to register, as ``(name, provider)`` pairs.
+
+    Anything
+    :py:meth:`~datafusion.context.SessionContext.register_catalog_provider`
+    accepts. Bound to the finished context like :py:attr:`table_providers`.
+
+    Two extensions claiming one name in the same call is refused. Replacing a
+    catalog the session already has is not — the default ``datafusion`` catalog
+    always exists, and swapping it is the usual way a library backs a session
+    with its own metadata.
+    """
+
     physical_optimizer_rules: tuple[PhysicalOptimizerRuleExportable, ...] = _components(
         "optimizer rule"
     )
diff --git a/python/tests/test_context.py b/python/tests/test_context.py
index 67a9c53c..856638b9 100644
--- a/python/tests/test_context.py
+++ b/python/tests/test_context.py
@@ -21,6 +21,7 @@ import gzip
 import pathlib
 import shutil
 
+import datafusion.catalog
 import pyarrow as pa
 import pyarrow.compute as pc
 import pyarrow.dataset as ds
@@ -1674,6 +1675,124 @@ def test_with_extensions_rejects_a_table_in_an_unknown_schema(ctx):
         ctx.udf("double")
 
 
+class _Schema(datafusion.catalog.SchemaProvider):
+    """One table, enough to prove a declared catalog is reachable from SQL."""
+
+    def __init__(self, table):
+        self.tables = {"t": table}
+
+    def table_names(self) -> set[str]:
+        return set(self.tables)
+
+    def register_table(self, name, table):
+        self.tables[name] = table
+
+    def deregister_table(self, name, cascade: bool = True):
+        del self.tables[name]
+
+    def table(self, name):
+        return self.tables.get(name)
+
+    def table_exist(self, name) -> bool:
+        return name in self.tables
+
+
+class _Catalog(datafusion.catalog.CatalogProvider):
+    def __init__(self, table):
+        self.schemas = {"s": _Schema(table)}
+
+    def schema_names(self) -> set[str]:
+        return set(self.schemas)
+
+    def schema(self, name):
+        return self.schemas.get(name)
+
+    def register_schema(self, name, schema):
+        self.schemas[name] = schema
+
+    def deregister_schema(self, name, cascade: bool):
+        del self.schemas[name]
+
+
+class _CatalogExtension:
+    """Contributes catalogs as ``(name, provider)`` pairs."""
+
+    def __init__(self, catalog_providers=()):
+        self._catalog_providers = catalog_providers
+
+    def __datafusion_session_components__(self, ctx):
+        return SessionExtensionComponents(catalog_providers=self._catalog_providers)
+
+
+def test_with_extensions_registers_a_declared_catalog(ctx):
+    """A declared catalog is queryable through its qualified name."""
+    table = ctx.from_pydict({"a": [1, 2, 3]}).into_view()
+
+    result = ctx.with_extensions(
+        _CatalogExtension(catalog_providers=(("engine", _Catalog(table)),))
+    )
+
+    assert "engine" in result.catalog_names()
+    assert (
+        result.sql("SELECT sum(a) FROM engine.s.t").collect()[0].column(0)[0].as_py()
+        == 6
+    )
+
+
+def test_with_extensions_rejects_a_catalog_two_extensions_claim(ctx):
+    """One name, two bundles: refused with both named."""
+    table = ctx.from_pydict({"a": [1]}).into_view()
+
+    with pytest.raises(ValueError, match=r"catalog named 'engine'"):
+        ctx.with_extensions(
+            _CatalogExtension(catalog_providers=(("engine", _Catalog(table)),)),
+            _CatalogExtension(catalog_providers=(("engine", _Catalog(table)),)),
+        )
+
+    assert "engine" not in ctx.catalog_names()
+
+
+def test_with_extensions_allows_replacing_an_existing_catalog(ctx):
+    """Replacing a catalog the session holds is ordinary, unlike a table.
+
+    ``register_catalog`` returns whichever provider it displaced rather than
+    refusing, and the default ``datafusion`` catalog always exists — so a
+    library backing a session with its own metadata has to be able to do this.
+    """
+    table = ctx.from_pydict({"a": [1, 2, 3]}).into_view()
+
+    result = ctx.with_extensions(
+        _CatalogExtension(catalog_providers=(("datafusion", _Catalog(table)),))
+    )
+
+    assert (
+        result.sql("SELECT sum(a) FROM datafusion.s.t")
+        .collect()[0]
+        .column(0)[0]
+        .as_py()
+        == 6
+    )
+
+
+def test_with_extensions_registers_no_catalog_when_a_later_hook_raises(ctx):
+    """Catalogs share the transaction, even though they write to a shared list."""
+
+    class BoomPlanner:
+        def __datafusion_session_planner__(self, ctx, fallback):
+            msg = "boom"
+            raise RuntimeError(msg)
+
+    table = ctx.from_pydict({"a": [1]}).into_view()
+
+    with pytest.raises(RuntimeError, match="boom"):
+        ctx.with_extensions(
+            _CatalogExtension(catalog_providers=(("engine", _Catalog(table)),)),
+            BoomPlanner(),
+        )
+
+    assert "engine" not in ctx.catalog_names()
+
+
 def test_session_extension_components_rejects_a_single_optimizer_rule():
     """The same for rules, naming what that field holds."""
     with pytest.raises(
diff --git a/python/tests/test_wrapper_coverage.py b/python/tests/test_wrapper_coverage.py
index 4b50606c..2bd4ec94 100644
--- a/python/tests/test_wrapper_coverage.py
+++ b/python/tests/test_wrapper_coverage.py
@@ -47,6 +47,9 @@ PRIVATE_SUPPORT_METHODS = frozenset(
         # destination schema during resolution, insert at commit.
         "_resolve_extension_tables",
         "_install_extension_tables",
+        # Catalogs, sharing their import half with register_catalog_provider.
+        "_resolve_extension_catalogs",
+        "_install_extension_catalogs",
     }
 )
 


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org