Skip to content

[KYUUBI #7673] Fix Spark engine metadata operations with custom session catalog - #7718

Closed
maomaodev wants to merge 9 commits into
apache:masterfrom
maomaodev:kyuubi-7673
Closed

maomaodev wants to merge 9 commits into
apache:masterfrom
maomaodev:kyuubi-7673

Conversation

@maomaodev

@maomaodev maomaodev commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Why are the changes needed?

The thrift GetSchemas/GetTables operations assumed spark_catalog is always the builtin V1 session catalog and listed databases/tables via spark.sessionState.catalog. When a custom session catalog is configured, e.g.

spark.sql.catalog.spark_catalog=org.apache.iceberg.spark.SparkSessionCatalog

these operations bypass the DSv2 catalog APIs (SupportsNamespaces/TableCatalog) and the V1 session catalog path cannot even parse the V2 table metadata the custom catalog persists in HMS - it may return wrong results, or throw and fail the whole request. #7673 is a real-world example: GetTables fails with ClassNotFoundException: org.apache.iceberg.mr.hive.HiveIcebergSerDe when the V1 HiveExternalCatalog tries to load tables registered by Iceberg with storage_handler = org.apache.iceberg.mr.hive.HiveIcebergStorageHandler.

Two more defects, which the builtin catalog has too, are fixed along the way:

  • the schema/table/function patterns were passed to the v1 catalog APIs as the Java regex produced by toJavaRegex, while those APIs compile Hive-style patterns themselves, so a trailing % could no longer match zero characters: a table, a temp view or a function whose name equals the pattern prefix went missing. The regex is now converted back via toV1Pattern, covering the builtin GetSchemas/GetTables, GetFunctions and the temp view paths;
  • GetColumns failed on local temp views (they surface with an empty namespace) and did not resolve the raw, unquoted names GetTables feeds back, breaking the getSchemas → getTables → getColumns round trip for identifiers needing quotes.

This patch routes GetSchemas/GetTables through the DSv2 catalog APIs when spark_catalog is a custom session catalog, keeping parity with the v1 path where it matters:

  • schema and table patterns match case-insensitively for spark_catalog (GetColumns and the global_temp schema included; column patterns stay case-sensitive as before);
  • for a CatalogExtension (e.g. Iceberg's SparkSessionCatalog, Delta's DeltaCatalog), table types and REMARKS are resolved with one batched v1 lookup (getTablesByName) per namespace, falling back to per-table loading when the batch fails, so a single unloadable table degrades REMARKS instead of failing the whole request (the [Bug] Legacy Iceberg tables fail with Kyuubi 1.11.1 and Iceberg 1.10.0 #7673 case, including LinkageError); a failed view probe degrades views to TABLE likewise;
  • a standalone session catalog (not a CatalogExtension, e.g. Iceberg's SparkCatalog) does not delegate to the v1 catalog, so the v1 lookup and view probe are skipped, and a same-named v1 table or view no longer decides the type and REMARKS of its tables;
  • for a custom session catalog, tables whose type does not match tableTypes are not loaded;
  • for any catalog, GetColumns skips the columns of a table whose loadTable or schema resolution fails instead of failing all matched tables; GetTables on non-session v2 catalogs degrades REMARKS of such a table likewise;
  • temp views are labeled spark_catalog, keeping the rows resolvable when another catalog is the current one, and are omitted from GetTables and GetColumns when another catalog is requested; temp view columns are read from the stored view metadata rather than the view plan - a view stored as SQL text resolves to an unanalyzed plan whose schema is unreadable - so local temp view columns surface with a null TABLE_SCHEM that resolves back, and global temp view columns, silently empty before, surface too;
  • the existing kyuubi.operation.getTables.ignoreTableProperties option now honors tableTypes via Spark's listTableSummaries (SPARK-52109, 4.1.0+) when the catalog implements it — detected by reflection, since vendors may backport — and its doc is updated accordingly.

How was this patch tested?

  1. New and updated tests:
    1. SparkMetadataTests, SparkOperationSuite: schemas, tables, temp views and functions whose names equal the pattern prefix; GetColumns on global temp views, VARCHAR/CHAR columns, and columns not stored in the metastore.
    2. IcebergMetadataTests (real HMS): spark_catalog and hadoop_prod listing, view detection, tableTypes, the batched v1 lookup and its fallback, temp views, and names needing quotes.
    3. SparkCatalogUtilsSuite: DSv2-only namespaces, case-insensitive patterns, unloadable tables, and pattern conversion.
    4. SummariesCatalogUtilsSuite (Derby-backed JDBCTableCatalog): listTableSummaries, standalone session catalogs, temp view scoping, and unloadable tables in a non-session catalog.
  2. Manually verified with Iceberg 1.10.1 and spark_catalog set to SparkSessionCatalog over HMS: beeline -u "jdbc:hive2://<kyuubi-host>:<port>/" -n <user> -e "!tables" threw ClassNotFoundException: org.apache.iceberg.mr.hive.HiveIcebergStorageHandler for a table registered with that handler; it now returns the table as TABLE with empty REMARKS, and views as VIEW.

Limitations

  • Non-session v2 catalogs report tables only (all rows typed TABLE). With ignoreTableProperties=true the tableTypes filter is applied on the listTableSummaries path, but with full table properties it is not applied to them, so a VIEW-only request still returns those tables typed TABLE (no VIEW rows are produced by the catalog itself). DSv2 ViewCatalog is still immature, so covering v2 tables only is intentional for this PR.
  • The fix guarantees listing for custom-catalog tables it can load; tables the custom session catalog delegates back to v1 (e.g. non-Iceberg tables under Iceberg's session catalog) are still listed as TABLE, and when loadTable fails for them — including LinkageError from missing SerDe/handler dependencies, the [Bug] Legacy Iceberg tables fail with Kyuubi 1.11.1 and Iceberg 1.10.0 #7673 case — REMARKS degrades to "" and GetColumns skips their columns (logged at warn).
  • A standalone spark_catalog reports tables only (all rows typed TABLE), unless ignoreTableProperties=true takes the listTableSummaries path, and loads each table for REMARKS, as non-session v2 catalogs do, since DSv2 has no batch API that returns comments. Set kyuubi.operation.getTables.ignoreTableProperties=true to skip loading.
  • Clients that pass the current catalog, e.g. !tables and !columns of beeline, do not see temp views when the current catalog is not spark_catalog.

Was this patch assisted by generative AI tooling?

Assisted-by: GLM-5.3
Assisted-by: Claude Opus 5.5
Co-authored-by: Cheng Pan chengpan@apache.org

@pan3793 pan3793 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Review of #7718 (head 8ffa541). Verdict: request changes. The #7673 diagnosis and the Iceberg fix mechanism are verified real; the listing refactor introduces the regressions below in the same configurations the PR targets.

  1. [Blocker, regression] Local temp views leak into the new v2 listing. catalog.listTables(ns) (SparkCatalogUtils.scala:202-204) reaches V2SessionCatalog.listTables -> SessionCatalog.listTables(db) with includeLocalTempViews = true, so temp views come back as Identifier.of(Array(), name); they are typed TABLE with TABLE_SCHEM="" (:217-232) and getTempViews (:350-359) emits the same view a second time as VIEW. Master used includeLocalTempViews = false here. Fix: drop identifiers with an empty namespace before typing/loading.

  2. [Blocker, regression] catalog.loadTable(ident) at :229 is unguarded and runs per row when ignoreTableProperties=false (the default), so the namespace-less identifier from (1) throws (requiresSinglePartNamespace/NoSuchTable) and fails the whole GetTables; any unloadable, dropped, or corrupt table does the same. It also forces per-table format I/O (Delta _delta_log, Iceberg metadata JSON) where master did one bulk HMS call. Fix: wrap in Try and degrade REMARKS to "" (or keep the session-catalog listing load-free).

  3. [Blocker, regression] The view probe keys listViews results by the outer db (:211-215) while SessionCatalog.listViews also returns local temp views, so a temp view v marks permanent table db.v as VIEW and removes it under tableTypes={TABLE}. Fix: only keep TableIdentifiers with a database.

  4. [Major, regression] getSchemas("spark_catalog", ...) with a custom session catalog now returns backtick-quoted namespaces and matches the pattern against the quoted form (:126, :170-173); a DB like 2024_db is returned as `2024_db` and no longer matchable by its own pattern. Master returned raw v1 names.

  5. [Major, regression] listAllNamespaces is a non-exhaustive match (:153-163) and is now reachable for the session catalog, so a TableCatalog-only session catalog throws MatchError in GetSchemas where master returned v1 rows.

  6. [Major, new failure mode] The per-namespace spark.sessionState.catalog.listViews(db, ...) probe calls requireDbExists, so a custom session catalog whose namespaces are not v1-backed now fails the whole GetTables with NoSuchDatabaseException. Guard with databaseExists or catch and skip the probe for that namespace.

  7. [Major] hasCustomSessionCatalog (:106-109) compares case-sensitively; Spark 4.x normalizes BUILTIN to builtin, so such a value is treated as custom. Use equalsIgnoreCase (mirrors V2SessionCatalog.hasCustomSessionCatalog).

  8. [Major, behavior change] tableTypes is now applied to ordinary v2 catalogs (:225) while view detection exists only for the session catalog, so getTables(<v2 catalog>, ..., Array("VIEW")) goes from all-rows-typed-TABLE to empty. DSv2 ViewCatalog is still immature, so covering v2 tables only is fine for this PR - please just document the limitation (non-session v2 catalogs report tables only, VIEW-only filters return empty) and drop the filter or add a test pinning the empty-result behavior.

  9. [Major, scope/claim] The fix guarantees only "the custom catalog can load the table". Tables delegated back to v1 (e.g. DeltaCatalog + catalogImplementation=hive, or non-Iceberg tables under Iceberg's session catalog) still hit HiveExternalCatalog/HiveClientImpl.getStorageHandler and the same ClassNotFoundException. Narrow the claim, or make the listing independent of per-catalog loading.

  10. [Major] TABLE_CAT is inconsistent within one result: catalog.name() at :231 vs the raw request string in getTempViews (:357) and getColumnsByCatalog, so getTables(null, ...) mixes "spark_catalog" with null. Align all row producers and tighten the assertions.

  11. [Test] DeltaMetadataTests#get tables and views exercises the new path (DeltaCatalog is a custom session catalog) but passes on master, so it does not discriminate the fix. Add a case that fails without the change, or drop it.

  12. [Test] Nothing covers GetSchemas: reverting only the getSchemas change keeps the suites green, because the test session catalogs delegate namespaces to the v1 catalog. Add a test-only CatalogExtension exposing a namespace the v1 catalog cannot see.

  13. [Test] IcebergMetadataTests creates spark_catalog.<db> namespaces and never drops them (withDatabases only drops unqualified names), making the exact-count get schemas assertion order-dependent. Drop them in the finally blocks.

  14. [Test] kyuubi.operation.getTables.ignoreTableProperties has no coverage repo-wide; the new path has three distinct behaviors for it (:208, :225, :228). Add a test.

  15. [Minor] The new tests never assert TABLE_SCHEM/TABLE_CAT; the docstring at :186-191 overstates ("returns both v1 and v2 views", "never loads the Hive storage handler") - it only covers views registered in the v1 catalog; catalog.name() and catalog.name are mixed in one file.

  16. [Minor] The new WithSimpleHMSContainer duplicates WithSecuredHMSContainer (drop the unused env, consider sharing the container def), hmsThriftUris has no null guard, and HostPortWaitStrategy has no startup-timeout margin.

  17. [Hygiene] Commit 80255d65e is tagged #7064 while the PR head/title use #7673, and the description does not describe the final diff or list the commands run. Please update the description for the final state.

@maomaodev

maomaodev commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review. All blockers and majors are addressed, code, tests, and PR metadata are now aligned. Point-by-point:

  1. [Blocker] Local temp views leak — Fixed. Identifiers are filtered by t.namespace().nonEmpty before typing/loading, matching master's includeLocalTempViews = false.

  2. [Blocker] Unguarded loadTable — Fixed. Wrapped in Try and degrade REMARKS to "" on failure, logging at warn so the degradation is traceable.

  3. [Blocker] View probe keys by outer db — Fixed. listViews results are filtered by .filter(_.database.isDefined).

  4. [Major] getSchemas backtick-quoted — Fixed. For a custom session catalog, getSchemas now lists namespaces through DSv2 (getSchemasWithPattern(catalog, schemaPattern, quote = false)) with quoting disabled, so a DB like 2026_db is returned raw and remains matchable by its own pattern, matching master's raw-name behavior.

  5. [Major] Non-exhaustive listAllNamespaces — Fixed. Added a case _ => Array.empty fallback, so a TableCatalog-only custom session catalog no longer throws MatchError in getSchemas.

  6. [Major] listViews requireDbExists — Fixed. The per-namespace probe is guarded with sessionCatalog.databaseExists(db).

  7. [Major] hasCustomSessionCatalog case-sensitivity — Fixed. Uses equalsIgnoreCase.

  8. [Major] tableTypes on ordinary v2 catalogs — Fixed. Dropped the filter, restoring master behavior (non-session v2 catalogs report tables only, typed TABLE). Limitation documented in the PR description.

  9. [Major] Scope/claim — Addressed. The listing is now independent of per-catalog loading (Try-guarded loadTable + databaseExists probe), and the claim is narrowed in the PR description.

  10. [Major] TABLE_CAT inconsistency — Fixed. All row producers use catalog.name().

  11. [Test] Delta get tables and views — Removed the non-discriminating Delta case; the Iceberg suite exercises the custom-session-catalog path and fails without the fix.

  12. [Test] GetSchemas coverage — Added SparkCatalogUtilsSuite#getSchemas lists DSv2-only namespace. It wires a test-only DummySessionCatalog (a DelegatingCatalogExtension exposing a namespace the v1 catalog cannot see) and asserts getSchemas lists it through DSv2 with raw (unquoted) names — the test fails without the hasCustomSessionCatalog detection and quote = false.

  13. [Test] Un-dropped namespaces — Fixed. All namespace-creating tests now drop namespaces in finally.

  14. [Test] ignoreTableProperties coverage — Added get tables with ignoreTableProperties, covering all three behaviors (view probe, tableTypes filter, loadTable).

  15. [Minor] TABLE_SCHEM/TABLE_CAT + docstring + name()/name — Fixed. Assertions added, overstating docstring removed, unified to catalog.name().

  16. [Minor] HMS container duplication — Fixed. Shared DOCKER_IMAGE_NAME/EXPOSED_HMS_PORT, added hmsThriftUris null guard, and added startup timeout.

  17. [Hygiene] Commit tag / description — Commit retagged to #7673; PR description rewritten to reflect the final diff, and the beeline command is now written out in full instead of beeline ....

@pan3793 pan3793 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Review of #7718 (head 3cdd2d7). Verdict: request changes. The previous round is addressed; 1-3 need to be addressed in this PR, and 1 and 2 are regressions in the configuration this PR targets. "Previous item N" refers to my last review; line numbers refer to SparkCatalogUtils.scala unless noted.

  1. [Major, regression] With a custom session catalog, schema and table patterns are matched as case-sensitive Java regex against DSv2 names (:176-179 via :207, :187-190 via :127, :259). Master listed through the v1 catalog, which matches case-insensitively, so getTables("spark_catalog", "DEFAULT", "MY_TABLE", null) and getSchemas("spark_catalog", "DEFAULT") return rows on master and nothing here. The view probe at :270 still uses v1 matching, so the two filters disagree within one request. Session catalog identifiers are case-insensitive; compile these patterns with Pattern.CASE_INSENSITIVE for spark_catalog.

  2. [Major, regression] Previous item 2 is fixed for failures, but the per-table format I/O noted there remains. With ignoreTableProperties=false (default), every custom session catalog (Iceberg, Delta, Hudi, Paimon) calls tc.loadTable per listed table just for REMARKS (:298), where master made one getTablesByName HMS call per database; e.g. DeltaCatalog with 5k tables turns one RPC into 5k _delta_log reads on every GetTables. Per namespace:

    1. Try the batched v1 sessionCatalog.getTablesByName first. It returns both the VIEW type and the comment (Iceberg pushes table properties, including comment, into HMS params), so REMARKS is unchanged and the databaseExists + listViews probe (:263-277) is only needed on the fallback path.
    2. Fall back to the current per-table path for namespaces where the batch throws (the #7673 case) and for identifiers it does not return (DSv2-only tables).
  3. [Major, perf] SPARK-52109 (4.1.0) added TableCatalog.listTableSummaries, which returns table types without loading tables when the catalog implements it. Since this PR reworks both TableCatalog branches (:254, :311), use it there for ignoreTableProperties=true, so tableTypes is honored without per-table loads:

    1. Detect the method by reflection, not by Spark version, since vendors backport.
    2. Call it only when the catalog has its own implementation. Calling it unconditionally turns today's single listTables into N loads and brings #7673 back for catalogs that don't implement it (e.g. DeltaCatalog via DelegatingCatalogExtension). A simple check is enough as long as the code comment explains it, e.g.
      // SPARK-52109 (4.1.0): added TableCatalog.listTableSummaries. Detect it by reflection
      // instead of by Spark version, since vendors may backport it. Use it only when the
      // catalog provides its own implementation, because the TableCatalog default calls
      // loadTable for every table, which is what this path avoids. A declaring class that
      // directly implements TableCatalog counts as not implemented: scalac emits a forwarder
      // to the interface default in such Scala classes (e.g. V2SessionCatalog). Real
      // implementations in such classes (e.g. JDBCTableCatalog) are skipped, which only
      // loses the optimization.
      private def implementsListTableSummaries(tc: TableCatalog): Boolean =
        try {
          val owner = tc.getClass.getMethod("listTableSummaries", classOf[Array[String]])
            .getDeclaringClass
          owner != classOf[TableCatalog] && !owner.getInterfaces.contains(classOf[TableCatalog])
        } catch {
          case _: NoSuchMethodException => false
        }
    3. Map VIEW and METRIC_VIEW to VIEW and the rest to TABLE, filter by tableTypes, keep REMARKS empty, and fall back to listTables per namespace on failure.
    4. Today this covers Iceberg 1.12.0 SparkCatalog and gives real VIEW types for non-session v2 catalogs, resolving the TODO at :317; new implementations are picked up with no code change. Iceberg's SparkSessionCatalog (Spark 4.2) is detected but forwards to V2SessionCatalog's default, so it stays per-table until Spark implements it there.
    5. Update the kyuubi.operation.getTables.ignoreTableProperties doc (it says tableTypes is ignored) and regenerate settings.md.
  4. [Minor] Try rethrows LinkageError (:298), so a NoClassDefFoundError (SerDe or handler class present, a dependency missing, the same upgrade pattern as #7673) still fails the whole GetTables. Catch it explicitly, also in the fallback from 2.

  5. [Minor, refines previous item 10] getTempViews labels temp views with the requested or current catalog (:379), but temp views live in the session catalog and getColumns labels them spark_catalog (:435, :454). With spark.sql.defaultCatalog=hadoop_prod, getTables(null, "global_temp", "%", ["VIEW"]) returns TABLE_CAT=hadoop_prod, and hadoop_prod.global_temp.v does not resolve. Use SESSION_CATALOG for these rows.

  6. [Test] IcebergOperationSuite.scala:30 and SparkIcebergOperationSuite.scala:35 repeat the same 14-entry extraConfigs, mostly re-listing IcebergSuiteMixin's entries, and IcebergMetadataTests (:28) now needs an HMS-backed spark_catalog without declaring it. Move the HMS overrides into one mixin built on super.extraConfigs, and require it from IcebergMetadataTests with a self-type.

  7. [Minor] STARTUP_TIMEOUT = 60s (WithSimpleHMSContainer.scala:50) equals testcontainers' default wait timeout, so the margin from previous item 16 has no effect. Use a larger value, e.g. 3 minutes.

  8. [Nit] Unrelated cosmetic changes: three section banners are re-padded while the Columns one (:405) is not, and the getCatalogs/getSchemas scaladocs are reworded. Revert, or make the banners consistent.

@github-actions github-actions Bot added the kind:documentation Documentation is a feature! label Nov 20, 2026
@maomaodev

Copy link
Copy Markdown
Contributor Author

Thanks for another round of careful review — both regression catches were spot on. All items are addressed; point-by-point:

1. [Major, regression] Case-sensitive pattern matching with a custom session catalog

Done. For spark_catalog, schema and table patterns now compile with Pattern.CASE_INSENSITIVE (compilePattern in SparkCatalogUtils), so within one request the custom session catalog's filters agree with the v1 view probe. The non-session branch keeps case-sensitive matching, unchanged, consistent with DSv2 catalogs' case-sensitive identifiers. Covered by a unit test (getSchemas matches session catalog patterns case-insensitively in SparkCatalogUtilsSuite) and an e2e assertion in IcebergMetadataTests querying with an uppercase schema pattern (getTables(cg, "DB_TYPE", "TABLE%", null)), which runs against the HMS-backed session catalog in both the server and engine topologies.

2. [Major, regression] Per-table loadTable just for REMARKS

Done as prescribed. With ignoreTableProperties=false (default), getCustomSessionCatalogTablesOrViews now, per namespace: partitions identifiers so only single-level namespaces can be v1-backed; makes one batched sessionCatalog.getTablesByName call that returns both the VIEW type and the comment; the databaseExists + listViews probe is lazy and only evaluated on the fallback path; per-table loads remain only for DSv2-only identifiers and for namespaces where the batch throws (the #7673 case). The join is case-insensitive on both sides to survive identifier case drift between the catalog and the metastore. I verified the failure sub-path empirically: with a DSv2-only test table the batched call throws NoSuchDatabaseException from requireDbExists (confirmed with a temporary log probe), and the table is still returned via the per-table fallback. Unit coverage: "getTables falls back to per-table loading when the batched v1 lookup fails" in SummariesCatalogUtilsSuite; real-catalog coverage via IcebergMetadataTests under HMS, including the comment passthrough — a table created with COMMENT comes back with REMARKS set under ignoreTableProperties=false.

3. [Major, perf] Use listTableSummaries for ignoreTableProperties=true — deviation on the detection check

Done for both TableCatalog branches, with one deviation I'd like your input on. If you see anything improper with the current approach, I'm happy to switch back.

Why not the Java declaring-class check — it has two false negatives:

  • JDBCTableCatalog directly implements TableCatalog with a real implementation yet gets classified as "not implemented";
  • subclasses inheriting a real implementation (e.g. a catalog extending JDBCTableCatalog to add auth or config) are misclassified the same way.

The Scala-reflection probe — scalac emits forwarders to interface defaults only as bytecode, never in the Scala symbol table, so Type#member resolves to the TableCatalog symbol exactly when the default is relied upon: member.owner != the TableCatalog symbol ⇔ the catalog has its own implementation. Verified across Scala/Java catalogs × {default, forwarder, direct, indirect, inherited real, inherited forwarder}: 12/12 correct, vs 10/12 for the Java check. scala-reflect is already a provided dependency of this module, and the comment on implementsListTableSummaries documents the mechanism.

A practical side benefit: because the probe correctly detects JDBCTableCatalog, Spark's native catalog can serve as the test vehicle. A custom test catalog overriding listTableSummaries would otherwise need separate sources per Spark generation: on 3.5 and 4.0 the TableSummary type does not exist, and the override modifier required on 4.1+ is a compile error on lower versions.

The rest is as prescribed:

  • VIEW and METRIC_VIEW map to VIEW, anything else (e.g. FOREIGN) to TABLE; JDBCTableCatalog reports FOREIGN for every table, so the TABLE rows in the tests exercise the FOREIGN mapping.
  • Summaries are filtered by tableTypes with empty REMARKS, falling back to per-namespace listTables on failure.
  • The TODO about view types is kept: the summaries path now reports real types when ignoreTableProperties is set, but the full-properties path still requires per-table loads, where Table does not expose view identity until ViewCatalog matures.
  • Coverage: this repo pins Iceberg 1.11.0, whose SparkCatalog does not implement listTableSummaries (1.12.0 does, as the review notes), so the fast path is tested with JDBCTableCatalog backed by an embedded Derby that arrives transitively via the spark-hive test dependency; tests pass on Spark 3.5 (Scala 2.12) and 4.0/4.1/4.2 (Scala 2.13).

4. [Minor] LinkageError from Try

Done. The attempt helper catches LinkageError in addition to NonFatal and wraps both the batched lookup and every per-table loadComment, so a missing SerDe/handler dependency degrades REMARKS instead of failing the whole GetTables.

5. [Minor] getTempViews labels temp views with the wrong catalog

Done. Temp view rows are now labeled SESSION_CATALOG regardless of the requested or current catalog, matching getColumns, with a comment explaining that this keeps the rows resolvable. Covered by a regression test in IcebergMetadataTests that lists global temp views with spark.sql.defaultCatalog=hadoop_prod and asserts TABLE_CAT=spark_catalog.

6. [Test] Duplicated extraConfigs / undeclared HMS dependency

Done. The HMS overrides moved into HMSIcebergSuiteMixin, built on super.extraConfigs, requiring WithSimpleHMSContainer via a self-type; IcebergMetadataTests now declares self: HMSIcebergSuiteMixin =>, so the HMS requirement is compile-checked. Both operation suites are thin shells mixing the mixin with their harness.

7. [Minor] STARTUP_TIMEOUT equals the testcontainers default

Done — bumped to 3 minutes in WithSimpleHMSContainer.

8. [Nit] Cosmetic banner/scaladoc changes

Banners are now consistent across all four sections, and the two scaladoc rewordings are reverted to master's wording.

@pan3793 pan3793 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks, all 8 items are addressed. On the detection deviation: keep the Scala-reflection check. I verified it on Spark 4.1.0: V2SessionCatalog (scalac forwarder only) is reported as not implemented and JDBCTableCatalog as implemented, which the declaring-class check gets wrong. Keeping the view-type TODO is fine given your reasoning.

Remaining, line numbers refer to SparkCatalogUtils.scala:

  1. [Major] GetColumns only half adopts case-insensitive matching for spark_catalog: the schema pattern goes through compilePattern (:493), the table pattern does not (:494). With a custom session catalog, getTables("spark_catalog", "DEFAULT", "MY_TABLE", null) returns the table, while getColumns with the same patterns returns no columns. Use compilePattern for the table pattern too, and cover it in the uppercase-pattern test. The column pattern stays case-sensitive, as on the v1 path.
  2. [Minor] implementsListTableSummaries (:456) catches only NonFatal. If a member signature in the catalog's class hierarchy references a class absent at runtime (e.g. an optional dependency), the catalog still loads and works, but resolving its members throws NoClassDefFoundError, and GetTables fails where it used to just call listTables. attempt exists for exactly this; use it here too.
  3. [Test] The "false" test uses DummySessionCatalog, which extends a Java class and so has no forwarder; nothing in the suite covers the case the Scala reflection exists for. Also assert !implementsListTableSummaries(new V2SessionCatalog(spark.sessionState.catalog)), which carries a forwarder on Spark 4.1+.
  4. [Nit] The ignoreTableProperties doc says "returning table identities only", which contradicts honoring tableTypes, and "view probe" is internal. Suggest: "Speed up the GetTables operation by not loading table metadata: REMARKS is left empty, and tableTypes is honored only when the catalog implements Spark's listTableSummaries (SPARK-52109, 4.1.0); otherwise all entries are reported as TABLE."
  5. [Hygiene] Please update the PR description for the final state: batched v1 lookup with per-table fallback, listTableSummaries, case-insensitive matching for spark_catalog, temp views labeled spark_catalog, and the ignoreTableProperties doc change. The get tables with ignoreTableProperties entry still says the tableTypes filter is skipped.

@maomaodev

Copy link
Copy Markdown
Contributor Author

Thanks for another round of professional review, and especially for verifying the probe on Spark 4.1.0 yourself — that forwarder case is exactly what the suite was missing, and it is now covered (item 3). All items are addressed; point-by-point:

1. [Major] GetColumns only half adopts case-insensitive matching

Done. getColumnsByCatalog now compiles the table pattern with compilePattern as well, so schema and table patterns behave consistently for spark_catalog (case-insensitive), while non-session catalogs and the column pattern are unchanged, as on the v1 path. Covered in the uppercase-pattern section of IcebergMetadataTests#get tables and views: getColumns(cg, "DB_TYPE", "TABLE%", "%") returns the column row for table_type.

2. [Minor] implementsListTableSummaries catches only NonFatal

Done. The probe now runs inside attempt and returns false on failure, so a NoClassDefFoundError from a member signature referencing an absent optional dependency degrades to the listTables path instead of failing GetTables where it used to just call listTables.

3. [Test] Nothing in the suite covers the forwarder case

Done — asserted as suggested: !implementsListTableSummaries(new V2SessionCatalog(spark.sessionState.catalog)) in SparkCatalogUtilsSuite. On Spark 3.5/4.0 the interface method does not exist and the probe returns false trivially, so no version gating is needed; on 4.1+ the forwarder is present and the assertion becomes the discriminating case.

4. [Nit] ignoreTableProperties doc

Done — adopted the suggested wording verbatim and regenerated docs/configuration/settings.md accordingly.

5. [Hygiene] PR description

Done. The description now reflects the final state: batched v1 lookup with per-table fallback, the listTableSummaries fast path, case-insensitive matching for spark_catalog (GetColumns included), temp views labeled spark_catalog, and the doc change. The get tables with ignoreTableProperties entry was rewritten to describe what it actually exercises — the session catalog there (Iceberg 1.11.0) does not implement listTableSummaries, so all entries come back as TABLE — with the fast path's tableTypes filtering attributed to SummariesCatalogUtilsSuite.

@pan3793 pan3793 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM. @wangzhigang1999 do you want to have another look? I think we should include this in 1.13

@pan3793

pan3793 commented Nov 24, 2026

Copy link
Copy Markdown
Member

cc @maron546, do you have a chance to verify if this patch resolves your issue?

@wangzhigang1999 wangzhigang1999 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 verified the #7673 fix on Spark 3.5.8 with Iceberg 1.11.0. With the legacy Hive storage handler missing, the baseline failed GetTables. This patch listed the Iceberg table and the other objects in the same schema.

Before merging

  1. getTables misclassifies views on fallback. With a view v and an Iceberg table v_ice that triggers the fallback, a VIEW filter returns v for "v" and zero rows for "v%". listMatchingTables already applies the Java regex. Could we call sessionCatalog.listViews(db, "*") and check those names only for unmatched single-level identifiers? L373–409
  2. getSchemas(null, "prefix%") drops prefix. With the built-in catalog, the baseline returns prefix, prefixx, and prefixxyz. The patch returns only the latter two. JDBC % can match zero characters, but this branch passes the converted regex prefix.* to listDatabases. Please preserve that match and cover the null-catalog call. I reproduced this with both Hive and in-memory catalogs. L127–132
  3. getColumns cannot use the schema name returned by getSchemas. For a schema named 2026, passing TABLE_SCHEM straight into getColumns returned id on the baseline and zero rows on this patch. getSchemas now returns the raw name, while getColumns still matches against the backtick-quoted form. Please use the same naming convention for spark_catalog across all three calls and cover getSchemas → getTables → getColumns in the quoted-name test. L489–499

Non-blocking follow-ups

  • With JDBCTableCatalog as spark_catalog, SQL reads the Derby table, but getTables reports the type and comment of a same-named Hive view. I saw the same behavior on the baseline. We can skip the V1 batch lookup and view probe for standalone (non-CatalogExtension) catalogs in a follow-up. L366–397
  • getTables("other", "global_temp", ...) still includes a session-catalog temp view. This patch fixes its TABLE_CAT label. The remaining follow-up is to omit the row when the caller explicitly requests another catalog. L525–530

@pan3793 pan3793 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fresh pass over the full diff at 63153e1. I agree with items 1-3 of #7718 (review) and need them fixed before merge. I verified the root cause on Spark 4.1.0: the v1 pattern APIs prepend (?i) and expand * to .*, so the converted prefix.* becomes prefix..*; listDatabases("prefix.*") returns only prefixx, and listViews("default", "v.*") misses v. This PR already reworks most of these paths, so please also fix the pre-existing issues in items 6-8 here.

Notes on those fixes, line numbers refer to SparkCatalogUtils.scala:

  1. Fallback view probe (:373-381): the helper from item 2 fixes the pattern. Also run the probe only when the batch fails, since an identifier a successful batch did not return is not in the metastore, and only for single-level identifiers: a DSv2 table a.b.v is currently typed VIEW whenever v1 database a has a view v.
  2. getSchemas (:132): add one helper that rewrites the converted regex for v1 calls, pattern.replace(".*", "*"). Spark's StringUtils.filterPattern and HMS's ObjectStore add (?i) and expand * themselves, so this keeps the case-insensitive match and the filtering on the HMS side; on 4.1.0, listDatabases("PREFIX*") returns prefix and prefixx. getGlobalTempViewManager (:145) also matches case-sensitively, so GLOBAL_TEMP misses global_temp while DEFAULT matches default; use compilePattern there.
  3. getColumnsByCatalog (:491-499): besides raw names for spark_catalog, skip identifiers with an empty namespace, as listMatchingTables does. V2SessionCatalog.listTables returns local temp views with an empty namespace and loadTable rejects them (REQUIRES_SINGLE_PART_NAMESPACE on 4.1.0), so getColumns("spark_catalog", "default", "%", "%") fails whenever the session has a temp view. Temp view columns already come from getColumnsByLocalTempViews. Cover it with a temp view in the session.

New:

  1. [Test] Nothing exercises the batched v1 lookup end to end. HMSIcebergSuiteMixin.scala:34 sets iceberg.engine.hive.enabled=true and the Iceberg Spark runtime does not ship HiveIcebergStorageHandler, so every namespace holding an Iceberg table takes the fallback; the unit fallback test fails the batch through a missing v1 database. Add a table created with TBLPROPERTIES ('engine.hive.enabled'='false') in its own namespace so the batch succeeds, assert the same TABLE_TYPE and REMARKS as on the fallback, and comment at :34 that the setting reproduces #7673.
  2. [Minor] A failed batch is dropped silently (:396, :402), and the namespace degrades to one loadTable per table. Log the cause once per namespace at warn so a slow GetTables can be traced.

Pre-existing, please fix here:

  1. [Minor] The other v1 pattern calls get the same converted regex, so a trailing % never matches zero characters there either: builtin GetTables (:222, :231), temp views (:549, :551, :582, :599), the builtin branch of getColumnsByCatalog (:507, :509), and GetFunctions.scala:68-69. Use the helper from item 2 at each, and cover a table, a temp view and a function whose name equals the prefix.
  2. [Minor] getCatalogTablesOrViews (:218): make namespaces a lazy val. The builtin branch does not use it, but the eager call still lists all databases, with one databaseExists each, on every GetTables.
  3. [Minor] The builtin branch of getColumnsByCatalog (:505) is unreachable, since V2SessionCatalog matches case tc: TableCatalog first, so builtin GetColumns runs one loadTable per table. Move it first with the !hasCustomSessionCatalog guard from getCatalogTablesOrViews, and pass includeLocalTempViews = false (:509), as temp view columns come from getColumnsByLocalTempViews. getTablesByName returns views with their schema, as loadTable does, and the branch already emits raw names, so its rows match what item 3 asks for.

@pan3793 pan3793 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks, all 8 items are addressed in 1d6e687, and c45aa5f fixes the temp view DDL that failed the Spark 4.0 and 4.1 jobs. Findings from a fresh pass over the full diff are inline, plus:

  1. [Hygiene] Please update the title and description for the final scope: the trailing % fix in the builtin GetSchemas/GetTables/GetColumns/GetFunctions and temp view paths, the batched builtin GetColumns, the temp view GetColumns fix, and the new and renamed tests. Suggested title: [KYUUBI #7673] Fix Spark engine metadata operations with custom session catalog.

}
}

test("get functions whose names equal the pattern prefix") {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[Test] This also runs in TrinoFrontendSuite, and the Trino JDBC driver (411) throws NotImplementedException from getFunctions, so that suite will fail. Move it to SparkOperationSuite, next to get functions (:306).

},
v1Candidates.filterNot(ident => byName.contains(joinKey(ident))))
case Failure(e) =>
warn(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[Minor] This warn also fires for namespaces the metastore does not have, e.g. DSv2-only namespaces of a custom catalog: getTablesByName checks the database first and throws, so every GetTables logs a stack trace per such namespace. In the Failure branch, check databaseExists once, skip the warn when it is absent, and reuse the result for the view probe (:413).

}
}
identifiers.flatMap { ident =>
val table = tc.loadTable(ident)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[Minor] loadTable is unguarded, so one table that fails to load (the v1-delegated ones described under Limitations) fails GetColumns for all matched tables, while GetTables degrades the same table to an empty REMARKS. Use attempt, warn, and skip its columns. Pre-existing, but the same inconsistency this PR resolves for GetTables.

}
}

// Rewrites the Java regex produced by `toJavaRegex` back into a SQL-like pattern: the v1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[Nit] This comment and the test name in SparkCatalogUtilsSuite call the result a SQL-like pattern, but the v1 APIs take Hive-style patterns (* and |, the rest is regex). Suggest: "Converts the regex from toJavaRegex to the pattern form of the v1 catalog APIs, which prepend (?i) and expand * themselves."

override protected def extraConfigs: Map[String, String] = super.extraConfigs ++ Map(
"spark.sql.catalogImplementation" -> "hive",
"spark.hadoop.hive.metastore.uris" -> hmsThriftUris,
"spark.sql.catalog.spark_catalog.uris" -> hmsThriftUris,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[Nit] Iceberg's property is uri, so spark.sql.catalog.spark_catalog.uris has no effect; the metastore URI comes from the line above. Remove it.

@maomaodev maomaodev changed the title [KYUUBI #7673] Fix thrift GetSchemas/GetTables with custom session catalog [KYUUBI #7673] Fix Spark engine metadata operations with custom session catalog Nov 24, 2026
@maomaodev

Copy link
Copy Markdown
Contributor Author

@pan3793 @wangzhigang1999 Thanks for the careful reviews and for verifying the fix empirically. The latest commits address the remaining feedback, in short:

  • Pattern round-trip: a single toV1Pattern helper (regex.replace(".*", "*")) now fronts every v1 catalog call — GetSchemas/GetTables/GetColumns/GetFunctions and both temp-view paths — so a trailing % matches zero characters again; covered by the schema, table/temp-view, and function "whose names equal the pattern prefix" tests.
  • Naming convention: spark_catalog returns and matches raw unquoted names uniformly across getSchemas → getTables → getColumns, covered by get tables and columns with names needing quotes.
  • Fallback view probe: runs only when the batched getTablesByName fails, and only for single-level identifiers; the batch failure is logged once per namespace at warn, and the batch-vs-fallback types and comments are pinned equal by a test.
  • Builtin GetColumns: the branch is reachable again (moved first behind the !hasCustomSessionCatalog guard), batches getTablesByName, skips empty-namespace identifiers; namespaces is now lazy.
  • Temp view columns are read from the stored view metadata instead of the view plan — a view stored as SQL text resolves to an unanalyzed plan with no readable schema, so global temp view columns were silently empty before. The interval test expectations now derive from the runtime type, and the temp-view listing test lives in SparkOperationSuite, where one connection maps to one session.

The two non-blocking follow-ups are left for follow-up PRs, as suggested.

The failing jobs (BatchesV2ResourceSuite) look unrelated to this PR, which does not touch the batch code paths.

1. GetColumns skips a table whose schema fails to resolve, and loads the
   tables of the builtin catalog one by one, since getTablesByName returns
   raw CHAR/VARCHAR and misses columns not stored in the metastore.
2. GetTables on non-session catalogs degrades REMARKS of a table that
   fails to load.
3. GetTables on a custom session catalog matches the table type before
   loading a table, and tolerates failed metastore database checks and
   view listings.
4. Probe listTableSummaries once per operation.
5. GetColumns tolerates a local temp view dropped after being listed.

Assisted-by: Claude Opus 5.5
1. GetTables skips the v1 batch lookup and view probe for a standalone
   session catalog, i.e. not a CatalogExtension, as a same-named v1 table
   or view must not decide the type and comment of its tables.
2. GetTables and GetColumns omit temp views when another catalog is
   requested.

Assisted-by: Claude Opus 5.5
@pan3793

pan3793 commented Nov 25, 2026

Copy link
Copy Markdown
Member

@maomaodev I just put 2 commits to fix what I'm finding directly. @wangzhigang1999 could you please take another look?

@wangzhigang1999 wangzhigang1999 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. I re-tested all five issues from my previous review on our Kubernetes cluster with Spark 3.5.8 and Iceberg 1.11.0. All five passed on c10db7b. Thanks for the fixes!

@maomaodev

Copy link
Copy Markdown
Contributor Author

Thanks @pan3793 @wangzhigang1999 for the fixes and verification. The implementation is now more robust and performs better, and the PR description is updated to the final state.

@pan3793 pan3793 added this to the v1.13.0 milestone Nov 26, 2026
@pan3793

pan3793 commented Nov 26, 2026

Copy link
Copy Markdown
Member

Merge Summary:

Posted by merge_kyuubi_pr.py

@pan3793 pan3793 closed this in 61d1c57 Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants