Skip to content

fix(frontend): persist data branch database identity - #28272

Merged
XuPeng-SH merged 13 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-26068-d5143fac
Sep 16, 2026
Merged

XuPeng-SH merged 13 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-26068-d5143fac

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Sep 5, 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:

Related to #26068

What this PR does / why we need it:

Root cause

Database-branch identity was inferred only from active ordinary-table rows in mo_branch_metadata. A successfully created branch database therefore lost all recognizable identity when its source had no ordinary tables, or after all cloned ordinary tables were dropped. DATA BRANCH DELETE DATABASE could not distinguish that database from an ordinary database and rejected the delete.

Implementation

  • Persists the categorical data-branch identity in the existing mo_database.dat_type field as part of the same internal CREATE DATABASE operation.
  • Uses one cluster-wide MORPCVersion75 gate for every producer and consumer: create, delete, publication classification, logical snapshot restore, PITR, and account/cluster restore.
  • Rejects branch-database creation below v75 before DDL; at v75 it writes the marker atomically.
  • Keeps table-receipt validation for every ordinary table. The database marker handles only the previously ambiguous empty, view-only, sequence-only, and all-tables-dropped cases.
  • Makes ALTER PUBLICATION classify the effective persisted database even when the statement omits a DATABASE clause, including correct cross-account owner resolution.
  • Preserves statement-local clone context across reusable ExecCtx instances.
  • Serializes branch database deletion against concurrent object DDL using the existing exclusive mo_database catalog-row lock.
  • Restores the marker from authoritative dat_type data and preflights snapshot and PITR source identities at their public restore entries before target-account creation, account deletion, session kill, view-metadata invalidation, foreign-key cleanup, table restore, or database replacement.
  • Adds focused unit, embedded lifecycle, concurrency, restore, multi-statement, and BVT coverage.

Compatibility

Current main owns protocol versions v64 through v74, with v74 assigned to corrected numeric HEX overload identities. This rebased PR claims the next continuous version, v75; it does not depend on #27716 or #28903. Concurrent PR #28950 must merge afterward as v76; the allocation order is recorded in both PRs.

Below v75, new branch-database creation and marked restore input fail before mutation, while existing table-backed branches continue to use table receipts. Downgrade does not erase markers. Re-enabling v75 restores marker-aware behavior without migration. No catalog schema migration is required because dat_type already exists and is persisted by backup/checkpoint/replay.

The exact design revision is data-branch-database-identity-2026-09-16-r20. Revision r20 keeps the v75-then-v76 allocation order and v74/v75 boundary coverage, and moves cluster, account, database, and table snapshot/PITR admission ahead of irreversible account, metadata, FK, and object side effects.

Validation

  • go test ./pkg/frontend -run 'Test(DataBranchDatabaseIdentityCapability|DataBranchCreateDatabaseRejectsBeforeExecutorBelowCapability|PrepareLogicalRestoreDatabaseCapability|NewLogicalRestoreDatabaseDefinitionRequiresTypeColumn|PreflightLogicalRestoreDatabases|ValidateDataBranchDeleteDatabaseTargetUsesDatabaseIdentity|LoadBranchDatabaseTypeRejectsMissingDatabase|InstallDataBranchCloneContextRestoresRequestContext|IsUserDatabaseType|DoAlterPublicationDataBranchIdentityCapability|MarkedDatabaseRestoreRejectsBeforeDestructiveWorkBelowCapability|MarkedAccountRestorePreflightsBeforeDestructiveWorkBelowCapability|ClusterRestorePreflightsBeforeAccountSideEffects|MarkedTableSnapshotRestorePreflightsBeforeFkSideEffects|RestorePitrPreflightsBeforeAccountCreation|RestorePitrPreflightsBeforeExistingAccountSideEffects|MarkedDatabaseRestorePreservesIdentityAtCapability)$' -count=1
  • go test ./pkg/tests/issues -run TestIssue26068DataBranchDatabaseIdentityLifecycle -count=1
  • go test ./pkg/sql/compile -run TestCreateDatabaseChecksExistingBeforeSerializingAbsence -count=1
  • git diff --check origin/main...HEAD

All commands above pass after syncing current main; go test ./pkg/frontend -count=1 also passes on PR head a1d4fa4ad6ea2a93643c665c38ceec85ae2bb0b7. Isolated TestScope_Database fails with the same missing lock service panic on both this branch and exact base 2ea4ec2e6ef4b20321a235ef416228506813e39b; the PR does not modify that DropDatabase lineage-lock path.

CI run 34948994437 passed the shared build, arm64 SCA, UT coverage, and both Compose BVT jobs. Ubuntu/x86 UT ended after 71m43s with the global timeout (Error 124) while unrelated fileservice and vm/engine tests were still active; no #28272-owned test reported a failure. The preceding rebased head 55339dc completed Ubuntu/x86 UT and all required checks successfully. On pre-rebase head 2d2af51450241340058720fe786d55a64d1db784, all build, SCA, and BVT checks passed. The two unrelated failures were rerun after their logs established infrastructure or shared-runner causes: Ubuntu/x86 UT passed in about 49 minutes, and UT Coverage passed in about 30 minutes. On preceding head 81d463a7922448f5713ce10f9463a396e6876ba7, build, arm64 SCA, UT Coverage, both BVT jobs, and the authorized Ubuntu/x86 UT rerun all passed. Rebased review-fix head 822050e783141dc047260991d1b8c6d67e57c474 passed build, arm64 SCA, UT Coverage, Ubuntu/x86 UT, and both Compose BVT jobs. Current restore-entry review-fix head a1d4fa4ad6ea2a93643c665c38ceec85ae2bb0b7 is running CI. The diff is confined to data-branch database identity, its producer/consumer/restore paths, design, and tests; no CI workflow is changed.

@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 25fe6784bcfe31929ec646a9ca860a12d46d54fc across catalog ownership, delete safety, legacy fallback, cross-account creation, publication consumers, rollback, BVT isolation, and mixed-version operation. The local implementation is internally coherent: the marker is written atomically with CREATE DATABASE; ordinary empty/subscription/unknown targets remain rejected; every present ordinary table still needs an active receipt; and focused UT/BVT cover the intended success and safety cases. One mandatory persistent-contract/rollout blocker remains.

[P1] Design and gate the new persistent database type for mixed-version clusters

This PR introduces a new durable mo_database.dat_type value and changes DATA BRANCH DELETE semantics, but the repository’s approved docs/design/data_branch_privilege.md still fixes the opposite contract: empty/view-only/sequence-only databases must fail closed, and database-level branch identity requires a separate design/implementation step. The PR neither updates that versioned design nor records an approved replacement decision, migration/rollback contract, or capability gate.

This is already a concrete mixed-version failure, not documentation drift. A new CN writes dat_type = data-branch; an old CN treats every non-empty dat_type as a non-user database in create/alter publication validation, so the same branch database accepts or rejects publication operations depending on which CN receives the request. Conversely, an old CN can create an empty/view-only branch without the marker, and a new CN must permanently reject its DATA BRANCH DELETE because there is no trustworthy identity to recover. During rollout, persistent state and user-visible behavior are therefore CN-version-dependent.

Please update the design document and obtain the required design decision for the marker/identity model, including upgrade, downgrade/rollback, mixed-version creation/deletion/publication behavior, and backup/restore. Implement a rollout/capability rule that prevents new persistent semantics from being emitted until all eligible CNs can consume them (or provide another reviewed compatibility mechanism). Add deterministic mixed-version/capability tests for old-created and new-created empty and table-backed branches. Merely documenting the current inconsistency as a residual risk is not sufficient for a new catalog contract.

No separate hot-path, unbounded-state, wait, cleanup, privilege, or SQL-injection blocker was found in the reviewed implementation.

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

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

发现两个 P1 阻塞项:

  1. 协议能力版本 v75 存在并行占用。当前 PR 在 pkg/defines/const.go:113-114 为 branch identity 宣布 v75,而 #28950 也在同一位置为 typed JSON MIN/MAX 宣布 v75。这样分阶段部署时,worker 可能通过 capability 检查却仍使用旧的 JSON 字节序比较,远程 partial MIN 可能把 256 和 1 的结果错误保留为 256。请统一累计协议版本的分配和合并顺序,并补 v74/v75 边界测试;当前负例仍使用 v73。

  2. cluster restore 的 preflight 检查发生在不可逆的账号副作用之后。snapshot_restore_with_ts.go:296 的检查是在 snapshot.go:3166 删除快照中不存在的账号之后才到达;doDropAccount 会触发连接终止和跨 CN kill 请求,之后 marker 检查才拒绝 restore,catalog rollback 无法撤销这些断连。请在删除账号及外键清理前预检所有 source identities,并增加入口级回归,证明不产生 destructive DDL/account kill/CDC。

此前 context leak、delete lock、ALTER bypass、publication owner 修复仍在。

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Addressed both P1 findings in 822050e783 (rebased onto current main):

  1. v75 allocation collision: fix(frontend): persist data branch database identity #28272 keeps v75 because it predates and is further through review/CI; fix: support JSON values in MIN and MAX #28950 must merge afterward as v76. The coordination is recorded on fix: support JSON values in MIN and MAX #28950: fix: support JSON values in MIN and MAX #28950 (comment). All capability negative tests now use the immediate predecessor v74, with v75 positive coverage.
  2. cluster restore preflight ordering: restore admission now scans every source account/database identity before target-account creation, account deletion, session/cross-CN kill, metadata invalidation, FK cleanup, or database replacement. TestClusterRestorePreflightsBeforeAccountSideEffects exercises the public cluster restore entry and proves execution stops before destructive SQL/account side effects.

Focused frontend tests and git diff --check pass after the rebase. Fresh CI is running on head 822050e783141dc047260991d1b8c6d67e57c474. Please re-review these two blockers.

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

新 head 复审仍有两个阻塞项(当前 822050e):

P1:PITR 可能在拒绝不支持的 identity 前提交账号创建。pkg/frontend/pitr.go:1065 的 createDroppedAccount 会调用 InitGeneralTenant,内部自行 BEGIN/COMMIT;随后 restoreDatabaseFromTS 才拒绝 marker,外层 rollback 无法撤销已提交的账号创建。已有账号的 PITR 也会在 admission 前做 metadata invalidation/FK cleanup。请在 doRestorePitr 的这些操作前预检 source identities,并增加入口级回归,证明拒绝时没有 account creation、commit 或 destructive SQL。

P2:table snapshot restore 绕过了早期 admission。pkg/frontend/snapshot.go:987 对 marked source database 跳过 preflight,先在 line 845 执行 deleteCurFkTables,再在 line 1425 prepareLogicalRestoreDatabase 拒绝,可能已发生 table DROP、index consumer draining 等副作用;且 lower-level table path 本身会执行 CREATE DATABASE IF NOT EXISTS。请在 FK-linked target 上通过 doRestoreSnapshot 测试,证明拒绝先于 DROP/CREATE 和 consumer side effects。

另外请保持协议版本分配顺序:#28272 使用 v75;#28950 应 rebase 后改用 v76。

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Both findings are valid and fixed in a1d4fa4ad6:

  1. PITR admission: doRestorePitr now preflights account/database/table source identities before dropped-account creation, metadata invalidation, FK cleanup, or object restore. Cross-account source resolution is performed once and reused. Cluster PITR enters the existing all-account preflight before generic FK cleanup. Entry regressions cover both a missing target account (no CREATE ACCOUNT or COMMIT) and an existing account (no metadata invalidation, FK query, DROP, or COMMIT).
  2. Table snapshot admission: table restore now shares database-level entry preflight. The regression configures an FK-linked target and calls doRestoreSnapshot; rejection occurs before the FK catalog is queried and before any DROP/CREATE/consumer-triggering DDL.

Validation: the focused restore/identity suite passes, full go test ./pkg/frontend -count=1 passes, and git diff --check passes. Design revision is now r20. Fresh CI is running on exact head a1d4fa4ad6ea2a93643c665c38ceec85ae2bb0b7. Please re-review.

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

新 head 复审通过(当前 a1d4fa4):此前两个阻塞项均已关闭。

  1. PITR:pitr.go:1054 在 createDroppedAccount/metadata invalidation/FK cleanup 前预检 historical source identities;新的 doRestorePitr 回归验证 rejection 时无 commit 或 destructive SQL。
  2. table snapshot restore:snapshot.go:806 在 target resolution/FK cleanup 前执行 admission;新的 doRestoreSnapshot + FK-linked target 回归验证无 FK query、DROP、CREATE 或 commit。

Exact-head CI build、UT、coverage、SCA 和两个 Compose BVT jobs 全部通过。

合并顺序要求:本 PR 占用 v75,应先合并;#28950 必须 rebase 并改用 v76,同时补 v75 rejection/v76 acceptance boundary evidence,避免 capability check 错误放行不兼容执行。

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 kind/documentation Improvements or additions to documentation kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants