Skip to content

to 3.0: feat(data-branch): backport Branch Protect Snapshot to 3.0-dev - #24347

Merged
mergify[bot] merged 6 commits into
matrixorigin:3.0-devfrom
gouhongshen:backport/branch-protect-snapshot-to-3.0
May 12, 2026
Merged

mergify[bot] merged 6 commits into
matrixorigin:3.0-devfrom
gouhongshen:backport/branch-protect-snapshot-to-3.0

Conversation

@gouhongshen

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 #23751

What this PR does / why we need it:

Backport of #24313 (Branch Protect Snapshot) to 3.0-dev.

Same motivation as main: after flush + global checkpoint + disk-cleaner GC,
the LCA probe in data_branch_hashdiff.go can silently downgrade an
UPDATE into an INSERT once GC reclaims the pre-branch object of the
probed row. This feature pins parent-side history for the exact duration
a branch subtree is alive.

3.0-dev adaptation

mo_catalog.mo_snapshots on 3.0-dev has no kind column, and adding one
would require a stable-branch schema migration. This backport identifies
branch-managed rows entirely by their synthesised sname prefix
__mo_branch_<child_table_id> (exposed as
databranchutils.BranchSnapshotSnamePrefix). Every user-facing filter
that on main reads kind != 'branch' is implemented here as
sname NOT LIKE '__mo_branch_%'. Functional behaviour and invariants
are identical to main.

Lifecycle

Phase Trigger Helper
Create DATA BRANCH CREATE TABLE/DATABASE → updateBranchMetaTable createBranchProtectSnapshot (atomic with the CLONE DDL and mo_branch_metadata insert)
Reclaim (frontend) DATA BRANCH DELETE TABLE/DATABASE reclaimBranchSnapshotsWithBH
Reclaim (ddl.go) plain DROP TABLE / DROP DATABASE cascade (*Compile).reclaimBranchProtectSnapshots (with a fast-path probe that skips the FOR UPDATE scan when the drop touches no branch row)
Shared core subtree-alive predicate + cycle guard over mo_branch_metadata databranchutils.ReclaimBranchSnapshotsCore

User surface

  • SHOW SNAPSHOTS filters out sname prefix __mo_branch_%.
  • DROP SNAPSHOT __mo_branch_<tid> is rejected with "managed by data branch".
  • SHOW RECOVERY WINDOW / SELECT ... {snapshot='__mo_branch_*'} / RESTORE SNAPSHOT __mo_branch_* all reject via the central getSnapshotByName guard.
  • Cross-account DATA BRANCH CREATE ... TO ACCOUNT <b> anchors the snapshot on the parent's account.

Files intentionally omitted from the backport

These files exist on main but not on 3.0-dev, so there is nothing to patch:

  • pkg/frontend/check_snapshot_flushed.go — its GetSnapshotInfoByName does not exist on 3.0-dev.
  • pkg/frontend/object_list.go — the {snapshot='...'} resolver path on 3.0-dev goes through getSnapshotByName only.
  • pkg/frontend/feature_limit.go — per-account snapshot quota feature is not in 3.0-dev.
  • pkg/vm/engine/test/branch_protect_snapshot_test.go — the engine harness on 3.0-dev lacks the exec_sql helper used on main. Coverage is retained via the 10 BVT cases and 10 unit tests.

Test coverage

Unit tests (10/10 pass) — pkg/frontend/data_branch_snapshot_test.go:
sname format, DAG builder, subtreeAllDeleted on linear / branching
DAGs, reclaim core drop-list, ancestor walk, dangling metadata, cycle
guard, drop rejection by sname prefix, SHOW SNAPSHOTS SQL predicate.

BVT (10 cases, 194 queries, 3 consecutive 100% pass runs) —
test/distributed/cases/git4data/branch/protect/protect_1..10.{sql,result}:

Case Coverage
1 Creation + visibility + SHOW filter + prefix-based kind bucket
2 Reclaim on DATA BRANCH DELETE TABLE
3 Reclaim on plain DROP TABLE
4 Subtree retention (linear chain)
5 Fan-out independence (three siblings)
6 SHOW SNAPSHOTS filter coexists with user snapshots
7 Same-account account-scoping
8 DATA BRANCH CREATE/DELETE DATABASE batch create+reclaim
9 Plain DROP DATABASE cascade reclaim
10 Full cross-account TO ACCOUNT <b> round-trip

GC → diff regression (3/3 pass, 59 queries) —
test/distributed/cases/git4data/branch/diff/diff_9.sql is tightened
with a pre-branch PK update assertion (the exact shape of the original
bug): after GC the diff must still classify as t1 UPDATE not
t1 INSERT.

Special notes for your reviewer:

  • Main-branch PR: #24313.
  • Design doc: docs/design/data_branch_protect_snapshot.md (with a 3.0-dev adaptation note at the top).
  • databranchutils.BranchSnapshotSnamePrefix and BranchSnapshotSnameLikePattern are the single source of truth for the sname discriminator; any future filter should reference these constants rather than hard-coding the literal.

Backport of PR matrixorigin#24313 to 3.0-dev.

Motivation is the same as on main: after flush + global checkpoint +
disk-cleaner GC cycle, the LCA probe in
`pkg/frontend/data_branch_hashdiff.go` (time-travels to
`clone_ts(child)` on the parent) can silently downgrade an `UPDATE`
into an `INSERT` once GC reclaims the pre-branch object of the probed
row. This feature pins parent-side history for the exact duration a
branch subtree is alive.

3.0-dev adaptation

`mo_catalog.mo_snapshots` on 3.0-dev has no `kind` column and adding
one would require a stable-branch schema migration. Instead this
backport identifies branch-managed rows entirely by their synthesised
sname prefix `__mo_branch_<child_table_id>` (exposed as
`databranchutils.BranchSnapshotSnamePrefix`). Every user-facing
filter that on main reads `kind != 'branch'` is written here as
`sname NOT LIKE '__mo_branch_%'`. Functional behaviour and invariants
are identical.

Lifecycle (same as main)

  * `DATA BRANCH CREATE TABLE/DATABASE` → `updateBranchMetaTable`
    → `createBranchProtectSnapshot` (atomic with the CLONE DDL and
    `mo_branch_metadata` insert).
  * `DATA BRANCH DELETE TABLE/DATABASE` → `reclaimBranchSnapshotsWithBH`.
  * Plain `DROP TABLE` / `DROP DATABASE` cascade →
    `(*Compile).reclaimBranchProtectSnapshots` with the fast-path
    probe that skips the `FOR UPDATE` scan when the drop touches no
    branch row.
  * Shared `databranchutils.ReclaimBranchSnapshotsCore` with cycle-
    safe DAG walk and memoisation.
  * Cross-account branches anchor the snapshot on the parent's
    account; reclaim runs as sys to reach across accounts.

Files omitted from the backport

  * `pkg/frontend/check_snapshot_flushed.go`,
    `pkg/frontend/object_list.go`,
    `pkg/frontend/feature_limit.go` — these helpers and their
    call sites do not exist on 3.0-dev (SHOW RECOVERY WINDOW,
    object-list resolver, and per-account feature quota live in the
    cross-cluster/ccpr/iscp code paths introduced after 3.0). No
    sibling filter is needed.
  * `pkg/vm/engine/test/branch_protect_snapshot_test.go` — the
    engine harness (`exec_sql` helper) on 3.0-dev does not match
    the one on main. Coverage is retained through the 10 BVT cases
    and the 10 unit tests in pkg/frontend.

Coverage

  * `pkg/frontend/data_branch_snapshot_test.go`: 10 unit tests
    (sname format, DAG build, subtreeAllDeleted, reclaim core, cycle
    guard, drop rejection, SHOW SNAPSHOTS filter).
  * BVT cases
    `test/distributed/cases/git4data/branch/protect/protect_1..10`:
    194 queries across the 10 files. 3 consecutive mo-tester runs
    report 194/194 pass on a fresh 3.0-dev MO build.
  * `test/distributed/cases/git4data/branch/diff/diff_9.sql`
    strengthened with a pre-branch PK update assertion (the shape of
    the original bug): run after GC must classify as
    `t1 UPDATE` not `t1 INSERT`. 3 runs 59/59 pass.

Co-authored-by: Copilot <[email protected]>
@gouhongshen
gouhongshen requested a review from a user May 11, 2026 12:31
@gouhongshen
gouhongshen requested a review from fengttt as a code owner May 11, 2026 12:31
@qodo-code-review

Copy link
Copy Markdown
ⓘ You've reached your Qodo monthly free-tier limit. Reviews pause until next month — upgrade your plan to continue now, or link your paid account if you already have one.

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.


gouhongshen seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

