Skip to content

fix(ddl): serialize foreign key validation with concurrent writes - #29066

Merged
mergify[bot] merged 5 commits into
matrixorigin:mainfrom
aptend:fix/28934-add-foreign-key-serialization
Sep 26, 2026
Merged

mergify[bot] merged 5 commits into
matrixorigin:mainfrom
aptend:fix/28934-add-foreign-key-serialization

Conversation

@aptend

@aptend aptend commented Sep 17, 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 #28934

What this PR does / why we need it:

A concurrent child update could commit while ALTER TABLE ... ADD FOREIGN KEY was waiting for the child-table lock. Validation could then read an older snapshot and publish a foreign key over an orphan row. A concurrent parent delete also needed a parent data lock, not just a catalog lock. Under REPEATABLE-READ/SI, a fixed old snapshot could remain stale even after the table lock reported a newer commit.

ADD FOREIGN KEY now opts into whole-table snapshot freshness for the child and each distinct, non-self parent. Under RC, after the lock is granted, it waits for the latest table commit to reach logtail and advances the snapshot before validation. Under SI, where the snapshot cannot be advanced, it rejects a newer table commit with a write conflict. Ordinary table locks retain their previous policy. Parent catalog and data locks are deduplicated; forward references remain catalog-only.

The lock work is bounded by the affected tables and FK actions, with no per-row work or new hot-path cost for ordinary locks. Exclusive parent/child locks intentionally serialize writes during FK validation.

Permanent two-CN tests exercise real SQL, transactions, lock watermarks, logtail visibility, validation, commit, rollback, and same-connection timeout recovery. They cover child-writer-first, ALTER-first, parent-delete-first, and stale SI snapshot cases. Failure paths require absent mo_foreign_keys and parent RefChildTbls metadata. The SI test was red on the prior implementation: ALTER incorrectly succeeded after another CN committed an orphan row.

Validation at final head f7509dd, rebased on main b457977:

  • Non-empty focused integration-test selection.
  • Focused two-CN integration test: -race -count=5, PASS in one process (29.275s).
  • Full lockop and compile package suites: -race -count=1, both PASS (5.931s / 7.238s).
  • Pre-rebase go vet and incremental golangci-lint passed; range-diff confirms the four PR patches are identical after rebase.

CI for the new head is pending; this PR does not claim a CI result.

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

@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Sep 17, 2026
@mergify mergify Bot added the kind/bug Something isn't working label Sep 17, 2026
@aptend aptend changed the title fix(lock): refresh stale snapshots for table locks fix(ddl): serialize foreign key validation with concurrent writes Sep 17, 2026

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

GPT-6 high review — REQUEST_CHANGES at exact head fefcb9d.

[P2] Focused repeated race evidence remains missing. The PR description reports a focused race-enabled integration test, but the prior gate requested -race -count=5 with a nonempty test selection on the current head. Current CI and one race pass do not prove in-process fixture/hook restoration across repetitions. Please provide terminal exact-head output. No new implementation blocker found.

@XuPeng-SH

Copy link
Copy Markdown
Contributor

Fixed the REPEATABLE-READ/SI stale-snapshot case and rebased the PR onto main at b457977; final head is f7509dd.

The new two-CN regression establishes an SI snapshot before another CN commits an orphan child update. It confirms that the SI transaction still sees the old row, then requires ADD FOREIGN KEY to reject the stale snapshot and leave no FK metadata. With the production fix temporarily removed, this same test failed because ALTER incorrectly succeeded. Unit controls cover newer/equal/older table commits and ordinary table-lock policy.

Exact final-head validation:

  • Non-empty selection: -list "^TestIssue28934AddForeignKeyLockOrdering$" printed the named test.
  • .agents/skills/mo-dev/scripts/mo-cgo-test -race -count=5 -timeout=10m -run "^TestIssue28934AddForeignKeyLockOrdering$" ./pkg/tests/issues — PASS, 29.275s, five repetitions in one process.
  • .agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=10m ./pkg/sql/colexec/lockop ./pkg/sql/compile — both PASS (5.931s / 7.238s).

Rebase completed without conflicts, and git range-diff confirms all four PR patches are identical after rebase. This supplies the previously requested repeated-race evidence on the current head; CI is not being claimed here.

@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 of head f7509ddd0091945b4e6d91906c4a59e423eb592e against base b457977980137e5056be18f03b22da6fc31908e0: APPROVE. No actionable correctness, liveness, resource, performance, or engineering-quality blocker found.

Reviewed every changed hunk in all six files and traced the three behavioral closures: table-lock snapshot freshness; ADD FK child/parent catalog and data locking through validation and transaction completion; deterministic test synchronization, cleanup, and reuse. This is an ordinary bug fix, so the large-feature design-document gate does not apply.

Previous review requests are addressed:

Request Verified closure
Real writer commit → lock watermark → logtail visibility → FK validation Two-CN child-writer-first, ALTER-first, and parent-delete-first cases exercise the SQL path and assert serializable results.
Timeout/retry without locks or partial metadata The timeout case checks removal of the ALTER holder/waiter, absent FK catalog and parent RefChildTbls, then succeeds on the same connection.
Repeated race proof at the current commit Non-empty selection and -race -count=5 PASS at f7509dd: 29.275s, five repetitions in one process.

The added SI regression is also meaningful: it establishes an old snapshot, commits an orphan from the other CN, verifies the old snapshot remains visible, and requires ADD FK rejection. The same scenario failed without the SI fix. Newer/equal/older timestamps and ordinary table-lock controls are covered by focused UTs.

Unhappy-path audit:

Dimension Result
Ownership Packers/vectors/results have cleanup owners. Transaction locks remain transaction-owned through validation and commit/rollback; statement errors in an explicit transaction do not imply premature unlock.
Wait termination Local/remote lock waits retain cancellation/deadline handling; logtail waits observe context cancellation; timeout cleanup and connection reuse have public-path evidence.
Bounded state Parent deduplication is bounded by ALTER actions. No new background worker, persistent queue, or unbounded cache is introduced.

Adjacent paths checked: multiple/self/cross-database parent handling, unresolved-parent guards, definition-change retry, competing DML metadata locks, COPY ALTER's separate insert-validation path, and LOAD unique-index promotion's RC-only eligibility and stronger global freshness barrier. No additional mechanism or refactor is needed for this fix.

Performance tradeoff: exclusive parent/child locks intentionally block writes during validation. Additional work is per affected table/action, not per data row; the existing validation scan remains. This review does not claim a measured throughput or latency improvement.

Reused the verified current-commit integration race result above and complete owning-package race passes: lockop 5.931s, compile 7.238s. Normal package/static results and rebase patch-identity evidence were reconciled. No identical tests were rerun solely for another review stage. Remote CI is still running and is not represented as passed.

@mergify

mergify Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-26 10:59 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-09-26 12:03 UTC · at b1b68925d7f6fb32153e788b5285f424222e85ca · squash

This pull request spent 1 hour 4 minutes 5 seconds in the queue, including 1 hour 3 minutes 49 seconds running CI.

Required conditions to merge

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/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants