← Back to Pull requests

[SPARK-59015][SQL] Rebind refreshed DSv2 relations to the current table schema #58298

Closed
unknown closed this pull request without merging on Sep 16, 2026 16:49 UTC
View on GitHub
unknown unknown commented on Aug 26, 2026 00:17 UTC
Author

What changes were proposed in this pull request?

When V2TableRefreshUtil refreshes a DataSourceV2Relation in ALLOW_NEW_FIELDS mode, the relation
is now replaced with a Project over a relation that exposes the current table schema: the relation
stays aligned with the physical scan, while the projection recreates the captured output — names,
expression IDs, types, nullability and metadata — for the already-analyzed parent plan. A new
CapturedSchemaProjection builds it, recursing through structs, arrays and maps, matching data columns
by name and metadata columns by their logical name. When the captured and current outputs already
match, the relation is returned unchanged, so an unchanged table keeps its plan and the rewrite is
idempotent under transformDown.

One shape cannot be recreated, and this PR makes it fail rather than answer wrongly: a MAP whose
key type gained a field. Keys that are distinct under the current key type can be equal under the
captured one, so narrowing the key back changes how many entries the map has. The rebuild goes through
Spark's map builder, which enforces key uniqueness, so the query raises DUPLICATED_MAP_KEY. Details
under user-facing changes.

Why are the changes needed?

Spark refreshes versioned DSv2 tables between analysis and optimization. V2TableRefreshUtil does
r.copy(table = currentTable), deliberately swapping in the current table while keeping the analyzed
output, which leaves:

relation.output   = [id, salary]                 // captured at analysis
scan data schema  = [id, salary, new_column]     // current snapshot

PushDownUtils.pruneColumns then calls toOutputAttrs(scan.readSchema(), relation), which builds its
name map only from relation.output, so any field the captured output does not know about throws
java.util.NoSuchElementException: key not found: new_column. The trigger is precisely that
Scan.readSchema() field names are not a subset of relation.output field names — not merely that
readSchema is wider than the query's project.

Reporting more than was requested is allowed: SupportsPushDownRequiredColumns.pruneColumns permits
partial pruning, its example being a source that only prunes top-level columns. That example alone
reproduces the failure:

sql("CREATE TABLE t (id INT, person STRUCT<name: STRING>) USING ...")
val df = spark.table("t")                              // captures person: STRUCT<name>
sql("ALTER TABLE t ADD COLUMN person.age INT FIRST")
df.collect()

[PLAN_VALIDATION_FAILED_RULE_IN_BATCH] ... The plan output schema has changed from
STRUCT<id: INT, person: STRUCT<name: STRING>> to
STRUCT<id: INT, person: STRUCT<age: INT, name: STRING>>

A one-shot query analyzes and optimizes back to back, so this window is normally invisible; it becomes
deterministic by forcing analysis on a DataFrame before changing the table, or via a temp view
created from a Dataset. This is not Connect-specific — the refresh phase lives in common
QueryExecution.

Does this PR introduce _any_ user-facing change?

Yes. Refresh exists so an already-analyzed plan runs against the table's current schema, so where the
captured output can still be reproduced the query now succeeds, and where it cannot the query fails
instead of improvising an answer.

  • Succeeds where it used to fail. Queries against a partially-pruning source, run after the table

  • gained a column, previously failed with NoSuchElementException or
    PLAN_VALIDATION_FAILED_RULE_IN_BATCH. They now return the captured schema.

  • Fails where it used to succeed: a map key that gained a field. The one compatibility break, and

  • it is intended. With a captured MAP<STRUCT<name: STRING>, INT>:

      ALTER TABLE t ADD COLUMN m.key.id INT;
      INSERT INTO t SELECT map(named_struct('name', 'a', 'id', 1), 10,
                               named_struct('name', 'a', 'id', 2), 20);
      

    Both keys are distinct now, but both are {name: 'a'} in the captured schema, so the map cannot hold
    two entries there. Previously the scan was asked to narrow the key itself and returned a map holding
    duplicate keys, which Spark propagated unchecked: size(m) reported both entries while collecting
    the row kept only the last. The projection now rebuilds the captured key through Spark's map builder,
    so the query fails with DUPLICATED_MAP_KEY — or keeps the last entry under
    spark.sql.mapKeyDedupPolicy=LAST_WIN. Narrowing a map key is a fold rather than a projection and is
    not something a scan can be asked to perform; a captured key type that cannot represent the current
    key set has no correct answer to return.

  • No change when the table has not changed — the outputs match, rebinding is skipped, and the plan

  • is identical to before.

    How was this patch tested?

    New CapturedSchemaProjectionSuite (27 tests) covers the projection at the expression level: nested
    struct/array/map shapes with a field added at every level and a different ordinal shift per level; an
    unchanged VARIANT leaf, which must be carried by reference rather than rebuilt; nulls; resolver-based
    name matching; captured metadata columns; captured field metadata surviving alias cleanup; a map key
    that gained a field under both spark.sql.mapKeyDedupPolicy values; and every rejection path.

    DataSourceV2DataFrameSuite gains 9 end-to-end tests that run an already-analyzed plan across a table
    change, mostly against a source that reports every data column from readSchema(): flat and nested
    widening, a column added first, an external case-only rename, two metadata-column cases, a self-join,
    and the map key above. Disabling the rebinding call in V2TableRefreshUtil fails 8 of the 9.

    Was this patch authored or co-authored using generative AI tooling?

    Generated-by: Claude Code 2.1.268

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: yyanyy Review duration: 31231m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #58298"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 56.8% · Lower = rushed or shallow review
    56.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.5% · Safe to merge
    22.5%
    Repository