Skip to content

feat(frontend): support schema evolution in data branch diff/merge - #24666

Closed
ULookup wants to merge 27 commits into
matrixorigin:mainfrom
ULookup:fix/issue-24549-schema-evolution-diff-merge
Closed

ULookup wants to merge 27 commits into
matrixorigin:mainfrom
ULookup:fix/issue-24549-schema-evolution-diff-merge

Conversation

@ULookup

@ULookup ULookup commented May 28, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #24549

What this PR does / why we need it:

This PR supports schema evolution in DATA BRANCH DIFF/MERGE by replacing the strict schema equivalence check with a named-column compatibility check. When a branch table has extra columns (e.g., added via ALTER TABLE ADD COLUMN), DIFF and MERGE now work correctly by projecting base-side batches to match the target layout, comparing only common columns, and preserving extra-column data in output.

Changes

  • pkg/frontend/data_branch_types.go: Add commonIdxes, tarOnlyIdxes, and baseColToTarIdx fields to the internal branch table struct.
  • pkg/frontend/data_branch.go: Replace isSchemaEquivalent with checkSchemaCompatibility; update getTableStuff to compute column index mappings.
  • pkg/frontend/data_branch_hashdiff.go: Add projectBaseBatchToTarget helper; apply base batch projection before hashmap encoding; limit row comparison to common columns.
  • pkg/frontend/data_branch_test.go: 6 unit tests for checkSchemaCompatibility.
  • pkg/frontend/data_branch_hashdiff_test.go: 2 unit tests for projection and comparison.
  • test/distributed/cases/git4data/branch/diff/diff_schema_evolve.sql: BVT for DIFF with schema evolution.
  • test/distributed/cases/git4data/branch/merge/merge_schema_evolve.sql: BVT for MERGE with schema evolution.

Replace strict schema equivalence check with named-column compatibility
check that allows compatible schema evolution (extra columns). Project
base-side batches to target layout before hashmap encoding. Limit row
comparison to common columns only.

Fixes matrixorigin#24549
@ULookup
ULookup requested a review from XuPeng-SH as a code owner May 28, 2026 07:31
@ULookup
ULookup requested a review from a user May 28, 2026 07:31
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

Fixes index out of range panic when base data batch has more
columns than base table definition (e.g., composite PK columns).
Clamp baseColCount to len(baseColToTarIdx) and validate tarColIdx
against len(colNames) before accessing out.Vecs.
When target table has extra columns not present in base (schema evolution),
INSERT SQL for MERGE must only reference common columns. Filter
visibleNames in newPKBatchInfo and use commonIdxes in
appendBatchRowsAsSQLValues/writeInsertRowValues when tarOnlyIdxes is
non-empty.

Also update diff_schema_evolve.result to expect 5 columns including the
extra column c in DIFF output.
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH XuPeng-SH 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.

Requesting changes. The direction is right, but the current implementation still has correctness/resource-lifecycle gaps that are not covered by the new tests.

  1. High: commonIdxes is a target-column index set, but compareRowInWrappedBatches treats it as a dense batch index.

In pkg/frontend/data_branch_hashdiff.go, the loop uses for batchIdx, colIdx := range compareIdxes and then reads wrapped.batch.Vecs[batchIdx]. Ret data batches are allocated in full target colNames layout, so for a legal schema evolution such as target [a, c(target-only), b] and base [a, b], commonIdxes == [0, 2]. The second comparison reads Vecs[1] (c) instead of Vecs[2] (b). This can both report false conflicts/diffs on the target-only column and miss real changes in common columns.

First-principles fix: keep one invariant for these index lists. If commonIdxes means target physical/data column indexes, always index batches by colIdx, not the loop ordinal. Add BVT/unit coverage for ALTER TABLE ... ADD COLUMN ... AFTER/FIRST or any case where a target-only column sits between two common columns, including update/conflict paths.

  1. High: projectBaseBatchToTarget leaks vectors and has unclear ownership transfer.

The helper first allocates a const-null vector for every target column, then overwrites common-column slots with vectors from baseBat without cleaning the previously allocated null vectors. That leaks one null vector per overwritten common column per projected batch. It also aliases out.Vecs[0] and common-column vectors directly to baseBat while dropping the original baseBat pointer, so cleanup ownership is implicit and fragile.

Please make the ownership explicit. For example, allocate NULL vectors only for target-only columns, move common vectors intentionally, clear the moved entries on baseBat, and clean the original batch wrapper on every path; or clone/copy vectors if transfer is not intended. Add a projection test that verifies cleanup/allocator balance or at least avoids allocating vectors that are immediately overwritten.

  1. High: the compatibility check allows base-only non-PK columns to disappear silently.

checkSchemaCompatibility iterates target columns and only checks that base PK columns are common. If the branch/target dropped a non-PK base column, this passes and DIFF/MERGE silently compare only the remaining common columns. That is not the same feature as supporting added/nullable columns from issue #24549, and it can hide data differences in the dropped base column.

Please reject base user-visible columns that are missing from target unless the PR deliberately defines and implements base-only-column semantics end-to-end. The previous unhappy-path coverage for dropped columns was removed; restore it with an expected rejection for non-PK drops, and keep the PK-drop rejection.

  1. Medium/High: commonIdxes is also used as SQL/output visible columns, but it is not filtered by visibility.

checkSchemaCompatibility skips Row_ID/FakePK/CPK, but it does not apply isDataBranchUserVisibleColumn. When tarOnlyIdxes is non-empty, newApplyBatchInfo and appendDataBranchApplyRowAsSQLValues replace visibleIdxes with commonIdxes. On tables with hidden columns such as cluster-by helper columns, this can include hidden common columns in INSERT column lists / SQL values and comparison paths.

Please separate the concepts: common physical indexes for hashmap/comparison, and common visible indexes for SQL/output/apply. Do not use one list for both. Add a cluster-by table + added column merge/diff BVT to cover this unhappy path.

CI is currently still pending on the latest head, but the above issues are independent of CI status.

@XuPeng-SH XuPeng-SH 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.

Requesting changes. The previous four blockers around sparse common-column indexes, projection ownership, base-only columns, and hidden-column output are fixed at the current head, and the new functional coverage is strong. However, the latest ALTER-lineage support introduces one high-severity lifecycle gap.

A lineage created solely because of a user snapshot or PITR has no reclaim path when that external history source is dropped or expires. This leaves the internal branch snapshot and live alter node in place, pins the old physical generation, and causes every later ALTER to keep extending the lineage even after no external history source exists.

Please close that lifecycle before merge and add coverage for create snapshot/PITR -> ALTER -> drop/expire history while the current table remains live, including a second ALTER to prove that no stale lineage keeps accumulating.

Comment thread pkg/sql/compile/alter.go
}
preserveHistoricalSource := false
if !hasLiveLineage {
if preserveHistoricalSource, err = c.alterTableHasHistoricalBranchSource(

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.

High (Q1/Q3): preserveHistoricalSource creates a live level=alter metadata node plus a kind=branch snapshot, but dropping the user snapshot or expiring/disabling the PITR never calls the branch reclaim pipeline. The only reclaim callers are table/branch deletion paths, and direct DROP SNAPSHOT rejects kind=branch rows. Therefore create snapshot s ...; alter table t ...; drop snapshot s; leaves the internal snapshot pinning the old physical table as long as t remains live. On the next ALTER, alterTableParticipatesInDataBranch is true and SubtreeHasLiveNode returns true for that stale live alter node, so another metadata row/snapshot is added even though no external history source remains. Repeating ALTER grows this chain without a bound and retains every old generation.

Please add a lifecycle owner for root historical lineage when snapshot/PITR coverage ends, while preserving nodes still needed by a live logical branch or another history source. Add a regression that drops/expires the external history without dropping t, asserts the internal snapshot/metadata become reclaimable, then performs another ALTER and proves the chain does not regrow from stale state.

@XuPeng-SH XuPeng-SH 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.

Approved after re-reviewing the current head (2174674).

The prior blockers are closed:

  • sparse physical vs visible common-column indexes are handled consistently;
  • projected batch/vector ownership is explicit and cleaned correctly;
  • base-only visible columns fail closed;
  • historical ALTER generations preserve diff/merge lineage;
  • source-only lineage is reclaimed when user snapshots/PITRs no longer own it, while alter:<logical-level> keeps a live logical branch component pinned.

The lifecycle is transactionally closed: lineage metadata and its branch snapshot are created/deleted as a pair in the owning transaction, ALTER copy/drop/rename failures roll back together, delete failures propagate, traversal is cycle-safe, and expired ownership is compacted on the next relevant ALTER/drop operation. The added BVT covers snapshot -> ALTER -> source drop -> second ALTER and live-branch release.

I also reran the focused lineage planner, frontend compaction, PITR hook, and compile-layer ALTER tests locally; all passed. Current CI is green.

@gouhongshen gouhongshen 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.

Codex automated review

The patch accepts column reordering but skips the projection required for base batches, so diff/merge can hash and compare different physical columns. Focused tests were blocked by the missing native usearch.h header.

P1 - Base batches are not projected for pure column reordering (pkg/frontend/data_branch_hashdiff.go:2319)

checkSchemaCompatibility matches columns by name and accepts base [a,b] with target [b,a], leaving tarOnlyIdxes empty. This condition therefore skips projectBaseBatchToTarget even though dataBranchBatchHasTargetLayout is false. buildHashmapForTable then uses the target pkColIdx+1 against the unprojected base vectors, hashing base b as target a; subsequent comparisons also use target indexes on the base layout. Diff can report false changes and merge can apply incorrect rows. ALTER ... MODIFY ... FIRST/AFTER supports physical column reordering. Project whenever the base batch layout differs from the target, not only when target-only columns exist.

@aunjgr aunjgr 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.

[P1] Pure column reordering is still mishandled in the ordinary base-side hashmap path. At data_branch_hashdiff.go:2318-2323, projection is gated by len(tarOnlyIdxes) > 0. For base [a,b] and target [b,a], there are no target-only columns, so the batch remains in base order while hashing and comparisons use target indexes. Project whenever !dataBranchBatchHasTargetLayout(...), independent of target-only columns, and add a pure FIRST/AFTER reorder DIFF/MERGE regression.

@aunjgr aunjgr 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.

[P1] Pure column reordering is still mishandled in the ordinary base-side hashmap path. At data_branch_hashdiff.go:2318-2323, projection is gated by len(tarOnlyIdxes) > 0. For base [a,b] and target [b,a], there are no target-only columns, so the batch remains in base order while hashing and comparisons use target indexes. Project whenever !dataBranchBatchHasTargetLayout(...), independent of target-only columns, and add a pure FIRST/AFTER reorder DIFF/MERGE regression.

This branch was previously deployed

1 inactive deployment
ci — 2174674c Deployed Jul 20, 2026 by VioletQwQ-0 via Matrixone Utils CI / pr-size-label #41442
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/feature size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Support schema evolution in DATA BRANCH DIFF / MERGE

6 participants