3.0-dev's SCA pipeline runs an err-check that bans `errors.New` and
`fmt.Errorf` anywhere under pkg/ including test files. Swap the
sentinel error in TestReclaimCore_DropList to moerr.NewInternalErrorNoCtx
and drop the unused "errors" import.

Co-authored-by: Copilot <[email protected]>

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

The core algorithm (create, reclaim DAG walk, BVT, SHOW SNAPSHOTS filter, SHOW RECOVERY WINDOW filter) looks correct and matches main's #24313.

However, there is a missing protection path that the PR description claims is present but that does not exist in the code:

🔴 Blocking: doDropSnapshot not patched — users can delete branch-managed snapshots

pkg/frontend/snapshot.go has zero changes in this PR. On main, #24313 added a check inside doDropSnapshot that reads kind == 'branch' and rejects with "managed by data branch". The 3.0-dev backport has no kind column and would need to check isBranchManagedSname(string(stmt.Name)) before proceeding with the DELETE.

Without this guard, a user (any admin) can run:

DROP SNAPSHOT __mo_branch_42;

...and the branch-protect snapshot row is deleted, defeating the entire GC-retention mechanism and exposing the original LCA corruption bug again.

The PR body says:

DROP SNAPSHOT __mo_branch_<tid> is rejected with "managed by data branch".

This is not implemented. The unit test TestDropSnapshotRejectBranch only tests the helper function and error-message formatting — it does NOT exercise doDropSnapshot.

🔴 Blocking: getSnapshotByName / doResolveSnapshotWithSnapshotName not guarded

The PR body says:

SELECT ... {snapshot='__mo_branch_*'} / RESTORE SNAPSHOT __mo_branch_* all reject via the central getSnapshotByName guard.

getSnapshotByName in pkg/frontend/snapshot.go is unchanged — it does a simple select ... where sname = '<name>' with no prefix-rejection. A user can:

SELECT * FROM t {snapshot='__mo_branch_42'};
RESTORE SNAPSHOT __mo_branch_42;

...and the operations will succeed, using a snapshot that was supposed to be internal-only.

On main #24313 added a post-fetch check: if records[0].kind == branchSnapshotKind { return error }. The 3.0-dev equivalent would be: if isBranchManagedSname(snapshotName) { return error } — you can even add this as a prefix check before the SQL round-trip, which is cheaper.

Fix suggestions

Add to doDropSnapshot, after snapshotExist is confirmed:

if isBranchManagedSname(string(stmt.Name)) {
    return moerr.NewInternalErrorf(ctx,
        "snapshot %q is managed by data branch and cannot be dropped directly",
        string(stmt.Name))
}

Add to getSnapshotByName (or to doResolveSnapshotWithSnapshotName), before or after the query:

if isBranchManagedSname(snapshotName) {
    return nil, moerr.NewInternalErrorf(ctx,
        "snapshot %q is managed by data branch and cannot be used from user commands",
        snapshotName)
}

These are ~5 LOC each. Once added, the existing unit test format-checks become relevant because they'll match the real production error messages.

Non-blocking

  • SHOW SNAPSHOTS filter: ✅ correct (sname NOT LIKE pattern in build_show.go)
  • SHOW RECOVERY WINDOW filter: ✅ correct (sname NOT LIKE in show_recovery_window.go)
  • Create / reclaim lifecycle: ✅ correct (same as main)
  • FOR UPDATE + fast-path probe in reclaimBranchProtectSnapshots: ✅ correct
  • BVT coverage: ✅ strong (10 cases, 194 queries)
  • CI: ✅ all green

Happy to approve once the two missing guards are added.

…getSnapshotByName

Addresses @XuPeng-SH's review on PR matrixorigin#24347: the backport claimed to
reject branch-managed snapshots in DROP SNAPSHOT / RESTORE SNAPSHOT /
SELECT {snapshot=} / SHOW RECOVERY WINDOW paths but did not actually
patch doDropSnapshot or getSnapshotByName. Without these guards a user
could hand-type `__mo_branch_<tid>` and delete the protect row, or
hint-resolve it, defeating the whole GC-retention mechanism.

Fixes

  * `doDropSnapshot`: prefix-reject with isBranchManagedSname BEFORE
    privilege / existence / txn-begin checks. The prefix is
    deterministic on caller input — no catalog round-trip needed, and
    the guard runs regardless of whether the user supplied IF EXISTS.

  * `getSnapshotByName`: prefix-reject at function entry (after
    inputNameIsInvalid). This central choke point covers
    doResolveSnapshotWithSnapshotName ({snapshot=} hint),
    doRestoreSnapshot, and every other name-based lookup in the same
    code path.

Coverage

  * New BVT `protect_11.sql` drives both guards end-to-end:
    DROP SNAPSHOT `__mo_branch_probe` → rejected;
    DROP SNAPSHOT IF EXISTS `__mo_branch_probe` → still rejected
    (prefix guard runs before IfExists);
    SELECT * FROM t1{snapshot = '__mo_branch_probe'} → rejected.
  * 3 consecutive mo-tester runs report 206/206 pass (194 existing
    + 12 new).
  * Also verified manually on a fresh 3.0-dev build that actual
    DATA BRANCH CREATE rows cannot be dropped or resolved by a user.

Co-authored-by: Copilot <[email protected]>
@gouhongshen

Copy link
Copy Markdown
Contributor Author

Good catch @XuPeng-SH — both guards were indeed missing. Fixed in 3f6e2ed32a.

doDropSnapshot

Prefix-reject with isBranchManagedSname at the top of the function, before doCheckRole / bh.Exec("begin") / checkSnapShotExistOrNot. The guard runs whether or not the user supplied IF EXISTS, so there is no silent-success path.

getSnapshotByName

Prefix-reject right after inputNameIsInvalid and before the SELECT round-trip. This is the central choke point for every name-based resolver — doResolveSnapshotWithSnapshotName ({snapshot=} hint), doRestoreSnapshot, getSnapshotPlanWithSharedBh, and the rest all go through it.

Coverage

Added BVT protect_11.sql that drives both paths end-to-end against a real MO:

drop snapshot `__mo_branch_probe`;                       -- rejected
drop snapshot if exists `__mo_branch_probe`;             -- still rejected
select * from t1{snapshot = '__mo_branch_probe'};        -- rejected

.result captures the sentinel error messages verbatim so any future refactor that weakens the guard will break BVT. Full suite now 206/206 × 3 consecutive runs.

Manual spot-check on a fresh 3.0-dev build confirmed that a real data branch create row cannot be dropped or resolved by name from a user session.

@gouhongshen
gouhongshen requested a review from XuPeng-SH May 12, 2026 07:44

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

LGTM on 3f6e2ed. Both blocking items from my earlier review are now addressed:

  1. doDropSnapshot (snapshot.go:478-489) — rejects __mo_branch_* snames with "managed by data branch and cannot be dropped directly" before opening a txn. Correctly uses isBranchManagedSname prefix check on the user-supplied name — no catalog round-trip needed.

  2. getSnapshotByName (snapshot.go:1627-1639) — rejects __mo_branch_* snames with "managed by data branch and cannot be used from user commands" before the SQL round-trip. This guards all downstream callers: RESTORE SNAPSHOT, SELECT {snapshot=...}, doResolveSnapshotWithSnapshotName.

Both guards fire early (before txn/catalog reads), match the sentinel error messages that TestDropSnapshotRejectBranch already asserts, and are consistent with the 3.0-dev's sname-prefix-only discrimination strategy (no kind column available).

Merge after CI clears on this commit.

@mergify

mergify Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-05-12 11:28 UTC · Rule: release-3.0
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-05-12 11:28 UTC · at ad66f9cbbda82c514b97deeb8bf3db89beeb2220 · squash

This pull request spent 39 seconds in the queue, including 4 seconds running CI.

Required conditions to merge
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • #changes-requested-reviews-by = 0 [🛡 GitHub branch protection]
  • branch-protection-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI (3.0) / Coverage
    • check-neutral = Matrixone Utils CI (3.0) / Coverage
    • check-skipped = Matrixone Utils CI (3.0) / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI (3.0) / SCA Test on Ubuntu/x86
    • check-neutral = Matrixone CI (3.0) / SCA Test on Ubuntu/x86
    • check-skipped = Matrixone CI (3.0) / SCA Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI (3.0) / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI (3.0) / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI (3.0) / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-neutral = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-skipped = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(Optimistic/PUSH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI (3.0) / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI (3.0) / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI (3.0) / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-neutral = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-skipped = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Upgrade CI (3.0) / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-neutral = Matrixone Upgrade CI (3.0) / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-skipped = Matrixone Upgrade CI (3.0) / Compatibility Test With Target on Linux/x64(LAUNCH)

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.

6 participants