Skip to content

fix: preserve DDL metadata consistency across retries - #27799

Merged
XuPeng-SH merged 2 commits into
matrixorigin:mainfrom
aptend:fix/277xx-ddl-consistency-main
Aug 29, 2026
Merged

XuPeng-SH merged 2 commits into
matrixorigin:mainfrom
aptend:fix/277xx-ddl-consistency-main

Conversation

@aptend

@aptend aptend commented Aug 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 #27766, #27725, #27658, #27708, #27735

What this PR does / why we need it:

This PR closes five related DDL consistency gaps with one shared regression suite:

  • restores ALTER COPY foreign keys and reverse references from the live source relation, including authoritative empty sets;
  • retries stale hidden-index generations instead of exposing internal table names;
  • keeps PRIMARY and secondary-index alias metadata consistent after column rename;
  • avoids rebuilding reverse foreign keys for duplicate CREATE TABLE statements;
  • qualifies hidden-index DROP TABLE statements when no default database is selected.

The regression coverage validates the public SQL and catalog behavior on a two-CN embedded cluster, with focused unit coverage for live FK snapshots, exact replacement, retry classification, duplicate CREATE planning, and PK metadata representations.

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

Deep-reviewed exact head 1ba1acb against merge base b789245, covering all five linked issues, the full DDL/FK/index lifecycle, concurrency retry behavior, unhappy paths, and regression quality. The five primary fix directions are sound, and the changed compile/plan packages plus focused race tests pass. Two blocking regressions remain:

[P1] snapshotAlterCopyForeignKeyState drops legacy reverse-FK definitions. The loop assigns refChildTbls = clone(definition.Tables) for every RefChildTableDef, so only the last definition survives. Multiple definitions are an explicitly supported legacy state: canonicalRefChildTableIDs and the existing canonicalization tests merge and deduplicate all of them. I added an exact-head counterexample with definitions [10,20] and [20,30]; the expected live set is [10,20,30], but this function returned [20,30]. ALTER COPY then restores only that truncated set and reconciles only those children, leaving the omitted child FK pointing at the dropped old parent generation. This can break RESTRICT/CASCADE routing and future DDL. Please canonicalize all live RefChildTableDefs (and defensively all ForeignKeyDefs) before replacing the relation, and retain a regression with multiple legacy definitions.

[P1] every missing hidden-index relation is now classified as ErrTxnNeedRetryWithDefChanged without proving that the parent definition actually changed. That is correct for the concurrent stale-generation case, but not for a persistent catalog inconsistency where TableExist/index metadata still names a relation that is genuinely absent. The RC execution loop has no retry-count bound: it rebuilds and retries while canRetry remains true. If replanning returns the same missing hidden name, ALTER now spins until client cancellation instead of returning the existing error. Please re-resolve the locked parent and retry only when its table/index generation differs from the planned one, or add an explicit same-generation/bounded escape. Add an unhappy-path test where the hidden relation remains absent after replan.

Performance note: every COPY ALTER now performs two full UpdateConstraint rewrites even for empty FK/ref-child sets. Combining the exact FK and reverse-reference replacement into one read/update would reduce catalog write amplification, but correctness of the two blockers above is the merge gate.

Validation: full ./pkg/sql/compile and ./pkg/sql/plan tests passed; focused race tests passed 10 iterations. The new legacy-definition counterexample failed exactly as described. Current CI is green but does not cover either failure mode.

@aptend
aptend force-pushed the fix/277xx-ddl-consistency-main branch from 1ba1acb to 632bdd3 Compare August 28, 2026 14:29
@aptend

aptend commented Aug 28, 2026

Copy link
Copy Markdown
Contributor Author

Addressed both blocking findings at 632bdd32c3:

  1. snapshotAlterCopyForeignKeyState now merges every legacy ForeignKeyDef, deep-copies each FK, and canonicalizes reverse child IDs across every RefChildTableDef. The regression covers multiple legacy containers, duplicate child IDs, and snapshot isolation.
  2. Missing hidden-index relations now retry only when the locked parent/index generation is proven stale. A persistent missing relation with the same parent ID and hidden-index generation returns the original ErrNoSuchTable, so the RC retry loop terminates. Both COPY and INPLACE ALTER paths use the generation-aware helper.

Validation:

  • focused compile regressions: PASS
  • go test -count=1 ./pkg/sql/compile ./pkg/sql/plan: PASS
  • focused -race -count=10: PASS
  • TestIssue277xxDDLConsistency two-CN public SQL regression: PASS
  • independent review: APPROVE / no blocker

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

Blocking correctness issue remains in the legacy self-FK path introduced here. remapAlterCopyForeignKeys deliberately recognizes ForeignTbl == oldTableID and rewrites it to newTableID (alter.go:2187-2200), but that makes reconcileAlterCopyParentForeignKeyReferences treat the replacement table itself as an ordinary external parent (2328-2356). With the normal self-reference reverse marker {0}, reconcileRefChildTableID cannot find oldTableID and appends newTableID, leaving duplicate semantic self references {0,newTableID}. With legacy reverse metadata {oldTableID}, the child pass at 1597-1604 attempts GetRelationById(oldTableID) after the old table has already been dropped. Either form can make an otherwise supported legacy self-FK ALTER COPY fail or persist inconsistent metadata. Please canonicalize self references as one unit: keep ForeignTbl and RefChildTableDef in the durable 0-sentinel form (or explicitly exclude the replacement self relation from external parent/child reconciliation), and add an ALTER COPY regression starting from ForeignTbl=oldTableID covering both reverse-marker forms. The two previous blockers are fixed. Focused compile/plan tests pass on exact head 632bdd3.

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

Re-reviewed exact head 632bdd32c39e5956223d2542558d10146811d8d6 against its current merge base and newest main. The previous blockers are closed: the live snapshot now merges/deep-copies all legacy FK containers and canonicalizes all reverse-reference containers, and hidden-index retry now requires a proven parent/index generation change so persistent same-generation absence returns the original error instead of spinning.

One blocking ALTER COPY correctness gap remains for legacy self-referencing foreign keys. remapAlterCopyForeignKeys recognizes ForeignTbl == oldTableID as self-reference but rewrites it to newTableID. reconcileAlterCopyParentForeignKeyReferences then includes newTableID in the ordinary parent set and updates the replacement relation as though it were external. With the durable reverse marker {0}, reconcileRefChildTableID cannot replace oldTableID and appends newTableID, persisting duplicate semantic self references {0,newTableID}. With the legacy reverse marker {oldTableID}, the child-reconciliation pass over sourceRefChildTbls attempts GetRelationById(oldTableID) after the old relation has been dropped and can fail the ALTER.

Canonicalize the self-FK as one unit: retain the durable zero sentinel in both ForeignTbl and reverse references, or explicitly exclude the replacement self relation from external parent/child reconciliation. Add full ALTER COPY regressions starting from ForeignTbl=oldTableID with both {0} and {oldTableID} reverse-marker forms, asserting one canonical self reference and no old-generation lookup. The other four DDL fixes, exact-set restoration, retry termination, cleanup, and public two-CN coverage are otherwise coherent.

@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 40a8dbc against declared base 46950ae. APPROVE; no remaining blocker.

The three prior blocker classes are closed:

  • live ALTER COPY snapshots merge and deep-copy every legacy ForeignKeyDef and canonicalize every RefChildTableDef;
  • a missing hidden-index relation retries only after a proven parent/index generation change, while same-generation persistent absence returns ErrNoSuchTable and terminates;
  • legacy self FKs now canonicalize ForeignTbl old-generation/0 and reverse old-generation/0 markers to the durable zero sentinel, and self references are excluded from external parent/child reconciliation.

The current consolidation restores FK and reverse-reference state in one exact UpdateConstraint and then reconciles only distinct external relations. The source snapshot is not mutated, empty sets remain authoritative, old-generation lookup is eliminated, and transaction failure paths retain rollback ownership. Q1-Q3 closure found no new resource owner, wait cycle, retry-without-progress path, or unbounded accumulation.

The other closures are coherent: duplicate CREATE defers to RelationExists without validating old reverse FKs against the ignored definition; PK/secondary alias metadata preserves public versus internal representations; qualified hidden-index DROP uses the planned database. Design gate is exempt because this is a bounded bug-fix series, not a new capability or architectural refactor.

Evidence reused on this exact head: focused compile/plan UT, focused race repetitions, the two-CN public DDL regression, and fully terminal green CI/SCA/build/BVT. Current main drift touches only unrelated ddl.go temp-table migration paths and does not invalidate these contracts.

@XuPeng-SH
XuPeng-SH merged commit fb56746 into matrixorigin:main Aug 29, 2026
17 of 20 checks passed
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…7799)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#27766, matrixorigin#27725, matrixorigin#27658, matrixorigin#27708, matrixorigin#27735

## What this PR does / why we need it:

This PR closes five related DDL consistency gaps with one shared
regression suite:

- restores ALTER COPY foreign keys and reverse references from the live
source relation, including authoritative empty sets;
- retries stale hidden-index generations instead of exposing internal
table names;
- keeps PRIMARY and secondary-index alias metadata consistent after
column rename;
- avoids rebuilding reverse foreign keys for duplicate CREATE TABLE
statements;
- qualifies hidden-index DROP TABLE statements when no default database
is selected.

The regression coverage validates the public SQL and catalog behavior on
a two-CN embedded cluster, with focused unit coverage for live FK
snapshots, exact replacement, retry classification, duplicate CREATE
planning, and PK metadata representations.

Co-authored-by: XuPeng-SH <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…7799)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#27766, matrixorigin#27725, matrixorigin#27658, matrixorigin#27708, matrixorigin#27735

## What this PR does / why we need it:

This PR closes five related DDL consistency gaps with one shared
regression suite:

- restores ALTER COPY foreign keys and reverse references from the live
source relation, including authoritative empty sets;
- retries stale hidden-index generations instead of exposing internal
table names;
- keeps PRIMARY and secondary-index alias metadata consistent after
column rename;
- avoids rebuilding reverse foreign keys for duplicate CREATE TABLE
statements;
- qualifies hidden-index DROP TABLE statements when no default database
is selected.

The regression coverage validates the public SQL and catalog behavior on
a two-CN embedded cluster, with focused unit coverage for live FK
snapshots, exact replacement, retry classification, duplicate CREATE
planning, and PK metadata representations.

Co-authored-by: XuPeng-SH <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…7799)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#27766, matrixorigin#27725, matrixorigin#27658, matrixorigin#27708, matrixorigin#27735

## What this PR does / why we need it:

This PR closes five related DDL consistency gaps with one shared
regression suite:

- restores ALTER COPY foreign keys and reverse references from the live
source relation, including authoritative empty sets;
- retries stale hidden-index generations instead of exposing internal
table names;
- keeps PRIMARY and secondary-index alias metadata consistent after
column rename;
- avoids rebuilding reverse foreign keys for duplicate CREATE TABLE
statements;
- qualifies hidden-index DROP TABLE statements when no default database
is selected.

The regression coverage validates the public SQL and catalog behavior on
a two-CN embedded cluster, with focused unit coverage for live FK
snapshots, exact replacement, retry classification, duplicate CREATE
planning, and PK metadata representations.

Co-authored-by: XuPeng-SH <[email protected]>
XuPeng-SH pushed a commit that referenced this pull request Oct 14, 2026
…29994)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Fixes #29954

Related to #29910: the production fix is already on main in #27799; this
PR adds regression coverage.

## What this PR does / why we need it:

Deleting a parent with no matching children can panic when an indexed
CASCADE child table contains unrelated rows. Direct DELETE appends these
recursive branches after planner tag remapping. Use a matched-only index
lookup and local input positions throughout untagged recursive deletes,
and keep runtime filters disabled to avoid a feedback wait cycle. Carry
the tagged self-referencing CASCADE source into its recursive context
before createQuery, so indexed REPLACE keeps the planner tags needed by
index scans, locks, and DELETE. Positional direct-DELETE actions still
use the matched-only local layout.

Add planner assertions and SQL regressions for empty and matching
cascades, single/composite/unique indexes, NULL keys, prepared deletes,
rollback, unrelated-row preservation, and RESTRICT controls. Cover
indexed self-referencing REPLACE with secondary/unique indexes,
recursive descendants, empty actions, forced-index reads, key reuse, and
subsequent direct DELETE. Extend the existing ALTER regression to cover
populated self references during VARCHAR resizing, including dropping
and re-adding the foreign key (#29910).

Validation:
- Review follow-up: the indexed self-referencing REPLACE planner
regression reproduces a panic at the previous PR head. After propagating
the descendant source tag, focused regressions and full `pkg/sql/plan`
tests pass (9.479s); package vet and configured incremental
golangci-lint pass.
- Updated indexed-cascade SQL regression passes normal mo-tester
comparison twice (128/128 each), with database teardown independently
checked before/between/after runs. Secondary-index EXPLAIN confirms that
the forced-index control uses an Index Table Scan.
- Rebased onto main `7af631bdf7`; full `pkg/sql/plan` tests pass with
repository CGo setup, Go 1.27.1, GOAMD64=v3, GOEXPERIMENT=simd.
- gofmt, diff checks, package vet, and configured incremental
golangci-lint pass.
- Before rebase, normal mo-tester comparisons passed: ALTER-integrity
81/81 statements; indexed cascade 102/102 twice; six related FK cases
681/681. The main update does not change the FK planner/ALTER paths; its
result-metadata evidence hook is opt-in and disabled in these tests.
- Actual COM_STMT_EXECUTE checks passed for single/composite indexes,
empty and matching deletes, rollback, and second-session isolation.
- On the clean pre-fix baseline, the original SQL reproduces the panic
and both new planner subtests fail.

This PR targets main; it does not include a v4.2.5 backport.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

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/bug Something isn't working size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants