From d8d8873a288f8b3798ae9bf06bc9b1101cf74898 Mon Sep 17 00:00:00 2001 From: Noah Date: Fri, 4 Dec 2026 07:44:57 -0500 Subject: [PATCH 1/2] fix: see tables other clients create or drop after the catalog is built `IcebergCatalogProvider` lists each namespace's tables once, when it is built, and `table()` returned `None` for any name not in that list. A long-lived session (a server, a notebook) never saw tables created by other engines until it was rebuilt, and a table another client dropped stayed listed and failed every lookup with `TableNotFound`, which also broke `information_schema.columns` for the whole catalog. The catalog, not the build-time list, now decides whether a table exists: - `table()` in a namespace built by listing the catalog also loads names missing from the list. Every catalog-backed lookup, including fixed sets (`with_fixed_tables`), returns `None` when the catalog reports `TableNotFound` or `NamespaceNotFound`. Fixed sets keep their membership otherwise. - `register_table` no longer refuses names on the list. It refused to recreate a table another client had dropped ("already exists"); the catalog reports real duplicates itself. - `deregister_table` loads the table from the catalog instead of checking the list. `DROP TABLE` looks a table up with `table()` and then calls `deregister_table`, ignoring its result, so dropping a table found only through the catalog would have reported success and dropped nothing. Both now reject names containing `$`, which `table()` reads as a metadata table (`t$snapshots`). The list checks used to stop some of these by accident; `CREATE TABLE "x$snapshots"` with no table `x` created a table that could never be read. The listing itself (`SHOW TABLES`, `information_schema.tables`) still reflects the build plus DDL through this provider: `table_names` is synchronous. Namespaces are still listed once. The Hive Metastore catalog reports a missing table as `Unexpected`, so there a dropped table still fails its lookup. --- crates/datafusion/src/catalog/schema.rs | 81 ++++++++--- crates/datafusion/tests/table_lookup.rs | 181 +++++++++++++++++++++++- 2 files changed, 236 insertions(+), 26 deletions(-) diff --git a/crates/datafusion/src/catalog/schema.rs b/crates/datafusion/src/catalog/schema.rs index 40492e6..344dddb 100644 --- a/crates/datafusion/src/catalog/schema.rs +++ b/crates/datafusion/src/catalog/schema.rs @@ -21,8 +21,8 @@ use async_trait::async_trait; use dashmap::DashMap; use datafusion::catalog::SchemaProvider; use datafusion::common::{ - config_err, exec_datafusion_err, exec_err, not_impl_datafusion_err, - plan_datafusion_err, + config_err, exec_datafusion_err, exec_err, not_impl_datafusion_err, not_impl_err, + plan_datafusion_err, plan_err, }; use datafusion::datasource::TableProvider; use datafusion::error::Result; @@ -33,7 +33,7 @@ use iceberg::arrow::arrow_schema_to_schema_auto_assign_ids; use iceberg::inspect::MetadataTableType; use iceberg::spec::FormatVersion; use iceberg::table::Table; -use iceberg::{Catalog, NamespaceIdent, TableCreation, TableIdent}; +use iceberg::{Catalog, ErrorKind, NamespaceIdent, TableCreation, TableIdent}; use crate::metadata::IcebergMetadataTableProvider; use crate::table_provider::IcebergTableProvider; @@ -43,7 +43,11 @@ use crate::to_datafusion_error; #[derive(Debug)] pub(crate) struct IcebergSchemaProvider { pub(super) namespace: NamespaceIdent, - ddl_catalog: Option>, + /// Set when the namespace's tables are whatever its catalog holds: lookups + /// of names not in `tables`, and DDL, go to it. `None` for a fixed set. + catalog: Option>, + /// The tables listed when the namespace was built, kept up to date by DDL + /// through it but not by other clients. tables: Arc>, } @@ -58,7 +62,7 @@ impl IcebergSchemaProvider { pub(super) fn fixed(namespace: NamespaceIdent) -> Self { Self { namespace, - ddl_catalog: None, + catalog: None, tables: Arc::default(), } } @@ -72,7 +76,7 @@ impl IcebergSchemaProvider { .await .map_err(to_datafusion_error)?; let schema = Self { - ddl_catalog: Some(catalog.clone()), + catalog: Some(catalog.clone()), ..Self::fixed(namespace) }; for id in tables { @@ -102,7 +106,7 @@ impl IcebergSchemaProvider { } fn catalog_for_ddl(&self) -> Result> { - self.ddl_catalog.clone().ok_or_else(|| { + self.catalog.clone().ok_or_else(|| { not_impl_datafusion_err!( "Cannot change membership of a fixed Iceberg table registration in {}", self.namespace @@ -148,13 +152,21 @@ impl SchemaProvider for IcebergSchemaProvider { } None => (name, None), }; - let Some(entry) = self.tables.get(table_name).map(|e| e.value().clone()) else { - return Ok(None); + // A table another client created after the listing isn't in `tables`, + // so look the name up in the catalog unless the set is fixed. + let entry = match self.tables.get(table_name) { + Some(entry) => entry.value().clone(), + None => match &self.catalog { + Some(catalog) => Registration::Live(catalog.clone()), + None => return Ok(None), + }, }; let provider: Arc = match entry { Registration::Live(catalog) => { let id = TableIdent::new(self.namespace.clone(), table_name.into()); - let table = catalog.load_table(&id).await.map_err(to_datafusion_error)?; + let Some(table) = load_if_exists(catalog.as_ref(), &id).await? else { + return Ok(None); + }; match metadata_table_type { Some(kind) => { Arc::new(IcebergMetadataTableProvider::try_new(table, kind)?) @@ -181,9 +193,12 @@ impl SchemaProvider for IcebergSchemaProvider { table: Arc, ) -> Result>> { let catalog = self.catalog_for_ddl()?; - // Check if table already exists - if self.table_exist(name.as_str()) { - return exec_err!("Table {name} already exists"); + // The catalog, not `tables`, knows whether the name is taken: another + // client may have created or dropped it since the listing. + if name.contains('$') { + return plan_err!( + "Iceberg table name {name} can't contain '$', which marks a metadata table" + ); } // Convert DataFusion schema to Iceberg schema @@ -235,9 +250,8 @@ impl SchemaProvider for IcebergSchemaProvider { fn deregister_table(&self, name: &str) -> Result>> { let catalog = self.catalog_for_ddl()?; - // Check if table exists - if !self.table_exist(name) { - return Ok(None); + if name.contains('$') { + return not_impl_err!("Cannot drop Iceberg metadata table {name}"); } let namespace = self.namespace.clone(); @@ -248,11 +262,18 @@ impl SchemaProvider for IcebergSchemaProvider { let result = tokio::task::spawn_blocking(move || { let rt = tokio::runtime::Handle::current(); rt.block_on(async move { - // Load the table before dropping it, to return its provider + // Load the table before dropping it, to return its provider. + // It may not be in `tables`: another client may have created it. let ident = TableIdent::new(namespace, table_name.clone()); - let removed = - IcebergTableProvider::from_catalog(catalog.clone(), ident.clone()) - .await?; + let Some(table) = load_if_exists(catalog.as_ref(), &ident).await? else { + tables.remove(&table_name); + return Ok(None); + }; + let removed = IcebergTableProvider::from_loaded( + catalog.clone(), + ident.clone(), + &table, + )?; catalog .drop_table(&ident) .await @@ -269,6 +290,26 @@ impl SchemaProvider for IcebergSchemaProvider { } } +/// Loads a table, or returns `None` if the catalog has no such table, for +/// example because another client dropped it after the listing. +async fn load_if_exists( + catalog: &dyn Catalog, + ident: &TableIdent, +) -> Result> { + match catalog.load_table(ident).await { + Ok(table) => Ok(Some(table)), + Err(e) + if matches!( + e.kind(), + ErrorKind::TableNotFound | ErrorKind::NamespaceNotFound + ) => + { + Ok(None) + } + Err(e) => Err(to_datafusion_error(e)), + } +} + /// Verifies that a table provider contains no data by scanning with LIMIT 1. /// Returns an error if the table has any rows. async fn ensure_table_is_empty(table: &Arc) -> Result<()> { diff --git a/crates/datafusion/tests/table_lookup.rs b/crates/datafusion/tests/table_lookup.rs index 25b098a..2dbb01f 100644 --- a/crates/datafusion/tests/table_lookup.rs +++ b/crates/datafusion/tests/table_lookup.rs @@ -15,8 +15,9 @@ // specific language governing permissions and limitations // under the License. -//! Each query looks its tables up in the catalog afresh, so it sees changes -//! other clients made to a table's schema after the catalog was registered. +//! Each query looks its tables up in the catalog afresh, so it sees the tables +//! other clients created or dropped, and the changes they made to a table's +//! schema, after the catalog was registered. #[cfg(test)] mod tests { @@ -25,7 +26,7 @@ mod tests { use std::sync::Arc; use datafusion::arrow::util::pretty::pretty_format_batches; - use datafusion::prelude::SessionContext; + use datafusion::prelude::{SessionConfig, SessionContext}; use iceberg::spec::{PrimitiveType, Type}; use iceberg::transaction::{ AddColumn, ApplyTransactionAction, Transaction, UpdateSchemaAction, @@ -54,7 +55,9 @@ mod tests { impl Session { async fn new(fixtures: &FixtureCatalog) -> Result { - let ctx = SessionContext::new(); + let ctx = SessionContext::new_with_config( + SessionConfig::new().with_information_schema(true), + ); let provider = IcebergCatalogProvider::catalog_builder(fixtures.catalog()) .build() .await?; @@ -68,8 +71,8 @@ mod tests { } } - /// Another client of the catalog, changing table `ns.t` as another engine - /// would, without the session knowing. + /// Another client of the catalog, changing it as another engine would, + /// without the session knowing. struct OtherClient { fixtures: FixtureCatalog, } @@ -90,6 +93,12 @@ mod tests { Ok(()) } + async fn drop_namespace(&self, name: &str) -> Result<()> { + let namespace = NamespaceIdent::new(name.to_string()); + self.fixtures.catalog().drop_namespace(&namespace).await?; + Ok(()) + } + /// Runs `sql` in a session of its own, started now. async fn sql(&self, sql: &str) -> Result { Session::new(&self.fixtures).await?.sql(sql).await @@ -185,4 +194,164 @@ mod tests { Ok(()) } + + #[tokio::test] + async fn uses_a_table_another_client_created() -> Result<()> { + let (session, other_client) = setup().await?; + other_client + .sql("CREATE TABLE c.ns.t (id INT NOT NULL)") + .await?; + other_client.sql("INSERT INTO c.ns.t VALUES (1)").await?; + + session.sql("INSERT INTO c.ns.t VALUES (2)").await?; + let rows = session.sql("SELECT * FROM c.ns.t ORDER BY id").await?; + insta::assert_snapshot!(rows, @r" + +----+ + | id | + +----+ + | 1 | + | 2 | + +----+ + "); + let snapshots = session + .sql("SELECT count(*) AS snapshots FROM c.ns.\"t$snapshots\"") + .await?; + insta::assert_snapshot!(snapshots, @r" + +-----------+ + | snapshots | + +-----------+ + | 2 | + +-----------+ + "); + let error = session + .sql("CREATE TABLE c.ns.t (id INT NOT NULL)") + .await + .unwrap_err(); + insta::assert_snapshot!(error.to_string(), @"Execution error: Table 'c.ns.t' already exists"); + session + .sql("CREATE TABLE IF NOT EXISTS c.ns.t (id INT NOT NULL)") + .await?; + + Ok(()) + } + + /// `DROP TABLE` looks the table up, then deregisters it and reports success + /// whatever deregistering returned, so the drop has to find the table in + /// the catalog too or it would drop nothing. + #[tokio::test] + async fn drops_a_table_another_client_created() -> Result<()> { + let (session, other_client) = setup().await?; + other_client + .sql("CREATE TABLE c.ns.t (id INT NOT NULL)") + .await?; + + session.sql("DROP TABLE c.ns.t").await?; + let error = other_client.sql("SELECT * FROM c.ns.t").await.unwrap_err(); + insta::assert_snapshot!(error.to_string(), @"Error during planning: table 'c.ns.t' not found"); + + Ok(()) + } + + #[tokio::test] + async fn forgets_a_table_another_client_dropped() -> Result<()> { + let (session, other_client) = setup().await?; + session + .sql("CREATE TABLE c.ns.kept (id INT NOT NULL)") + .await?; + session + .sql("CREATE TABLE c.ns.dropped (id INT NOT NULL)") + .await?; + session.sql("INSERT INTO c.ns.dropped VALUES (1)").await?; + other_client.sql("DROP TABLE c.ns.dropped").await?; + + // Listing columns looks up every listed table, `dropped` included. + let columns = session + .sql( + "SELECT table_name, column_name, data_type \ + FROM information_schema.columns \ + WHERE table_schema = 'ns' AND table_name NOT LIKE '%$%' \ + ORDER BY table_name, column_name", + ) + .await?; + insta::assert_snapshot!(columns, @r" + +------------+-------------+-----------+ + | table_name | column_name | data_type | + +------------+-------------+-----------+ + | kept | id | Int32 | + +------------+-------------+-----------+ + "); + let error = session.sql("SELECT * FROM c.ns.dropped").await.unwrap_err(); + insta::assert_snapshot!(error.to_string(), @"Error during planning: table 'c.ns.dropped' not found"); + let error = session.sql("DROP TABLE c.ns.dropped").await.unwrap_err(); + insta::assert_snapshot!(error.to_string(), @"Execution error: Table 'c.ns.dropped' doesn't exist."); + session.sql("DROP TABLE IF EXISTS c.ns.dropped").await?; + + session + .sql("CREATE TABLE c.ns.dropped (id INT NOT NULL)") + .await?; + let rows = session + .sql("SELECT count(*) AS n FROM c.ns.dropped") + .await?; + insta::assert_snapshot!(rows, @r" + +---+ + | n | + +---+ + | 0 | + +---+ + "); + + Ok(()) + } + + #[tokio::test] + async fn forgets_a_namespace_another_client_dropped() -> Result<()> { + let (session, other_client) = setup().await?; + session.sql("CREATE TABLE c.ns.t (id INT NOT NULL)").await?; + other_client.sql("DROP TABLE c.ns.t").await?; + other_client.drop_namespace("ns").await?; + + let error = session.sql("SELECT * FROM c.ns.t").await.unwrap_err(); + insta::assert_snapshot!(error.to_string(), @"Error during planning: table 'c.ns.t' not found"); + let tables = session + .sql("SELECT count(*) AS n FROM information_schema.tables WHERE table_schema = 'ns'") + .await?; + insta::assert_snapshot!(tables, @" + +---+ + | n | + +---+ + | 0 | + +---+ + "); + + Ok(()) + } + + #[tokio::test] + async fn refuses_to_create_a_table_named_like_a_metadata_table() -> Result<()> { + let (session, _) = setup().await?; + + let error = session + .sql("CREATE TABLE c.ns.\"t$snapshots\" (id INT NOT NULL)") + .await + .unwrap_err(); + insta::assert_snapshot!(error.to_string(), @"Error during planning: Iceberg table name t$snapshots can't contain '$', which marks a metadata table"); + + Ok(()) + } + + /// The catalog has no table named `t$snapshots`, and `DROP TABLE` reports + /// success when deregistering finds nothing, so this must be refused. + #[tokio::test] + async fn refuses_to_drop_a_metadata_table() -> Result<()> { + let (session, _) = setup().await?; + session.sql("CREATE TABLE c.ns.t (id INT NOT NULL)").await?; + + let error = session + .sql("DROP TABLE c.ns.\"t$snapshots\"") + .await + .unwrap_err(); + insta::assert_snapshot!(error.to_string(), @"Execution error: Table 'c.ns.t$snapshots' doesn't exist."); + + Ok(()) + } } From 6ecad66ea33602d1ec30da08693a9889224f34c4 Mon Sep 17 00:00:00 2001 From: Noah Date: Fri, 4 Dec 2026 08:54:40 -0500 Subject: [PATCH 2/2] refactor: share the metadata-name check and describe live table lookups `register_table` and `deregister_table` now reject `$` names through one helper, `ensure_not_metadata_name`, with the same error. Comments and docs follow the new behaviour: the `tables` field doc no longer says the names were listed (fixed sets configure them) and says what still relies on it; the note on duplicate names sits at `create_table`; `catalog_builder`'s docs and `AGENTS.md` say that table lookups, `CREATE TABLE` and `DROP TABLE` ask the catalog while namespaces stay fixed (#165). --- AGENTS.md | 4 +- crates/datafusion/src/catalog/provider.rs | 3 +- crates/datafusion/src/catalog/schema.rs | 48 +++++++++++++---------- 3 files changed, 31 insertions(+), 24 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ea33c41..91f5c51 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,10 +77,10 @@ The playground config holds `[[catalogs]]` entries with `name`, `type` (`rest` o ### Catalog → schema → table -`IcebergCatalogProvider::catalog_builder(client)` discovers namespaces and table names at construction. `with_fixed_tables` supplies the names locally and allows appends with fixed membership. `static_builder()` accepts detached tables and historical snapshots and builds a read-only catalog synchronously. +`IcebergCatalogProvider::catalog_builder(client)` discovers namespaces and table names at construction. Namespaces stay fixed, but table lookups, `CREATE TABLE` and `DROP TABLE` ask the catalog, so they see tables other clients create or drop later; the listed names only serve listings. `with_fixed_tables` supplies the names locally and allows appends with fixed membership. `static_builder()` accepts detached tables and historical snapshots and builds a read-only catalog synchronously. - Names like `$snapshots`, `$manifests`, and `$history` resolve to `IcebergMetadataTableProvider`. -- SQL `CREATE TABLE` and `DROP TABLE` reach the *synchronous* `SchemaProvider::register_table` and `deregister_table` methods, which call the async catalog through `spawn_blocking` + `block_on`. `register_table` rejects input tables that contain rows, so CTAS isn't supported. It auto-assigns field IDs and uses format V2 unless the schema needs V3. +- SQL `CREATE TABLE` and `DROP TABLE` reach the *synchronous* `SchemaProvider::register_table` and `deregister_table` methods, which call the async catalog through `spawn_blocking` + `block_on`. Both reject names containing `$`, which lookups read as metadata tables. `register_table` rejects input tables that contain rows, so CTAS isn't supported. It auto-assigns field IDs and uses format V2 unless the schema needs V3. ### Table providers (`table_provider/`) diff --git a/crates/datafusion/src/catalog/provider.rs b/crates/datafusion/src/catalog/provider.rs index 9b0c895..16539a9 100644 --- a/crates/datafusion/src/catalog/provider.rs +++ b/crates/datafusion/src/catalog/provider.rs @@ -36,7 +36,8 @@ pub struct IcebergCatalogProvider { impl IcebergCatalogProvider { /// Starts a live catalog builder with a REST client, in-memory catalog, or caching wrapper. - /// By default, building the provider discovers namespaces and table names. + /// By default, building the provider discovers namespaces and table names; + /// tables other clients create or drop later are found by name when queried. pub fn catalog_builder(catalog: Arc) -> IcebergCatalogProviderBuilder { IcebergCatalogProviderBuilder { catalog, diff --git a/crates/datafusion/src/catalog/schema.rs b/crates/datafusion/src/catalog/schema.rs index 344dddb..546bfa2 100644 --- a/crates/datafusion/src/catalog/schema.rs +++ b/crates/datafusion/src/catalog/schema.rs @@ -21,7 +21,7 @@ use async_trait::async_trait; use dashmap::DashMap; use datafusion::catalog::SchemaProvider; use datafusion::common::{ - config_err, exec_datafusion_err, exec_err, not_impl_datafusion_err, not_impl_err, + config_err, exec_datafusion_err, exec_err, not_impl_datafusion_err, plan_datafusion_err, plan_err, }; use datafusion::datasource::TableProvider; @@ -43,11 +43,12 @@ use crate::to_datafusion_error; #[derive(Debug)] pub(crate) struct IcebergSchemaProvider { pub(super) namespace: NamespaceIdent, - /// Set when the namespace's tables are whatever its catalog holds: lookups - /// of names not in `tables`, and DDL, go to it. `None` for a fixed set. + /// The catalog this namespace mirrors: lookups of names missing from + /// `tables`, and DDL, go to it. `None` for a fixed set of tables. catalog: Option>, - /// The tables listed when the namespace was built, kept up to date by DDL - /// through it but not by other clients. + /// The tables when the namespace was built, updated by DDL through it but + /// not by other clients. With `catalog` set, only `table_names` and + /// `table_exist` rely on it. tables: Arc>, } @@ -152,8 +153,8 @@ impl SchemaProvider for IcebergSchemaProvider { } None => (name, None), }; - // A table another client created after the listing isn't in `tables`, - // so look the name up in the catalog unless the set is fixed. + // Another client may have created the table after the listing, so ask + // the catalog unless the set is fixed. let entry = match self.tables.get(table_name) { Some(entry) => entry.value().clone(), None => match &self.catalog { @@ -193,13 +194,7 @@ impl SchemaProvider for IcebergSchemaProvider { table: Arc, ) -> Result>> { let catalog = self.catalog_for_ddl()?; - // The catalog, not `tables`, knows whether the name is taken: another - // client may have created or dropped it since the listing. - if name.contains('$') { - return plan_err!( - "Iceberg table name {name} can't contain '$', which marks a metadata table" - ); - } + ensure_not_metadata_name(&name)?; // Convert DataFusion schema to Iceberg schema // DataFusion schemas don't have field IDs, so we use the function that assigns them automatically @@ -231,6 +226,8 @@ impl SchemaProvider for IcebergSchemaProvider { // Verify the input table is empty - CREATE TABLE only accepts schema definition ensure_table_is_empty(&table).await?; + // The catalog rejects a name that's taken. `tables` can't: + // other clients create and drop tables without updating it. catalog .create_table(&namespace, table_creation) .await @@ -250,9 +247,7 @@ impl SchemaProvider for IcebergSchemaProvider { fn deregister_table(&self, name: &str) -> Result>> { let catalog = self.catalog_for_ddl()?; - if name.contains('$') { - return not_impl_err!("Cannot drop Iceberg metadata table {name}"); - } + ensure_not_metadata_name(name)?; let namespace = self.namespace.clone(); let tables = self.tables.clone(); @@ -262,8 +257,8 @@ impl SchemaProvider for IcebergSchemaProvider { let result = tokio::task::spawn_blocking(move || { let rt = tokio::runtime::Handle::current(); rt.block_on(async move { - // Load the table before dropping it, to return its provider. - // It may not be in `tables`: another client may have created it. + // Load the table to return its provider. It may be missing from + // `tables` if another client created it. let ident = TableIdent::new(namespace, table_name.clone()); let Some(table) = load_if_exists(catalog.as_ref(), &ident).await? else { tables.remove(&table_name); @@ -290,8 +285,8 @@ impl SchemaProvider for IcebergSchemaProvider { } } -/// Loads a table, or returns `None` if the catalog has no such table, for -/// example because another client dropped it after the listing. +/// Loads a table, or returns `None` if the catalog has no such table or +/// namespace, for example because another client dropped it after the listing. async fn load_if_exists( catalog: &dyn Catalog, ident: &TableIdent, @@ -310,6 +305,17 @@ async fn load_if_exists( } } +/// Rejects a name that `table()` reads as a metadata table (`t$snapshots`): a +/// table created under it couldn't be read, and dropping it would drop nothing. +fn ensure_not_metadata_name(name: &str) -> Result<()> { + if name.contains('$') { + return plan_err!( + "Iceberg table name {name} can't contain '$', which marks a metadata table" + ); + } + Ok(()) +} + /// Verifies that a table provider contains no data by scanning with LIMIT 1. /// Returns an error if the table has any rows. async fn ensure_table_is_empty(table: &Arc) -> Result<()> {