Skip to content

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

Merged
XuPeng-SH merged 66 commits into
matrixorigin:mainfrom
VioletQwQ-0:codex/takeover-24666-data-branch-schema-evolution
Jul 29, 2026
Merged

XuPeng-SH merged 66 commits into
matrixorigin:mainfrom
VioletQwQ-0:codex/takeover-24666-data-branch-schema-evolution

Conversation

@VioletQwQ-0

@VioletQwQ-0 VioletQwQ-0 commented Jul 20, 2026 •

Copy link
Copy Markdown
Collaborator

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 continues the unfinished work from #24666 while preserving its original commits and authorship.

It supports schema evolution in DATA BRANCH DIFF/MERGE by matching columns with stable identity, separating physical and visible common-column indexes, projecting compatible historical batches, comparing common columns, preserving target-only data, and maintaining ALTER lineage ownership.

Safety contract

DIFF/MERGE is allowed only when the endpoint schemas can be mapped without guessing:

Schema relation Behavior
Same stable column identity with equal type attributes and nullability Treat as common; compare it and apply MERGE changes.
Pure reorder or lineage-proven rename Treat as common using the resolved historical identity, not the mutable endpoint name.
Target-only visible column with an explicit primary key Keep it in target-layout DIFF/OUTPUT, but do not write it into a base table that does not own the column.
Base-visible column missing from the target Fail closed.
Same logical name reused by DROP/ADD, including rename/drop/add variants Fail closed because the identities differ.
Common column with different type attributes, nullability, or primary-key identity Fail closed.
Target-only column on a fake-PK table Fail closed because the hidden key depends on the complete row layout.

Historical batches are projected through the lineage-resolved layout. A target-only column whose historical representation changed is omitted from the old batch and reconstructed from the current endpoint instead of being cast or matched by name.

COPY ALTER preserves the replaced physical generation only while a live data branch or a covering snapshot/PITR owns it. Snapshot/PITR publication and COPY ALTER update the same bootstrap-created mo_feature_registry row before choosing/probing the history boundary, while explicitly preserving the row's metadata: pessimistic transactions serialize on the row lock, while optimistic transactions serialize through write-write conflict and whole-statement retry. Snapshot/PITR creation now returns commit conflicts instead of reporting false success. After a wait, ALTER probes owners in a fresh transaction so it does not reuse an old SI snapshot. If identity, ownership, or generation connectivity cannot be proven, the operation returns an error.

Both PITR execution locations follow this contract. The frontend path and CREATE PITR ... INTERNAL engine path cross the same stable barrier; the INTERNAL path refreshes a pessimistic-RC snapshot after waiting and re-resolves the current database/table ID before selecting its timestamp and publishing mo_pitr, rather than reusing the ID captured during planning.

Review fixes on the latest head:

  • project reordered and target-only historical layouts without moving incompatible vectors;
  • reject same-name DROP/ADD column redefinitions by Seqnum, while preserving pure FIRST / AFTER reorderings;
  • retain ALTER snapshot/metadata pairs while table-, database-, or account-level historical owners still cover the component, including current-table-first deletion;
  • reclaim deleted intermediate ALTER generations after the final logical or historical owner disappears;
  • preserve explicit-transaction ALTER semantics for ordinary snapshot/PITR-covered tables;
  • serialize snapshot/PITR owner publication with COPY ALTER even when the initial owner query is empty;
  • serialize engine-executed INTERNAL PITR publication and refresh its target generation after waiting;
  • rename the merge BVT tables by scenario and role so each case is readable in isolation.

Validation

  • go test ./pkg/frontend/databranchutils ./pkg/frontend ./pkg/sql/compile ./pkg/vm/engine/test -count=1
  • full go test -race for pkg/frontend/databranchutils, pkg/frontend, and pkg/sql/compile, plus focused repeated race tests for lineage-owner publication
  • TestPreparePitrPublicationSerializesCopyAlter and TestResolveCurrentPitrObjectIDRefreshesPlannedTableID, each with -race -count=100, plus production TestPitrCases
  • authenticated cluster regressions TestIssue26087ConcurrentDataBranchQuota and TestIssue26114CrossAccountBranchUsesTargetQuotaAndOwnership
  • git diff upstream/main --check
  • full mo-pr-preflight-review and mo-self-review

The BVT fixtures are included for DIFF/MERGE identity redefinition and table/account/database historical-owner cleanup; they are executed by CI because this local worktree has no standalone mo-tester runner.

@mergify

mergify Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

⚠️ The sha of the head commit of this PR conflicts with #24666. Mergify cannot evaluate rules on this PR. Once #24666 is merged or closed, Mergify will resume processing this PR. ⚠️

@matrix-meow matrix-meow added the size/XXL Denotes a PR that changes 2000+ lines label Jul 20, 2026
@VioletQwQ-0
VioletQwQ-0 marked this pull request as ready for review July 20, 2026 05:53
@VioletQwQ-0
VioletQwQ-0 requested review from a user and gouhongshen July 20, 2026 05:53
@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 →

@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

One blocking schema-evolution regression found. Focused frontend tests could not run because the worktree lacks cgo/libmo.dylib.

P1 - Allow target-only historical type changes or reject them consistently (pkg/frontend/data_branch_hashdiff.go:2625)

checkSchemaCompatibility accepts a target-only column regardless of its type, so t0(a,b) and branch t1(a,b,c varchar) are compatible. However, after t1 first adds c int and then modifies it to varchar, every DIFF/MERGE walks the old physical generation and this mapping rejects old c int against endpoint c varchar before even opening CollectChanges. The column is target-only and is deliberately omitted from MERGE apply (commonVisibleIdxes), so its historical representation cannot affect t0; nevertheless all operations fail, including when there were no writes to c. Skip/project such non-common historical columns as NULL, or make the endpoint compatibility check reject this evolution up front. Add an end-to-end regression covering add-target-only-column -> modify its type -> DIFF/MERGE.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Addressed the blocking historical-generation schema mapping regression.

Changes:

  • Thread the endpoint target-only column indexes into historical generation mapping.
  • When a historical physical column has a different type from a target-only endpoint column, leave it unmapped so projection creates a NULL vector with the endpoint type; existing endpoint hydration restores the current value when the row still exists.
  • Keep historical type drift for common columns and primary-key incompatibility fail-closed.
  • Preserve compatible target-only mappings, source-only/rename behavior, and reordered columns.

Coverage:

  • Added focused unit coverage for the old failure, typed-NULL projection and vector ownership, common-column rejection, compatible target-only columns, source-only/rename, and reorder mappings.
  • Added DIFF BVT cases for no writes and historical target-only values across ADD c INT -> MODIFY c VARCHAR.
  • Added a MERGE BVT case proving common-column changes apply while the historical target-only value is ignored by destination apply.

Validation:

  • go test ./pkg/frontend -count=1
  • focused go test -race ./pkg/frontend ... -count=1
  • go vet ./pkg/frontend
  • go build ./pkg/frontend
  • git diff --check
  • full mo-self-review across correctness, concurrency, lifecycle, compatibility, failure modes, API closure, and Q1-Q3: zero open blockers

The BVT fixtures were not executed locally because this worktree has no mo-tester runner; the new-head CI will validate them.

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

Reviewed updated head c515a14. The target-only historical type-drift blocker is closed: incompatible non-common columns are projected as NULL and hydrated from the endpoint, while common-column and primary-key drift remain rejected. DIFF and MERGE regressions cover both unchanged and updated rows. No remaining blockers found.

# Conflicts:
#	pkg/frontend/data_branch_snapshot_test.go

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

Please cleanup test cases, with better names.

Actually there need to be a solid/clean doc on the behavior of the merge. I am not sure are all the cases listed/handled in reasonable way, and I want to read that doc and review the design. This is a pretty tricky thing. We should do the safe route -- unless we are exactly sure what to do, raise an error. The "we are exactly sure what to do" part should be designed/documented/reviewed.

@aptend aptend 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 for one P1 concurrency-correctness issue.

[P1] Serialize historical-owner publication with copy ALTER

The historical snapshot/PITR probes in pkg/sql/compile/alter.go use SELECT ... FOR UPDATE, which only protects owner rows that already exist. A concurrent publisher can choose its snapshot timestamp or PITR create time before copy ALTER commits, while its catalog row is not visible yet. ALTER then observes no historical owner, skips lineage preservation, performs the copy-and-swap, and the owner commits afterward with a time before the ALTER boundary.

A later data branch created from that historical owner can therefore resolve the old physical generation without an ALTER edge to the current generation, so DIFF/MERGE cannot reliably reconcile schema identity across the copy ALTER.

The new PITR mo_branch_metadata lock only serializes PITR publication with compaction: ALTER does not acquire that lock before its early owner probe, and CREATE SNAPSHOT does not acquire it at all. Please add a stable serialization point shared by CREATE SNAPSHOT, CREATE PITR, and copy ALTER before timestamp selection/owner probing, or revalidate the owner set under such a lock before the swap. Please also add a barrier-based concurrent regression test for this interleaving.

Current head also has a failing PROXY BVT: pitr_basic.sql times out while selecting mo_pitr. That should be investigated or rerun before merge.

# Conflicts:
#	pkg/frontend/data_branch_hashdiff.go
#	pkg/frontend/data_branch_hashdiff_test.go
#	pkg/sql/plan/function/func_unary_test.go
# Conflicts:
#	pkg/frontend/data_branch.go
#	pkg/frontend/feature_limit.go
#	pkg/frontend/feature_limit_test.go
#	pkg/sql/compile/alter.go
#	test/distributed/cases/snapshot/sys_create_snapshot_for_sys_db_table_level.result
# Conflicts:
#	pkg/frontend/clone.go

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

Deep-reviewed exact head c955ed6. One P1 correctness race remains.

doCreateSnapshot chooses the snapshot timestamp before publishing the owner row, and does not acquire a stable lock shared with COPY ALTER. prepareAlterDataBranchLineage probes owner rows with SELECT ... FOR UPDATE, but an empty result does not serialize against a concurrent later insert. The same issue exists for PITR because ALTER does not take the PITR-side stable lock before its early owner probe.

Interleaving: snapshot/PITR chooses time t; COPY ALTER sees no owner and skips the A-to-C lineage handoff, then swaps A to C; the owner row commits with timestamp t. A later data branch resolves old A at t, while current C has no LCA lineage, leaving the branch histories disconnected.

Please introduce synchronization on a stable key shared by owner publication and COPY ALTER before timestamp selection/owner probing, and add a deterministic barrier test covering this interleaving.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Fixed the empty-owner publication race in 7755749. CREATE SNAPSHOT, CREATE PITR, and COPY ALTER now cross the same bootstrap-created mo_feature_registry write barrier before timestamp selection/owner probing. The write preserves the registry metadata, serializes pessimistic transactions by row lock and optimistic transactions by write conflict, and snapshot/PITR commit conflicts are now returned instead of being reported as success.

I initially used mo_database as the stable key, but an authenticated cluster regression exposed that as invalid because it enters special catalog DDL tuple parsing. I replaced it before pushing; both issue cluster tests now pass, along with the full frontend/databranchutils/compile normal and race suites and pkg/vm/engine/test. Please re-review the current head.

@aptend aptend 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 for one remaining P1 correctness gap.

[P1] Serialize the engine/internal PITR publication path with COPY ALTER

The new stable publication barrier closes the frontend doCreatePitr path, but CREATE PITR ... INTERNAL is deliberately routed to engine execution (CreatePitr.StmtKind returns defaultStatusTyp) and reaches Scope.CreatePitr in pkg/sql/compile/ddl.go. That path resolves and stores the target object ID during planning, then selects now and inserts into mo_pitr without crossing LineageOwnerPublicationLockSQL.

Concrete interleaving: an INTERNAL PITR resolves old generation A; concurrent COPY ALTER crosses the barrier, observes no published historical owner, skips lineage preservation, and swaps A to C; the PITR then inserts its old timestamp/object ID. A later data branch restored from that PITR can resolve A with no lineage edge to current C, reproducing the disconnected-generation failure this barrier is intended to prevent. INTERNAL PITR is a real supported path and is exercised by pkg/tests/ddl/ddl_test.go.

Please make the INTERNAL/engine path share the barrier across object resolution, timestamp selection, and publication. Adding the write only immediately before the insert is insufficient if the plan already captured a stale object ID; either route this path through the frontend creation flow or refresh/re-resolve the object under the barrier. Add a deterministic regression for CREATE PITR ... INTERNAL racing COPY ALTER.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Addressed the INTERNAL PITR publication race in db2107d.

Scope.CreatePitr now crosses the same stable publication barrier as the frontend snapshot/PITR paths before choosing the PITR timestamp. After a pessimistic-RC wait it refreshes the transaction snapshot and re-resolves the current database/table ID, so the insert no longer uses the generation captured during planning. The barrier write and mo_pitr insert remain in the same statement transaction through commit/rollback.

I added a deterministic COPY ALTER interleaving and a stale planned-ID regression. I also fixed the current PESSIMISTIC BVT failure: merge_schema_evolve.sql had been renamed by scenario, but its .result commands still used t0/t1; all 139 SQL/result statements now match. The Utils Coverage failure was only the downstream prerequisite failure from that BVT job.

Validation:

  • TestPreparePitrPublicationSerializesCopyAlter with -race -count=100
  • TestResolveCurrentPitrObjectIDRefreshesPlannedTableID with -race -count=100
  • full pkg/sql/compile with -race -count=1
  • production TestPitrCases
  • TestIssue26087ConcurrentDataBranchQuota and TestIssue26114CrossAccountBranchUsesTargetQuotaAndOwnership
  • 139/139 BVT SQL/result statement alignment
  • git diff --check
  • exact-head preflight: PASS review=PASS validation=PENDING

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Synced with current upstream/main in 73e0cdb. The only content conflict was in clone_database_source_test.go; I retained both this PR’s empty-source lock regression and main’s cyclic-FK ordering regression. Focused race tests (100 iterations each), full pkg/frontend and pkg/sql/compile race suites, production TestPitrCases, BVT statement alignment, diff check, self-review, and exact-head preflight all pass locally. Fresh CI is pending.

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

Deep review complete on exact head dba14dfe0c. The prior historical-owner/COPY ALTER race is closed by a real stable-row write barrier shared by frontend snapshot/PITR publication, INTERNAL PITR publication, and COPY ALTER. The INTERNAL path now refreshes its RC snapshot and re-resolves the database/table object ID under that barrier instead of using the generation captured during planning. I traced all production owner-write entry points, the optimistic WW-conflict and pessimistic lock paths, transaction cleanup, lineage preservation, and the latest merge resolutions; no remaining blocker found. Six focused race regressions passed 100 iterations each, full race suites for frontend/databranchutils, frontend, and sql/compile passed, all eight owning packages passed test/build/vet, and embedded-cluster TestPitrCases passed. Required CI is green and this exact head merges cleanly with current main.

This branch was previously deployed

1 inactive deployment
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.

8 participants