Skip to content

test: synchronize data branch quota probe - #27848

Merged
mergify[bot] merged 1 commit into
matrixorigin:mainfrom
gouhongshen:agent/issue-27847-ac27c67c
Aug 29, 2026
Merged

mergify[bot] merged 1 commit into
matrixorigin:mainfrom
gouhongshen:agent/issue-27847-ac27c67c

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Aug 29, 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 #27847

What this PR does / why we need it:

Root cause

The fixture opened conn1 next SI transaction immediately after conn2 received a successful cleanup-delete response. That response confirms the TN commit, but it does not guarantee that the same CN has applied the delete logtail. The next SI snapshot could therefore use an older CN frontier and still see mode_probe.a = 2.

Changes

  • Assert that the cleanup delete affected exactly one row.
  • Commit a later write marker in the test account and wait for its commit frontier to apply on the same CN before conn1 opens the next SI transaction.
  • Assert that the marker transaction returned a non-empty commit timestamp, so the wait has a real write frontier.

The change is test-only; it adds no production behavior or fallback path.

Issue-to-test proof

TestIssue26087ConcurrentDataBranchQuota now proves the cleanup row was removed and that the next implicit SI transaction observes an applied frontier before checking both the empty probe table and DATA BRANCH transaction-mode behavior.

BVT is not appropriate: SQL BVT cannot observe the in-process CN logtail frontier that caused this intermittent fixture failure. The existing two-CN Go integration test is the direct test layer.

Tests

  • .agents/skills/mo-dev/scripts/mo-cgo-test -tags matrixone_test -count=20 -timeout=30m -run "^TestIssue26087ConcurrentDataBranchQuota$" ./pkg/tests/issues (pass, 122.547s)
  • .agents/skills/mo-dev/scripts/mo-cgo-test -race -tags matrixone_test -vet=off -count=1 -timeout=10m -run "^TestIssue26087ConcurrentDataBranchQuota$" ./pkg/tests/issues (pass, 52.579s)
  • .agents/skills/mo-dev/scripts/mo-cgo-test -tags matrixone_test -count=1 -timeout=30m ./pkg/tests/issues (pass, 92.918s)

Risks

The marker table and row exist only in the isolated test account. The added synchronization waits at most 10 seconds through the shared test helper and fails explicitly if the required logtail frontier is not applied.

@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 review complete; no blocking findings. The synchronization is causally sound: after the SI cleanup delete commits, a later write on the same TN provides a strictly later commit frontier, and WaitLogtailApplied on the same CN proves all logtail through that frontier is applied before conn1 opens its next SI snapshot. The exact affected-row assertion also fails closed if cleanup did not happen. Scope and cost stay test-only and bounded: one marker table owned by the disposable account, one marker row/transaction, and the existing 10s helper deadline; no production path, quota count, or public behavior changes. Exact-head CI passed twice, including the changed test in the exclusive race package (25.70s and 28.94s), plus coverage/package validation. APPROVE.

@mergify mergify Bot added the queued label Aug 29, 2026
@mergify

mergify Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-29 22:09 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-08-29 22:10 UTC · at 2197147eb9a01cb8108e4a94e8f4824936a3a09c · squash

This pull request spent 12 seconds in the queue, including 1 second running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)

@mergify
mergify Bot merged commit a15139d into matrixorigin:main Aug 29, 2026
49 of 50 checks passed
@mergify mergify Bot removed the queued label Aug 29, 2026
mergify Bot pushed a commit that referenced this pull request Aug 30, 2026
### Root cause

Fresh table clones copied the source row from `mo_catalog.mo_increment_columns` into the destination allocator. That row offset is the upper bound of a reserved allocation batch (10,000 in the reproducer), not the next source-session value (4). Because a fresh clone has a new table ID and an independent allocator, transferring that reservation made its first generated ID 10,001.

The persisted table definition separately carries explicit schema lower bounds such as `ALTER TABLE ... AUTO_INCREMENT = 100`. Those are user-visible state and must still be preserved.

### Changes

- For a fresh clone, reconstruct visible auto-increment state from the copied row maximum and the larger source/destination schema lower bound. Do not copy the source allocator reserved-batch upper bound.
- Continue copying raw allocator state for ALTER COPY paths that retain the column-ID space, where existing CN caches make that state part of the ownership handoff.
- Continue copying allocator state for hidden internal auto-increment columns; hidden index-table allocator handling is unchanged.
- Add unit coverage for the fresh-clone and ALTER COPY ownership boundaries, including a source schema lower bound larger than the destination lower bound.
- Add BVT coverage for table clone, database clone, both Data Branch forms, empty sources, deleted maximum IDs, explicit `AUTO_INCREMENT`, explicit transactions, and historical snapshots.
- Stabilize the five existing snapshot stored-procedure checks with `ORDER BY name` and `@sortkey:1`, while retaining `@ignore:0,9,10`; this changes neither the expected `proc_id` entries nor any non-ignored field assertion.
- Update table-clone and temporary-table-clone BVT expectations to assert contiguous IDs from the highest copied row instead of discarded source reservation batches.

### Issue-to-test proof

- The exact issue reproduction reports source next `4`, clone next `5`, and first cloned-table insert `4` for table, database, and both Data Branch clone forms.
- Empty sources insert `1`; a source whose largest row was deleted seeds the independent clone from the copied maximum; explicit `AUTO_INCREMENT = 100` inserts `100`; snapshot clone asserts snapshot-visible rows plus exact `4 / 5` inserted/next values.
- A permanent source cloned into a temporary table preserves copied IDs `10` and `11`, then assigns `12` to the first destination insert.
- Unit tests prove that fresh visible columns discard the persisted reservation while preserving the larger source/destination schema floor; ALTER COPY and hidden internal columns retain allocator state required by their ownership model.
- The existing chained-clone BVT proves subsequent clone and delete/insert sequences continue at `40001` through `40006`, without introducing a new 10,000-value gap at each clone.
- The snapshot/restore procedure checks still validate every catalog field except the pre-existing ignored ID and timestamp columns. Their deterministic unique `name` ordering prevents ignored allocator IDs from pairing one procedure with another.

### Verification

Latest semantic rebase: patch-equivalent head `1c9ff2e42bc751bd0028bcfe0cd51b8704071bcb` was rebased conflict-free from `main` at `a15139da62b938b0918c19675c619b259cd86460` onto `main` at `07fe9a69c6a3d6ed5e2b4299fb143d10bef442c0`, producing exact head `23c7a20c072375324fee984c087de370ef5bd323`.

- `git range-diff a15139d..1c9ff2e 07fe9a6..23c7a20`: all four clone patches are equivalent.
- Stable aggregate patch ID before and after the rebase: `ff530dfc6cb58fd343bc0663b95c917a95aa40fc`.
- The final diff is the intended six clone files plus two targeted snapshot BVT files; `git diff --check origin/main...HEAD` passed and the worktree is clean.
- On exact head `c3332623e5be8961a2c54bed286c888b75f82bee`, an isolated local MatrixOne service and mo-tester upstream/main `334d3e124bbfbdcd6b5cc63439278d172c72b706` passed `sys_restore_system_table_to_sys_account` twice with CI flags `-g -n -o`: 313/313 statements each time. Normal metadata mode also passed 313/313.
- A direct matcher negative-control proves the BVT assertion remains strict: ignored IDs `9/10` versus expected `1920000/1920001` fail under full-row sorting, while `ORDER BY name` plus `@sortkey:1` pairs rows correctly; mutations to each of the 14 non-ignored columns are rejected. `@sortkey:1` alone remains order-dependent, so it is deliberately paired with SQL ordering.
- Exact-head MatrixOne CGo validation selected and passed all eight focused clone allocator tests.
- Incoming main commit `07fe9a69c6 fix(embed): align HAKeeper transport timeout under race (#27849)` changes only embed/logservice configuration and its tests, with no PR-file overlap. All six directly affected tests passed: three embed timeout/config tests, two logservice client-config tests, and the authenticated two-CN fixture test.
- Because the incoming logservice change is a transitive dependency of the clone owners, the complete `pkg/sql/compile`, `pkg/frontend`, and `pkg/sql/colexec/table_clone` packages were rerun through the MatrixOne CGo wrapper and passed on exact head `23c7a20c07`.
- Workflow `33283224004` attempt 1 on exact head `23c7a20c07` passed shared build, normal Ubuntu UT, SCA, Coverage UT, and PROXY BVT. All three changed clone cases passed; PESSIMISTIC BVT reproduced only unrelated #27164, and aggregate Coverage was derivative.
- Attempt-2 PESSIMISTIC BVT job `99187224896` is in progress after the single permitted failed-job rerun.

### CI investigation

- #27164 remains the underlying mo-tester defect. Workflow `33283224004` attempt 1 reproduced its snapshot result-pairing mismatch in PESSIMISTIC BVT job `99182619116` on exact head `23c7a20c07`.
- PESSIMISTIC BVT completed 72,946 statements with 72,471 successful, exactly two failed, 473 ignored, and zero abnormal. `snapshot/sys_restore_system_table_to_sys_account.sql` completed 313 statements with 311 successful; at SQL rows 167 and 183, both `mo_stored_procedure` comparisons reported `row:0,column:1`, expected `test_if_hit_second_elseif`, and received `test_if_hit_else`. Expected ignored `proc_id` values were `1920000/1920001`; actual ignored values were `9/10`. The final error list contains no other SQL.
- All three changed clone cases passed in attempt 1: `clone_auto_increment_state.sql` 65/65, `table_clone.sql` 74/74, and `temporary_table_clone.sql` 163/163. This PR now adds only a case-level mitigation for all five `mo_stored_procedure` selectors in the same snapshot test; it does not modify mo-tester, expected `proc_id` values, or ignored columns. Fresh CI on `c3332623e5` is pending.
- Attempt-1 aggregate Coverage job `99186546271` was derivative: its direct log records `prerequisites_ready: false` for generation `33283224004-1` and exits before coverage processing.
- Workflow `33283224004` was rerun for failed jobs exactly once; its old-head results are superseded by fresh CI on `c3332623e5`. The rerun policy remains exhausted for that prior workflow.
- #27847 is resolved as a blocker for this PR. Current main includes #27848 test synchronization, and the directly affected quota test passed on the preceding exact head.
- #27833, #27127, #27771, #26519, and #27145 remain resolved as blockers for this PR.

### Residual risks

A fresh clone intentionally owns an independent allocator. If the highest generated source rows were deleted, the clone starts after the highest row it actually copied rather than inheriting an unused cached range from the source CN. Explicit schema lower bounds remain preserved. There are no catalog, wire-format, or API changes in this PR, and the fix does not read or mutate source CN allocator caches.

Approved by: @XuPeng-SH
mergify Bot pushed a commit that referenced this pull request Aug 30, 2026
### Root cause

The failing PROXY BVT exposed inconsistent lock order around data-branch owner catalogs. Restore could hold snapshot/catalog locks and later replace `mo_feature_registry`, while snapshot/PITR publication, lineage GC, account deletion, data-branch mutation, and CCPR cleanup entered through different orders. Restore could therefore be selected as a deadlock victim; the later account mismatch and reconnect failures were consequences of that aborted restore transaction.

Review also exposed liveness boundaries: background GC could hold the global owner boundary through unbounded work and repeat full discovery up to 16 times; local contention could mask parent cancellation; a DATA BRANCH statement inside explicit `BEGIN` could retain the singleton boundary until a user-controlled later commit; CCPR snapshot cleanup bypassed the boundary entirely; and commit-time validation initially covered only ordinary COMMIT, allowing repeated BEGIN or SET autocommit=1 to commit the marked transaction without crossing the boundary.

### Changes

- Use the bootstrap-created `SNAPSHOT` row in `mo_feature_registry` as the single owner-lifecycle boundary; remove the independent `mo_tables` gate.
- Cross the boundary before snapshot/PITR create, drop, and retention changes; internal Create/Drop PITR; COPY ALTER ownership decisions; whole-account/cluster snapshot or PITR restore; standalone DROP ACCOUNT; ordinary DROP DATABASE/TABLE; every data-branch create/delete transaction; and CCPR snapshot deletion.
- Keep restore-internal DROP ACCOUNT reentrant because whole-account restore already owns the boundary in its outer transaction. Database/table restore remains outside this gate because it does not replace account-level owner catalogs.
- Centralize data-branch create/delete admission for all four mutation paths. Autocommit mutations acquire the boundary at transaction admission. Explicit user transactions preserve the existing transactional DATA BRANCH contract without retaining the global row between statements: a successful mutation marks the transaction, and the single low-level terminal commit path performs a system-account fast-fail validation write on the same transaction immediately before physical commit. This covers ordinary COMMIT, replacement BEGIN/START TRANSACTION, and autocommit off-to-on. A competing lifecycle writer aborts and fully rolls back the user transaction using the transaction cleanup context, so cancellation cannot leave its earlier catalog locks alive.
- Preserve feature-quota freshness ordering: ordinary RC mutations establish the TN catalog frontier before writing the lifecycle row; fixed-SI checks keep their independent pessimistic-RC quota transaction and do not advance the outer snapshot.
- Run lineage GC as one explicit-SI work unit per scheduled invocation: one complete discovery, one fast-fail lifecycle validation, and at most 128 paired snapshot/metadata deletes. This removes the previous 16-fold full-catalog rescan amplification while retaining durable progress across runs. A one-minute task-work budget bounds worker occupancy; local expiry and lock/SI contention roll back and defer. Parent cancellation/deadline takes precedence, while remote-owner timeout and substantive failures remain visible.
- Make CCPR snapshot cleanup execute `lifecycle gate -> escaped snapshot delete -> commit` in one transaction. Gate/delete failure rolls back; commit failure is returned without a blind post-commit rollback, preserving unknown-commit handling.
- Allow compile internal SQL execution with a nil plan in direct Scope callers; production plan behavior, including DROP DATABASE foreign-key handling, is unchanged.

### Issue-to-test proof

- The existing BVT `snapshot/cluster/restore_dropped_account_with_cluster.sql` is the reported reproduction: it restores dropped/replaced accounts, verifies the account set, authenticates restored accounts, and validates table data. It passed twice through a real two-CN PROXY (`204/204` each); subsequent required PROXY CI also passed.
- `TestLineageOwnerLifecycleLockSerializesEmptyProbe` proves competing owner decisions cannot bypass the stable row.
- `TestLockRestoreLineageOwnerLifecycleCoversWholeCatalogRestore`, `Test_doDropAccount_InTransaction`, and `TestOwnerCatalogDropEntryPointsStopAtLifecycleAdmissionFailure` cover restore levels, standalone/reentrant account deletion, ordinary DROP entry points, and gate-failure rollback/order.
- `TestGetDataBranchMutationExecutorAdmitsBeforeMutation`, `...RollsBackOnAdmissionFailure`, and `TestValidateDataBranchLineageOwnerLifecycleAtCommitFastFailsStableWrite` prove common admission order, cleanup, same-transaction validation, system-account execution, disabled statement retry, and fast-fail policy.
- `TestLineageOwnerLifecycleValidationCoversEveryTerminalCommitPath` proves ordinary COMMIT, replacement BEGIN, and autocommit off-to-on all validate before physical commit and fully roll back on failure.\n- `TestIssue26113CloneCreatedTableInSameTransaction` preserves DATA BRANCH's existing explicit-transaction atomicity and is the exact coverage-mode regression that caught the rejected-statement design.
- `TestIssue26087ConcurrentDataBranchQuota` uses two CNs to prove an open tenant transaction does not own the global lifecycle row, a completed system snapshot forces both tenant COMMIT and replacement BEGIN validation to fail and fully release its catalog locks, concurrent autocommit table/database branch mutations preserve exact quota outcomes, fixed SI is not advanced, and implicit transaction mode keeps its independent mutation transaction. The upstream #27848 logtail-frontier synchronization remains composed in the same test.
- `BenchmarkComputeAlterLineageCompactionPlan2049` records the remaining single-discovery planner cost and allocation envelope under `-benchmem`.
- `TestCompactExpiredAlterDataBranchLineageWithExecutor` proves discovery precedes lifecycle admission and only the bounded delete pair follows it.
- `TestDataBranchLineageGCExecutorMakesDurableProgressAcrossRuns` proves one independent committed batch per run and eventual cleanup across runs.
- `TestDataBranchLineageGCExecutorScansOnceAndBoundsMutationAtScale` uses 2,049 eligible generations to prove one discovery transaction and a 128-row commit cap instead of 16 complete rescans.
- `TestDataBranchLineageGCExecutorDefersOnLocalTimeBudget`, `...DefersAfterContentionRollback`, `...ParentContextPrecedesContention`, and `...DoesNotSuppressOtherErrors` close timeout, contention, parent-control, rollback, and substantive-error paths.
- `TestDeleteSnapshotWithLifecycleGateIsAtomicAndOrdered` proves CCPR gate/delete/commit order, SQL quoting, rollback on both pre-commit failures, and commit-error propagation.

### Validation

Latest review update, exact head `d6925af23a`:

- `TestLineageOwnerLifecycleValidationCoversEveryTerminalCommitPath`: passed\n- focused lifecycle terminal-path race stress at `-count=100`: passed\n- coverage-mode exact two-CN `TestIssue26087ConcurrentDataBranchQuota`, including replacement BEGIN: passed\n- complete `pkg/frontend`: passed\n- complete `pkg/frontend -race`: passed
- CI-version `golangci-lint 2.6.2 --enable-only prealloc ./pkg/frontend ./pkg/tests/issues`: 0 issues
- `git diff --check`
- post-rebase coverage-mode `TestIssue26087ConcurrentDataBranchQuota` and `TestIssue26113CloneCreatedTableInSameTransaction`: passed together
- post-rebase focused #27849 embed/logservice HAKeeper timeout tests: passed
- post-rebase focused #27154 fresh-clone and ALTER COPY auto-increment allocator tests: passed
- post-rebase focused #27814 LOAD unique-index promotion plus lineage-GC lifecycle tests: passed
- post-rebase complete `pkg/sql/compile`: passed

Earlier series evidence retained:

- full `pkg/frontend`, `pkg/sql/compile`, `pkg/publication`, `pkg/util/executor`, and `pkg/frontend/...` suites; CGo-configured vet
- focused GC, restore, quota, CCPR, and lifecycle race tests
- exact PROXY reproduction twice on the same instance (`204/204` both runs)
- coverage-mode public regressions for snapshot restore and two-CN quota admission
- 2,049-row planner benchmark, three one-second samples: 819-898 µs/op, 463,384 B/op, 8,135 allocs/op
- CI-version SCA correction and focused validation

Freshness:

- current `origin/main` / PR base: `7a87bd69891d498ca72c7eb3a92458da2992f6a1` (#27814)
- exact head: `d6925af23ab02f640ebb815d6a20b2441fb7f052`
- the prior twelve-patch series remains unchanged by the last rebase; the terminal-commit closure is the thirteenth patch
- #27814 directly overlaps `pkg/sql/compile/compile.go` and adds LOAD unique-index lock promotion before source initialization plus retry-owned proof cleanup. The composed diff keeps that state machine unchanged; this PR's nil-plan internal-SQL guard remains isolated in `runSqlWithResultAndOptions` and still preserves DROP DATABASE foreign-key options for non-nil plans. Focused tests for both lock/lifecycle protocols, the complete compile package, and this PR's two exact embedded-cluster regressions passed after rebase.

### Residual risks

The shared write boundary serializes rare owner-lifecycle mutations globally. Autocommit owners hold it only for their mutation transaction; an explicit DATA BRANCH transaction holds no global row while idle and must win fast-fail validation immediately before COMMIT or roll back. Existing ordinary DDL and administrative statements remain prohibited in explicit transactions. GC still performs one complete read-only catalog discovery, but never holds the foreground boundary during that scan; each invocation has a one-minute work budget and can commit no more than 128 paired rows. Remaining eligible lineage advances on later scheduled runs.

Approved by: @XuPeng-SH, @fengttt
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
### Root cause

The fixture opened conn1 next SI transaction immediately after conn2 received a successful cleanup-delete response. That response confirms the TN commit, but it does not guarantee that the same CN has applied the delete logtail. The next SI snapshot could therefore use an older CN frontier and still see `mode_probe.a = 2`.

### Changes

- Assert that the cleanup delete affected exactly one row.
- Commit a later write marker in the test account and wait for its commit frontier to apply on the same CN before conn1 opens the next SI transaction.
- Assert that the marker transaction returned a non-empty commit timestamp, so the wait has a real write frontier.

The change is test-only; it adds no production behavior or fallback path.

### Issue-to-test proof

`TestIssue26087ConcurrentDataBranchQuota` now proves the cleanup row was removed and that the next implicit SI transaction observes an applied frontier before checking both the empty probe table and DATA BRANCH transaction-mode behavior.

BVT is not appropriate: SQL BVT cannot observe the in-process CN logtail frontier that caused this intermittent fixture failure. The existing two-CN Go integration test is the direct test layer.

### Tests

- `.agents/skills/mo-dev/scripts/mo-cgo-test -tags matrixone_test -count=20 -timeout=30m -run "^TestIssue26087ConcurrentDataBranchQuota$" ./pkg/tests/issues` (pass, 122.547s)
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -tags matrixone_test -vet=off -count=1 -timeout=10m -run "^TestIssue26087ConcurrentDataBranchQuota$" ./pkg/tests/issues` (pass, 52.579s)
- `.agents/skills/mo-dev/scripts/mo-cgo-test -tags matrixone_test -count=1 -timeout=30m ./pkg/tests/issues` (pass, 92.918s)

### Risks

The marker table and row exist only in the isolated test account. The added synchronization waits at most 10 seconds through the shared test helper and fails explicitly if the required logtail frontier is not applied.

Approved by: @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
### Root cause

Fresh table clones copied the source row from `mo_catalog.mo_increment_columns` into the destination allocator. That row offset is the upper bound of a reserved allocation batch (10,000 in the reproducer), not the next source-session value (4). Because a fresh clone has a new table ID and an independent allocator, transferring that reservation made its first generated ID 10,001.

The persisted table definition separately carries explicit schema lower bounds such as `ALTER TABLE ... AUTO_INCREMENT = 100`. Those are user-visible state and must still be preserved.

### Changes

- For a fresh clone, reconstruct visible auto-increment state from the copied row maximum and the larger source/destination schema lower bound. Do not copy the source allocator reserved-batch upper bound.
- Continue copying raw allocator state for ALTER COPY paths that retain the column-ID space, where existing CN caches make that state part of the ownership handoff.
- Continue copying allocator state for hidden internal auto-increment columns; hidden index-table allocator handling is unchanged.
- Add unit coverage for the fresh-clone and ALTER COPY ownership boundaries, including a source schema lower bound larger than the destination lower bound.
- Add BVT coverage for table clone, database clone, both Data Branch forms, empty sources, deleted maximum IDs, explicit `AUTO_INCREMENT`, explicit transactions, and historical snapshots.
- Stabilize the five existing snapshot stored-procedure checks with `ORDER BY name` and `@sortkey:1`, while retaining `@ignore:0,9,10`; this changes neither the expected `proc_id` entries nor any non-ignored field assertion.
- Update table-clone and temporary-table-clone BVT expectations to assert contiguous IDs from the highest copied row instead of discarded source reservation batches.

### Issue-to-test proof

- The exact issue reproduction reports source next `4`, clone next `5`, and first cloned-table insert `4` for table, database, and both Data Branch clone forms.
- Empty sources insert `1`; a source whose largest row was deleted seeds the independent clone from the copied maximum; explicit `AUTO_INCREMENT = 100` inserts `100`; snapshot clone asserts snapshot-visible rows plus exact `4 / 5` inserted/next values.
- A permanent source cloned into a temporary table preserves copied IDs `10` and `11`, then assigns `12` to the first destination insert.
- Unit tests prove that fresh visible columns discard the persisted reservation while preserving the larger source/destination schema floor; ALTER COPY and hidden internal columns retain allocator state required by their ownership model.
- The existing chained-clone BVT proves subsequent clone and delete/insert sequences continue at `40001` through `40006`, without introducing a new 10,000-value gap at each clone.
- The snapshot/restore procedure checks still validate every catalog field except the pre-existing ignored ID and timestamp columns. Their deterministic unique `name` ordering prevents ignored allocator IDs from pairing one procedure with another.

### Verification

Latest semantic rebase: patch-equivalent head `1c9ff2e42bc751bd0028bcfe0cd51b8704071bcb` was rebased conflict-free from `main` at `a15139da62b938b0918c19675c619b259cd86460` onto `main` at `07fe9a69c6a3d6ed5e2b4299fb143d10bef442c0`, producing exact head `23c7a20c072375324fee984c087de370ef5bd323`.

- `git range-diff a15139d..1c9ff2e 07fe9a6..23c7a20`: all four clone patches are equivalent.
- Stable aggregate patch ID before and after the rebase: `ff530dfc6cb58fd343bc0663b95c917a95aa40fc`.
- The final diff is the intended six clone files plus two targeted snapshot BVT files; `git diff --check origin/main...HEAD` passed and the worktree is clean.
- On exact head `c3332623e5be8961a2c54bed286c888b75f82bee`, an isolated local MatrixOne service and mo-tester upstream/main `334d3e124bbfbdcd6b5cc63439278d172c72b706` passed `sys_restore_system_table_to_sys_account` twice with CI flags `-g -n -o`: 313/313 statements each time. Normal metadata mode also passed 313/313.
- A direct matcher negative-control proves the BVT assertion remains strict: ignored IDs `9/10` versus expected `1920000/1920001` fail under full-row sorting, while `ORDER BY name` plus `@sortkey:1` pairs rows correctly; mutations to each of the 14 non-ignored columns are rejected. `@sortkey:1` alone remains order-dependent, so it is deliberately paired with SQL ordering.
- Exact-head MatrixOne CGo validation selected and passed all eight focused clone allocator tests.
- Incoming main commit `07fe9a69c6 fix(embed): align HAKeeper transport timeout under race (matrixorigin#27849)` changes only embed/logservice configuration and its tests, with no PR-file overlap. All six directly affected tests passed: three embed timeout/config tests, two logservice client-config tests, and the authenticated two-CN fixture test.
- Because the incoming logservice change is a transitive dependency of the clone owners, the complete `pkg/sql/compile`, `pkg/frontend`, and `pkg/sql/colexec/table_clone` packages were rerun through the MatrixOne CGo wrapper and passed on exact head `23c7a20c07`.
- Workflow `33283224004` attempt 1 on exact head `23c7a20c07` passed shared build, normal Ubuntu UT, SCA, Coverage UT, and PROXY BVT. All three changed clone cases passed; PESSIMISTIC BVT reproduced only unrelated matrixorigin#27164, and aggregate Coverage was derivative.
- Attempt-2 PESSIMISTIC BVT job `99187224896` is in progress after the single permitted failed-job rerun.

### CI investigation

- matrixorigin#27164 remains the underlying mo-tester defect. Workflow `33283224004` attempt 1 reproduced its snapshot result-pairing mismatch in PESSIMISTIC BVT job `99182619116` on exact head `23c7a20c07`.
- PESSIMISTIC BVT completed 72,946 statements with 72,471 successful, exactly two failed, 473 ignored, and zero abnormal. `snapshot/sys_restore_system_table_to_sys_account.sql` completed 313 statements with 311 successful; at SQL rows 167 and 183, both `mo_stored_procedure` comparisons reported `row:0,column:1`, expected `test_if_hit_second_elseif`, and received `test_if_hit_else`. Expected ignored `proc_id` values were `1920000/1920001`; actual ignored values were `9/10`. The final error list contains no other SQL.
- All three changed clone cases passed in attempt 1: `clone_auto_increment_state.sql` 65/65, `table_clone.sql` 74/74, and `temporary_table_clone.sql` 163/163. This PR now adds only a case-level mitigation for all five `mo_stored_procedure` selectors in the same snapshot test; it does not modify mo-tester, expected `proc_id` values, or ignored columns. Fresh CI on `c3332623e5` is pending.
- Attempt-1 aggregate Coverage job `99186546271` was derivative: its direct log records `prerequisites_ready: false` for generation `33283224004-1` and exits before coverage processing.
- Workflow `33283224004` was rerun for failed jobs exactly once; its old-head results are superseded by fresh CI on `c3332623e5`. The rerun policy remains exhausted for that prior workflow.
- matrixorigin#27847 is resolved as a blocker for this PR. Current main includes matrixorigin#27848 test synchronization, and the directly affected quota test passed on the preceding exact head.
- matrixorigin#27833, matrixorigin#27127, matrixorigin#27771, matrixorigin#26519, and matrixorigin#27145 remain resolved as blockers for this PR.

### Residual risks

A fresh clone intentionally owns an independent allocator. If the highest generated source rows were deleted, the clone starts after the highest row it actually copied rather than inheriting an unused cached range from the source CN. Explicit schema lower bounds remain preserved. There are no catalog, wire-format, or API changes in this PR, and the fix does not read or mutate source CN allocator caches.

Approved by: @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…n#27826)

### Root cause

The failing PROXY BVT exposed inconsistent lock order around data-branch owner catalogs. Restore could hold snapshot/catalog locks and later replace `mo_feature_registry`, while snapshot/PITR publication, lineage GC, account deletion, data-branch mutation, and CCPR cleanup entered through different orders. Restore could therefore be selected as a deadlock victim; the later account mismatch and reconnect failures were consequences of that aborted restore transaction.

Review also exposed liveness boundaries: background GC could hold the global owner boundary through unbounded work and repeat full discovery up to 16 times; local contention could mask parent cancellation; a DATA BRANCH statement inside explicit `BEGIN` could retain the singleton boundary until a user-controlled later commit; CCPR snapshot cleanup bypassed the boundary entirely; and commit-time validation initially covered only ordinary COMMIT, allowing repeated BEGIN or SET autocommit=1 to commit the marked transaction without crossing the boundary.

### Changes

- Use the bootstrap-created `SNAPSHOT` row in `mo_feature_registry` as the single owner-lifecycle boundary; remove the independent `mo_tables` gate.
- Cross the boundary before snapshot/PITR create, drop, and retention changes; internal Create/Drop PITR; COPY ALTER ownership decisions; whole-account/cluster snapshot or PITR restore; standalone DROP ACCOUNT; ordinary DROP DATABASE/TABLE; every data-branch create/delete transaction; and CCPR snapshot deletion.
- Keep restore-internal DROP ACCOUNT reentrant because whole-account restore already owns the boundary in its outer transaction. Database/table restore remains outside this gate because it does not replace account-level owner catalogs.
- Centralize data-branch create/delete admission for all four mutation paths. Autocommit mutations acquire the boundary at transaction admission. Explicit user transactions preserve the existing transactional DATA BRANCH contract without retaining the global row between statements: a successful mutation marks the transaction, and the single low-level terminal commit path performs a system-account fast-fail validation write on the same transaction immediately before physical commit. This covers ordinary COMMIT, replacement BEGIN/START TRANSACTION, and autocommit off-to-on. A competing lifecycle writer aborts and fully rolls back the user transaction using the transaction cleanup context, so cancellation cannot leave its earlier catalog locks alive.
- Preserve feature-quota freshness ordering: ordinary RC mutations establish the TN catalog frontier before writing the lifecycle row; fixed-SI checks keep their independent pessimistic-RC quota transaction and do not advance the outer snapshot.
- Run lineage GC as one explicit-SI work unit per scheduled invocation: one complete discovery, one fast-fail lifecycle validation, and at most 128 paired snapshot/metadata deletes. This removes the previous 16-fold full-catalog rescan amplification while retaining durable progress across runs. A one-minute task-work budget bounds worker occupancy; local expiry and lock/SI contention roll back and defer. Parent cancellation/deadline takes precedence, while remote-owner timeout and substantive failures remain visible.
- Make CCPR snapshot cleanup execute `lifecycle gate -> escaped snapshot delete -> commit` in one transaction. Gate/delete failure rolls back; commit failure is returned without a blind post-commit rollback, preserving unknown-commit handling.
- Allow compile internal SQL execution with a nil plan in direct Scope callers; production plan behavior, including DROP DATABASE foreign-key handling, is unchanged.

### Issue-to-test proof

- The existing BVT `snapshot/cluster/restore_dropped_account_with_cluster.sql` is the reported reproduction: it restores dropped/replaced accounts, verifies the account set, authenticates restored accounts, and validates table data. It passed twice through a real two-CN PROXY (`204/204` each); subsequent required PROXY CI also passed.
- `TestLineageOwnerLifecycleLockSerializesEmptyProbe` proves competing owner decisions cannot bypass the stable row.
- `TestLockRestoreLineageOwnerLifecycleCoversWholeCatalogRestore`, `Test_doDropAccount_InTransaction`, and `TestOwnerCatalogDropEntryPointsStopAtLifecycleAdmissionFailure` cover restore levels, standalone/reentrant account deletion, ordinary DROP entry points, and gate-failure rollback/order.
- `TestGetDataBranchMutationExecutorAdmitsBeforeMutation`, `...RollsBackOnAdmissionFailure`, and `TestValidateDataBranchLineageOwnerLifecycleAtCommitFastFailsStableWrite` prove common admission order, cleanup, same-transaction validation, system-account execution, disabled statement retry, and fast-fail policy.
- `TestLineageOwnerLifecycleValidationCoversEveryTerminalCommitPath` proves ordinary COMMIT, replacement BEGIN, and autocommit off-to-on all validate before physical commit and fully roll back on failure.\n- `TestIssue26113CloneCreatedTableInSameTransaction` preserves DATA BRANCH's existing explicit-transaction atomicity and is the exact coverage-mode regression that caught the rejected-statement design.
- `TestIssue26087ConcurrentDataBranchQuota` uses two CNs to prove an open tenant transaction does not own the global lifecycle row, a completed system snapshot forces both tenant COMMIT and replacement BEGIN validation to fail and fully release its catalog locks, concurrent autocommit table/database branch mutations preserve exact quota outcomes, fixed SI is not advanced, and implicit transaction mode keeps its independent mutation transaction. The upstream matrixorigin#27848 logtail-frontier synchronization remains composed in the same test.
- `BenchmarkComputeAlterLineageCompactionPlan2049` records the remaining single-discovery planner cost and allocation envelope under `-benchmem`.
- `TestCompactExpiredAlterDataBranchLineageWithExecutor` proves discovery precedes lifecycle admission and only the bounded delete pair follows it.
- `TestDataBranchLineageGCExecutorMakesDurableProgressAcrossRuns` proves one independent committed batch per run and eventual cleanup across runs.
- `TestDataBranchLineageGCExecutorScansOnceAndBoundsMutationAtScale` uses 2,049 eligible generations to prove one discovery transaction and a 128-row commit cap instead of 16 complete rescans.
- `TestDataBranchLineageGCExecutorDefersOnLocalTimeBudget`, `...DefersAfterContentionRollback`, `...ParentContextPrecedesContention`, and `...DoesNotSuppressOtherErrors` close timeout, contention, parent-control, rollback, and substantive-error paths.
- `TestDeleteSnapshotWithLifecycleGateIsAtomicAndOrdered` proves CCPR gate/delete/commit order, SQL quoting, rollback on both pre-commit failures, and commit-error propagation.

### Validation

Latest review update, exact head `d6925af23a`:

- `TestLineageOwnerLifecycleValidationCoversEveryTerminalCommitPath`: passed\n- focused lifecycle terminal-path race stress at `-count=100`: passed\n- coverage-mode exact two-CN `TestIssue26087ConcurrentDataBranchQuota`, including replacement BEGIN: passed\n- complete `pkg/frontend`: passed\n- complete `pkg/frontend -race`: passed
- CI-version `golangci-lint 2.6.2 --enable-only prealloc ./pkg/frontend ./pkg/tests/issues`: 0 issues
- `git diff --check`
- post-rebase coverage-mode `TestIssue26087ConcurrentDataBranchQuota` and `TestIssue26113CloneCreatedTableInSameTransaction`: passed together
- post-rebase focused matrixorigin#27849 embed/logservice HAKeeper timeout tests: passed
- post-rebase focused matrixorigin#27154 fresh-clone and ALTER COPY auto-increment allocator tests: passed
- post-rebase focused matrixorigin#27814 LOAD unique-index promotion plus lineage-GC lifecycle tests: passed
- post-rebase complete `pkg/sql/compile`: passed

Earlier series evidence retained:

- full `pkg/frontend`, `pkg/sql/compile`, `pkg/publication`, `pkg/util/executor`, and `pkg/frontend/...` suites; CGo-configured vet
- focused GC, restore, quota, CCPR, and lifecycle race tests
- exact PROXY reproduction twice on the same instance (`204/204` both runs)
- coverage-mode public regressions for snapshot restore and two-CN quota admission
- 2,049-row planner benchmark, three one-second samples: 819-898 µs/op, 463,384 B/op, 8,135 allocs/op
- CI-version SCA correction and focused validation

Freshness:

- current `origin/main` / PR base: `7a87bd69891d498ca72c7eb3a92458da2992f6a1` (matrixorigin#27814)
- exact head: `d6925af23ab02f640ebb815d6a20b2441fb7f052`
- the prior twelve-patch series remains unchanged by the last rebase; the terminal-commit closure is the thirteenth patch
- matrixorigin#27814 directly overlaps `pkg/sql/compile/compile.go` and adds LOAD unique-index lock promotion before source initialization plus retry-owned proof cleanup. The composed diff keeps that state machine unchanged; this PR's nil-plan internal-SQL guard remains isolated in `runSqlWithResultAndOptions` and still preserves DROP DATABASE foreign-key options for non-nil plans. Focused tests for both lock/lifecycle protocols, the complete compile package, and this PR's two exact embedded-cluster regressions passed after rebase.

### Residual risks

The shared write boundary serializes rare owner-lifecycle mutations globally. Autocommit owners hold it only for their mutation transaction; an explicit DATA BRANCH transaction holds no global row while idle and must win fast-fail validation immediately before COMMIT or roll back. Existing ordinary DDL and administrative statements remain prohibited in explicit transactions. GC still performs one complete read-only catalog discovery, but never holds the foreground boundary during that scan; each invocation has a one-minute work budget and can commit no more than 128 paired rows. Remaining eligible lineage advances on later scheduled runs.

Approved by: @XuPeng-SH, @fengttt
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
### Root cause

The fixture opened conn1 next SI transaction immediately after conn2 received a successful cleanup-delete response. That response confirms the TN commit, but it does not guarantee that the same CN has applied the delete logtail. The next SI snapshot could therefore use an older CN frontier and still see `mode_probe.a = 2`.

### Changes

- Assert that the cleanup delete affected exactly one row.
- Commit a later write marker in the test account and wait for its commit frontier to apply on the same CN before conn1 opens the next SI transaction.
- Assert that the marker transaction returned a non-empty commit timestamp, so the wait has a real write frontier.

The change is test-only; it adds no production behavior or fallback path.

### Issue-to-test proof

`TestIssue26087ConcurrentDataBranchQuota` now proves the cleanup row was removed and that the next implicit SI transaction observes an applied frontier before checking both the empty probe table and DATA BRANCH transaction-mode behavior.

BVT is not appropriate: SQL BVT cannot observe the in-process CN logtail frontier that caused this intermittent fixture failure. The existing two-CN Go integration test is the direct test layer.

### Tests

- `.agents/skills/mo-dev/scripts/mo-cgo-test -tags matrixone_test -count=20 -timeout=30m -run "^TestIssue26087ConcurrentDataBranchQuota$" ./pkg/tests/issues` (pass, 122.547s)
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -tags matrixone_test -vet=off -count=1 -timeout=10m -run "^TestIssue26087ConcurrentDataBranchQuota$" ./pkg/tests/issues` (pass, 52.579s)
- `.agents/skills/mo-dev/scripts/mo-cgo-test -tags matrixone_test -count=1 -timeout=30m ./pkg/tests/issues` (pass, 92.918s)

### Risks

The marker table and row exist only in the isolated test account. The added synchronization waits at most 10 seconds through the shared test helper and fails explicitly if the required logtail frontier is not applied.

Approved by: @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
### Root cause

Fresh table clones copied the source row from `mo_catalog.mo_increment_columns` into the destination allocator. That row offset is the upper bound of a reserved allocation batch (10,000 in the reproducer), not the next source-session value (4). Because a fresh clone has a new table ID and an independent allocator, transferring that reservation made its first generated ID 10,001.

The persisted table definition separately carries explicit schema lower bounds such as `ALTER TABLE ... AUTO_INCREMENT = 100`. Those are user-visible state and must still be preserved.

### Changes

- For a fresh clone, reconstruct visible auto-increment state from the copied row maximum and the larger source/destination schema lower bound. Do not copy the source allocator reserved-batch upper bound.
- Continue copying raw allocator state for ALTER COPY paths that retain the column-ID space, where existing CN caches make that state part of the ownership handoff.
- Continue copying allocator state for hidden internal auto-increment columns; hidden index-table allocator handling is unchanged.
- Add unit coverage for the fresh-clone and ALTER COPY ownership boundaries, including a source schema lower bound larger than the destination lower bound.
- Add BVT coverage for table clone, database clone, both Data Branch forms, empty sources, deleted maximum IDs, explicit `AUTO_INCREMENT`, explicit transactions, and historical snapshots.
- Stabilize the five existing snapshot stored-procedure checks with `ORDER BY name` and `@sortkey:1`, while retaining `@ignore:0,9,10`; this changes neither the expected `proc_id` entries nor any non-ignored field assertion.
- Update table-clone and temporary-table-clone BVT expectations to assert contiguous IDs from the highest copied row instead of discarded source reservation batches.

### Issue-to-test proof

- The exact issue reproduction reports source next `4`, clone next `5`, and first cloned-table insert `4` for table, database, and both Data Branch clone forms.
- Empty sources insert `1`; a source whose largest row was deleted seeds the independent clone from the copied maximum; explicit `AUTO_INCREMENT = 100` inserts `100`; snapshot clone asserts snapshot-visible rows plus exact `4 / 5` inserted/next values.
- A permanent source cloned into a temporary table preserves copied IDs `10` and `11`, then assigns `12` to the first destination insert.
- Unit tests prove that fresh visible columns discard the persisted reservation while preserving the larger source/destination schema floor; ALTER COPY and hidden internal columns retain allocator state required by their ownership model.
- The existing chained-clone BVT proves subsequent clone and delete/insert sequences continue at `40001` through `40006`, without introducing a new 10,000-value gap at each clone.
- The snapshot/restore procedure checks still validate every catalog field except the pre-existing ignored ID and timestamp columns. Their deterministic unique `name` ordering prevents ignored allocator IDs from pairing one procedure with another.

### Verification

Latest semantic rebase: patch-equivalent head `1c9ff2e42bc751bd0028bcfe0cd51b8704071bcb` was rebased conflict-free from `main` at `a15139da62b938b0918c19675c619b259cd86460` onto `main` at `07fe9a69c6a3d6ed5e2b4299fb143d10bef442c0`, producing exact head `23c7a20c072375324fee984c087de370ef5bd323`.

- `git range-diff a15139d..1c9ff2e 07fe9a6..23c7a20`: all four clone patches are equivalent.
- Stable aggregate patch ID before and after the rebase: `ff530dfc6cb58fd343bc0663b95c917a95aa40fc`.
- The final diff is the intended six clone files plus two targeted snapshot BVT files; `git diff --check origin/main...HEAD` passed and the worktree is clean.
- On exact head `c3332623e5be8961a2c54bed286c888b75f82bee`, an isolated local MatrixOne service and mo-tester upstream/main `334d3e124bbfbdcd6b5cc63439278d172c72b706` passed `sys_restore_system_table_to_sys_account` twice with CI flags `-g -n -o`: 313/313 statements each time. Normal metadata mode also passed 313/313.
- A direct matcher negative-control proves the BVT assertion remains strict: ignored IDs `9/10` versus expected `1920000/1920001` fail under full-row sorting, while `ORDER BY name` plus `@sortkey:1` pairs rows correctly; mutations to each of the 14 non-ignored columns are rejected. `@sortkey:1` alone remains order-dependent, so it is deliberately paired with SQL ordering.
- Exact-head MatrixOne CGo validation selected and passed all eight focused clone allocator tests.
- Incoming main commit `07fe9a69c6 fix(embed): align HAKeeper transport timeout under race (matrixorigin#27849)` changes only embed/logservice configuration and its tests, with no PR-file overlap. All six directly affected tests passed: three embed timeout/config tests, two logservice client-config tests, and the authenticated two-CN fixture test.
- Because the incoming logservice change is a transitive dependency of the clone owners, the complete `pkg/sql/compile`, `pkg/frontend`, and `pkg/sql/colexec/table_clone` packages were rerun through the MatrixOne CGo wrapper and passed on exact head `23c7a20c07`.
- Workflow `33283224004` attempt 1 on exact head `23c7a20c07` passed shared build, normal Ubuntu UT, SCA, Coverage UT, and PROXY BVT. All three changed clone cases passed; PESSIMISTIC BVT reproduced only unrelated matrixorigin#27164, and aggregate Coverage was derivative.
- Attempt-2 PESSIMISTIC BVT job `99187224896` is in progress after the single permitted failed-job rerun.

### CI investigation

- matrixorigin#27164 remains the underlying mo-tester defect. Workflow `33283224004` attempt 1 reproduced its snapshot result-pairing mismatch in PESSIMISTIC BVT job `99182619116` on exact head `23c7a20c07`.
- PESSIMISTIC BVT completed 72,946 statements with 72,471 successful, exactly two failed, 473 ignored, and zero abnormal. `snapshot/sys_restore_system_table_to_sys_account.sql` completed 313 statements with 311 successful; at SQL rows 167 and 183, both `mo_stored_procedure` comparisons reported `row:0,column:1`, expected `test_if_hit_second_elseif`, and received `test_if_hit_else`. Expected ignored `proc_id` values were `1920000/1920001`; actual ignored values were `9/10`. The final error list contains no other SQL.
- All three changed clone cases passed in attempt 1: `clone_auto_increment_state.sql` 65/65, `table_clone.sql` 74/74, and `temporary_table_clone.sql` 163/163. This PR now adds only a case-level mitigation for all five `mo_stored_procedure` selectors in the same snapshot test; it does not modify mo-tester, expected `proc_id` values, or ignored columns. Fresh CI on `c3332623e5` is pending.
- Attempt-1 aggregate Coverage job `99186546271` was derivative: its direct log records `prerequisites_ready: false` for generation `33283224004-1` and exits before coverage processing.
- Workflow `33283224004` was rerun for failed jobs exactly once; its old-head results are superseded by fresh CI on `c3332623e5`. The rerun policy remains exhausted for that prior workflow.
- matrixorigin#27847 is resolved as a blocker for this PR. Current main includes matrixorigin#27848 test synchronization, and the directly affected quota test passed on the preceding exact head.
- matrixorigin#27833, matrixorigin#27127, matrixorigin#27771, matrixorigin#26519, and matrixorigin#27145 remain resolved as blockers for this PR.

### Residual risks

A fresh clone intentionally owns an independent allocator. If the highest generated source rows were deleted, the clone starts after the highest row it actually copied rather than inheriting an unused cached range from the source CN. Explicit schema lower bounds remain preserved. There are no catalog, wire-format, or API changes in this PR, and the fix does not read or mutate source CN allocator caches.

Approved by: @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…n#27826)

### Root cause

The failing PROXY BVT exposed inconsistent lock order around data-branch owner catalogs. Restore could hold snapshot/catalog locks and later replace `mo_feature_registry`, while snapshot/PITR publication, lineage GC, account deletion, data-branch mutation, and CCPR cleanup entered through different orders. Restore could therefore be selected as a deadlock victim; the later account mismatch and reconnect failures were consequences of that aborted restore transaction.

Review also exposed liveness boundaries: background GC could hold the global owner boundary through unbounded work and repeat full discovery up to 16 times; local contention could mask parent cancellation; a DATA BRANCH statement inside explicit `BEGIN` could retain the singleton boundary until a user-controlled later commit; CCPR snapshot cleanup bypassed the boundary entirely; and commit-time validation initially covered only ordinary COMMIT, allowing repeated BEGIN or SET autocommit=1 to commit the marked transaction without crossing the boundary.

### Changes

- Use the bootstrap-created `SNAPSHOT` row in `mo_feature_registry` as the single owner-lifecycle boundary; remove the independent `mo_tables` gate.
- Cross the boundary before snapshot/PITR create, drop, and retention changes; internal Create/Drop PITR; COPY ALTER ownership decisions; whole-account/cluster snapshot or PITR restore; standalone DROP ACCOUNT; ordinary DROP DATABASE/TABLE; every data-branch create/delete transaction; and CCPR snapshot deletion.
- Keep restore-internal DROP ACCOUNT reentrant because whole-account restore already owns the boundary in its outer transaction. Database/table restore remains outside this gate because it does not replace account-level owner catalogs.
- Centralize data-branch create/delete admission for all four mutation paths. Autocommit mutations acquire the boundary at transaction admission. Explicit user transactions preserve the existing transactional DATA BRANCH contract without retaining the global row between statements: a successful mutation marks the transaction, and the single low-level terminal commit path performs a system-account fast-fail validation write on the same transaction immediately before physical commit. This covers ordinary COMMIT, replacement BEGIN/START TRANSACTION, and autocommit off-to-on. A competing lifecycle writer aborts and fully rolls back the user transaction using the transaction cleanup context, so cancellation cannot leave its earlier catalog locks alive.
- Preserve feature-quota freshness ordering: ordinary RC mutations establish the TN catalog frontier before writing the lifecycle row; fixed-SI checks keep their independent pessimistic-RC quota transaction and do not advance the outer snapshot.
- Run lineage GC as one explicit-SI work unit per scheduled invocation: one complete discovery, one fast-fail lifecycle validation, and at most 128 paired snapshot/metadata deletes. This removes the previous 16-fold full-catalog rescan amplification while retaining durable progress across runs. A one-minute task-work budget bounds worker occupancy; local expiry and lock/SI contention roll back and defer. Parent cancellation/deadline takes precedence, while remote-owner timeout and substantive failures remain visible.
- Make CCPR snapshot cleanup execute `lifecycle gate -> escaped snapshot delete -> commit` in one transaction. Gate/delete failure rolls back; commit failure is returned without a blind post-commit rollback, preserving unknown-commit handling.
- Allow compile internal SQL execution with a nil plan in direct Scope callers; production plan behavior, including DROP DATABASE foreign-key handling, is unchanged.

### Issue-to-test proof

- The existing BVT `snapshot/cluster/restore_dropped_account_with_cluster.sql` is the reported reproduction: it restores dropped/replaced accounts, verifies the account set, authenticates restored accounts, and validates table data. It passed twice through a real two-CN PROXY (`204/204` each); subsequent required PROXY CI also passed.
- `TestLineageOwnerLifecycleLockSerializesEmptyProbe` proves competing owner decisions cannot bypass the stable row.
- `TestLockRestoreLineageOwnerLifecycleCoversWholeCatalogRestore`, `Test_doDropAccount_InTransaction`, and `TestOwnerCatalogDropEntryPointsStopAtLifecycleAdmissionFailure` cover restore levels, standalone/reentrant account deletion, ordinary DROP entry points, and gate-failure rollback/order.
- `TestGetDataBranchMutationExecutorAdmitsBeforeMutation`, `...RollsBackOnAdmissionFailure`, and `TestValidateDataBranchLineageOwnerLifecycleAtCommitFastFailsStableWrite` prove common admission order, cleanup, same-transaction validation, system-account execution, disabled statement retry, and fast-fail policy.
- `TestLineageOwnerLifecycleValidationCoversEveryTerminalCommitPath` proves ordinary COMMIT, replacement BEGIN, and autocommit off-to-on all validate before physical commit and fully roll back on failure.\n- `TestIssue26113CloneCreatedTableInSameTransaction` preserves DATA BRANCH's existing explicit-transaction atomicity and is the exact coverage-mode regression that caught the rejected-statement design.
- `TestIssue26087ConcurrentDataBranchQuota` uses two CNs to prove an open tenant transaction does not own the global lifecycle row, a completed system snapshot forces both tenant COMMIT and replacement BEGIN validation to fail and fully release its catalog locks, concurrent autocommit table/database branch mutations preserve exact quota outcomes, fixed SI is not advanced, and implicit transaction mode keeps its independent mutation transaction. The upstream matrixorigin#27848 logtail-frontier synchronization remains composed in the same test.
- `BenchmarkComputeAlterLineageCompactionPlan2049` records the remaining single-discovery planner cost and allocation envelope under `-benchmem`.
- `TestCompactExpiredAlterDataBranchLineageWithExecutor` proves discovery precedes lifecycle admission and only the bounded delete pair follows it.
- `TestDataBranchLineageGCExecutorMakesDurableProgressAcrossRuns` proves one independent committed batch per run and eventual cleanup across runs.
- `TestDataBranchLineageGCExecutorScansOnceAndBoundsMutationAtScale` uses 2,049 eligible generations to prove one discovery transaction and a 128-row commit cap instead of 16 complete rescans.
- `TestDataBranchLineageGCExecutorDefersOnLocalTimeBudget`, `...DefersAfterContentionRollback`, `...ParentContextPrecedesContention`, and `...DoesNotSuppressOtherErrors` close timeout, contention, parent-control, rollback, and substantive-error paths.
- `TestDeleteSnapshotWithLifecycleGateIsAtomicAndOrdered` proves CCPR gate/delete/commit order, SQL quoting, rollback on both pre-commit failures, and commit-error propagation.

### Validation

Latest review update, exact head `d6925af23a`:

- `TestLineageOwnerLifecycleValidationCoversEveryTerminalCommitPath`: passed\n- focused lifecycle terminal-path race stress at `-count=100`: passed\n- coverage-mode exact two-CN `TestIssue26087ConcurrentDataBranchQuota`, including replacement BEGIN: passed\n- complete `pkg/frontend`: passed\n- complete `pkg/frontend -race`: passed
- CI-version `golangci-lint 2.6.2 --enable-only prealloc ./pkg/frontend ./pkg/tests/issues`: 0 issues
- `git diff --check`
- post-rebase coverage-mode `TestIssue26087ConcurrentDataBranchQuota` and `TestIssue26113CloneCreatedTableInSameTransaction`: passed together
- post-rebase focused matrixorigin#27849 embed/logservice HAKeeper timeout tests: passed
- post-rebase focused matrixorigin#27154 fresh-clone and ALTER COPY auto-increment allocator tests: passed
- post-rebase focused matrixorigin#27814 LOAD unique-index promotion plus lineage-GC lifecycle tests: passed
- post-rebase complete `pkg/sql/compile`: passed

Earlier series evidence retained:

- full `pkg/frontend`, `pkg/sql/compile`, `pkg/publication`, `pkg/util/executor`, and `pkg/frontend/...` suites; CGo-configured vet
- focused GC, restore, quota, CCPR, and lifecycle race tests
- exact PROXY reproduction twice on the same instance (`204/204` both runs)
- coverage-mode public regressions for snapshot restore and two-CN quota admission
- 2,049-row planner benchmark, three one-second samples: 819-898 µs/op, 463,384 B/op, 8,135 allocs/op
- CI-version SCA correction and focused validation

Freshness:

- current `origin/main` / PR base: `7a87bd69891d498ca72c7eb3a92458da2992f6a1` (matrixorigin#27814)
- exact head: `d6925af23ab02f640ebb815d6a20b2441fb7f052`
- the prior twelve-patch series remains unchanged by the last rebase; the terminal-commit closure is the thirteenth patch
- matrixorigin#27814 directly overlaps `pkg/sql/compile/compile.go` and adds LOAD unique-index lock promotion before source initialization plus retry-owned proof cleanup. The composed diff keeps that state machine unchanged; this PR's nil-plan internal-SQL guard remains isolated in `runSqlWithResultAndOptions` and still preserves DROP DATABASE foreign-key options for non-nil plans. Focused tests for both lock/lifecycle protocols, the complete compile package, and this PR's two exact embedded-cluster regressions passed after rebase.

### Residual risks

The shared write boundary serializes rare owner-lifecycle mutations globally. Autocommit owners hold it only for their mutation transaction; an explicit DATA BRANCH transaction holds no global row while idle and must win fast-fail validation immediately before COMMIT or roll back. Existing ordinary DDL and administrative statements remain prohibited in explicit transactions. GC still performs one complete read-only catalog discovery, but never holds the foreground boundary during that scan; each invocation has a one-minute work budget and can commit no more than 128 paired rows. Remaining eligible lineage advances on later scheduled runs.

Approved by: @XuPeng-SH, @fengttt
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
### Root cause

The fixture opened conn1 next SI transaction immediately after conn2 received a successful cleanup-delete response. That response confirms the TN commit, but it does not guarantee that the same CN has applied the delete logtail. The next SI snapshot could therefore use an older CN frontier and still see `mode_probe.a = 2`.

### Changes

- Assert that the cleanup delete affected exactly one row.
- Commit a later write marker in the test account and wait for its commit frontier to apply on the same CN before conn1 opens the next SI transaction.
- Assert that the marker transaction returned a non-empty commit timestamp, so the wait has a real write frontier.

The change is test-only; it adds no production behavior or fallback path.

### Issue-to-test proof

`TestIssue26087ConcurrentDataBranchQuota` now proves the cleanup row was removed and that the next implicit SI transaction observes an applied frontier before checking both the empty probe table and DATA BRANCH transaction-mode behavior.

BVT is not appropriate: SQL BVT cannot observe the in-process CN logtail frontier that caused this intermittent fixture failure. The existing two-CN Go integration test is the direct test layer.

### Tests

- `.agents/skills/mo-dev/scripts/mo-cgo-test -tags matrixone_test -count=20 -timeout=30m -run "^TestIssue26087ConcurrentDataBranchQuota$" ./pkg/tests/issues` (pass, 122.547s)
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -tags matrixone_test -vet=off -count=1 -timeout=10m -run "^TestIssue26087ConcurrentDataBranchQuota$" ./pkg/tests/issues` (pass, 52.579s)
- `.agents/skills/mo-dev/scripts/mo-cgo-test -tags matrixone_test -count=1 -timeout=30m ./pkg/tests/issues` (pass, 92.918s)

### Risks

The marker table and row exist only in the isolated test account. The added synchronization waits at most 10 seconds through the shared test helper and fails explicitly if the required logtail frontier is not applied.

Approved by: @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
### Root cause

Fresh table clones copied the source row from `mo_catalog.mo_increment_columns` into the destination allocator. That row offset is the upper bound of a reserved allocation batch (10,000 in the reproducer), not the next source-session value (4). Because a fresh clone has a new table ID and an independent allocator, transferring that reservation made its first generated ID 10,001.

The persisted table definition separately carries explicit schema lower bounds such as `ALTER TABLE ... AUTO_INCREMENT = 100`. Those are user-visible state and must still be preserved.

### Changes

- For a fresh clone, reconstruct visible auto-increment state from the copied row maximum and the larger source/destination schema lower bound. Do not copy the source allocator reserved-batch upper bound.
- Continue copying raw allocator state for ALTER COPY paths that retain the column-ID space, where existing CN caches make that state part of the ownership handoff.
- Continue copying allocator state for hidden internal auto-increment columns; hidden index-table allocator handling is unchanged.
- Add unit coverage for the fresh-clone and ALTER COPY ownership boundaries, including a source schema lower bound larger than the destination lower bound.
- Add BVT coverage for table clone, database clone, both Data Branch forms, empty sources, deleted maximum IDs, explicit `AUTO_INCREMENT`, explicit transactions, and historical snapshots.
- Stabilize the five existing snapshot stored-procedure checks with `ORDER BY name` and `@sortkey:1`, while retaining `@ignore:0,9,10`; this changes neither the expected `proc_id` entries nor any non-ignored field assertion.
- Update table-clone and temporary-table-clone BVT expectations to assert contiguous IDs from the highest copied row instead of discarded source reservation batches.

### Issue-to-test proof

- The exact issue reproduction reports source next `4`, clone next `5`, and first cloned-table insert `4` for table, database, and both Data Branch clone forms.
- Empty sources insert `1`; a source whose largest row was deleted seeds the independent clone from the copied maximum; explicit `AUTO_INCREMENT = 100` inserts `100`; snapshot clone asserts snapshot-visible rows plus exact `4 / 5` inserted/next values.
- A permanent source cloned into a temporary table preserves copied IDs `10` and `11`, then assigns `12` to the first destination insert.
- Unit tests prove that fresh visible columns discard the persisted reservation while preserving the larger source/destination schema floor; ALTER COPY and hidden internal columns retain allocator state required by their ownership model.
- The existing chained-clone BVT proves subsequent clone and delete/insert sequences continue at `40001` through `40006`, without introducing a new 10,000-value gap at each clone.
- The snapshot/restore procedure checks still validate every catalog field except the pre-existing ignored ID and timestamp columns. Their deterministic unique `name` ordering prevents ignored allocator IDs from pairing one procedure with another.

### Verification

Latest semantic rebase: patch-equivalent head `1c9ff2e42bc751bd0028bcfe0cd51b8704071bcb` was rebased conflict-free from `main` at `a15139da62b938b0918c19675c619b259cd86460` onto `main` at `07fe9a69c6a3d6ed5e2b4299fb143d10bef442c0`, producing exact head `23c7a20c072375324fee984c087de370ef5bd323`.

- `git range-diff a15139d..1c9ff2e 07fe9a6..23c7a20`: all four clone patches are equivalent.
- Stable aggregate patch ID before and after the rebase: `ff530dfc6cb58fd343bc0663b95c917a95aa40fc`.
- The final diff is the intended six clone files plus two targeted snapshot BVT files; `git diff --check origin/main...HEAD` passed and the worktree is clean.
- On exact head `c3332623e5be8961a2c54bed286c888b75f82bee`, an isolated local MatrixOne service and mo-tester upstream/main `334d3e124bbfbdcd6b5cc63439278d172c72b706` passed `sys_restore_system_table_to_sys_account` twice with CI flags `-g -n -o`: 313/313 statements each time. Normal metadata mode also passed 313/313.
- A direct matcher negative-control proves the BVT assertion remains strict: ignored IDs `9/10` versus expected `1920000/1920001` fail under full-row sorting, while `ORDER BY name` plus `@sortkey:1` pairs rows correctly; mutations to each of the 14 non-ignored columns are rejected. `@sortkey:1` alone remains order-dependent, so it is deliberately paired with SQL ordering.
- Exact-head MatrixOne CGo validation selected and passed all eight focused clone allocator tests.
- Incoming main commit `07fe9a69c6 fix(embed): align HAKeeper transport timeout under race (matrixorigin#27849)` changes only embed/logservice configuration and its tests, with no PR-file overlap. All six directly affected tests passed: three embed timeout/config tests, two logservice client-config tests, and the authenticated two-CN fixture test.
- Because the incoming logservice change is a transitive dependency of the clone owners, the complete `pkg/sql/compile`, `pkg/frontend`, and `pkg/sql/colexec/table_clone` packages were rerun through the MatrixOne CGo wrapper and passed on exact head `23c7a20c07`.
- Workflow `33283224004` attempt 1 on exact head `23c7a20c07` passed shared build, normal Ubuntu UT, SCA, Coverage UT, and PROXY BVT. All three changed clone cases passed; PESSIMISTIC BVT reproduced only unrelated matrixorigin#27164, and aggregate Coverage was derivative.
- Attempt-2 PESSIMISTIC BVT job `99187224896` is in progress after the single permitted failed-job rerun.

### CI investigation

- matrixorigin#27164 remains the underlying mo-tester defect. Workflow `33283224004` attempt 1 reproduced its snapshot result-pairing mismatch in PESSIMISTIC BVT job `99182619116` on exact head `23c7a20c07`.
- PESSIMISTIC BVT completed 72,946 statements with 72,471 successful, exactly two failed, 473 ignored, and zero abnormal. `snapshot/sys_restore_system_table_to_sys_account.sql` completed 313 statements with 311 successful; at SQL rows 167 and 183, both `mo_stored_procedure` comparisons reported `row:0,column:1`, expected `test_if_hit_second_elseif`, and received `test_if_hit_else`. Expected ignored `proc_id` values were `1920000/1920001`; actual ignored values were `9/10`. The final error list contains no other SQL.
- All three changed clone cases passed in attempt 1: `clone_auto_increment_state.sql` 65/65, `table_clone.sql` 74/74, and `temporary_table_clone.sql` 163/163. This PR now adds only a case-level mitigation for all five `mo_stored_procedure` selectors in the same snapshot test; it does not modify mo-tester, expected `proc_id` values, or ignored columns. Fresh CI on `c3332623e5` is pending.
- Attempt-1 aggregate Coverage job `99186546271` was derivative: its direct log records `prerequisites_ready: false` for generation `33283224004-1` and exits before coverage processing.
- Workflow `33283224004` was rerun for failed jobs exactly once; its old-head results are superseded by fresh CI on `c3332623e5`. The rerun policy remains exhausted for that prior workflow.
- matrixorigin#27847 is resolved as a blocker for this PR. Current main includes matrixorigin#27848 test synchronization, and the directly affected quota test passed on the preceding exact head.
- matrixorigin#27833, matrixorigin#27127, matrixorigin#27771, matrixorigin#26519, and matrixorigin#27145 remain resolved as blockers for this PR.

### Residual risks

A fresh clone intentionally owns an independent allocator. If the highest generated source rows were deleted, the clone starts after the highest row it actually copied rather than inheriting an unused cached range from the source CN. Explicit schema lower bounds remain preserved. There are no catalog, wire-format, or API changes in this PR, and the fix does not read or mutate source CN allocator caches.

Approved by: @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…n#27826)

### Root cause

The failing PROXY BVT exposed inconsistent lock order around data-branch owner catalogs. Restore could hold snapshot/catalog locks and later replace `mo_feature_registry`, while snapshot/PITR publication, lineage GC, account deletion, data-branch mutation, and CCPR cleanup entered through different orders. Restore could therefore be selected as a deadlock victim; the later account mismatch and reconnect failures were consequences of that aborted restore transaction.

Review also exposed liveness boundaries: background GC could hold the global owner boundary through unbounded work and repeat full discovery up to 16 times; local contention could mask parent cancellation; a DATA BRANCH statement inside explicit `BEGIN` could retain the singleton boundary until a user-controlled later commit; CCPR snapshot cleanup bypassed the boundary entirely; and commit-time validation initially covered only ordinary COMMIT, allowing repeated BEGIN or SET autocommit=1 to commit the marked transaction without crossing the boundary.

### Changes

- Use the bootstrap-created `SNAPSHOT` row in `mo_feature_registry` as the single owner-lifecycle boundary; remove the independent `mo_tables` gate.
- Cross the boundary before snapshot/PITR create, drop, and retention changes; internal Create/Drop PITR; COPY ALTER ownership decisions; whole-account/cluster snapshot or PITR restore; standalone DROP ACCOUNT; ordinary DROP DATABASE/TABLE; every data-branch create/delete transaction; and CCPR snapshot deletion.
- Keep restore-internal DROP ACCOUNT reentrant because whole-account restore already owns the boundary in its outer transaction. Database/table restore remains outside this gate because it does not replace account-level owner catalogs.
- Centralize data-branch create/delete admission for all four mutation paths. Autocommit mutations acquire the boundary at transaction admission. Explicit user transactions preserve the existing transactional DATA BRANCH contract without retaining the global row between statements: a successful mutation marks the transaction, and the single low-level terminal commit path performs a system-account fast-fail validation write on the same transaction immediately before physical commit. This covers ordinary COMMIT, replacement BEGIN/START TRANSACTION, and autocommit off-to-on. A competing lifecycle writer aborts and fully rolls back the user transaction using the transaction cleanup context, so cancellation cannot leave its earlier catalog locks alive.
- Preserve feature-quota freshness ordering: ordinary RC mutations establish the TN catalog frontier before writing the lifecycle row; fixed-SI checks keep their independent pessimistic-RC quota transaction and do not advance the outer snapshot.
- Run lineage GC as one explicit-SI work unit per scheduled invocation: one complete discovery, one fast-fail lifecycle validation, and at most 128 paired snapshot/metadata deletes. This removes the previous 16-fold full-catalog rescan amplification while retaining durable progress across runs. A one-minute task-work budget bounds worker occupancy; local expiry and lock/SI contention roll back and defer. Parent cancellation/deadline takes precedence, while remote-owner timeout and substantive failures remain visible.
- Make CCPR snapshot cleanup execute `lifecycle gate -> escaped snapshot delete -> commit` in one transaction. Gate/delete failure rolls back; commit failure is returned without a blind post-commit rollback, preserving unknown-commit handling.
- Allow compile internal SQL execution with a nil plan in direct Scope callers; production plan behavior, including DROP DATABASE foreign-key handling, is unchanged.

### Issue-to-test proof

- The existing BVT `snapshot/cluster/restore_dropped_account_with_cluster.sql` is the reported reproduction: it restores dropped/replaced accounts, verifies the account set, authenticates restored accounts, and validates table data. It passed twice through a real two-CN PROXY (`204/204` each); subsequent required PROXY CI also passed.
- `TestLineageOwnerLifecycleLockSerializesEmptyProbe` proves competing owner decisions cannot bypass the stable row.
- `TestLockRestoreLineageOwnerLifecycleCoversWholeCatalogRestore`, `Test_doDropAccount_InTransaction`, and `TestOwnerCatalogDropEntryPointsStopAtLifecycleAdmissionFailure` cover restore levels, standalone/reentrant account deletion, ordinary DROP entry points, and gate-failure rollback/order.
- `TestGetDataBranchMutationExecutorAdmitsBeforeMutation`, `...RollsBackOnAdmissionFailure`, and `TestValidateDataBranchLineageOwnerLifecycleAtCommitFastFailsStableWrite` prove common admission order, cleanup, same-transaction validation, system-account execution, disabled statement retry, and fast-fail policy.
- `TestLineageOwnerLifecycleValidationCoversEveryTerminalCommitPath` proves ordinary COMMIT, replacement BEGIN, and autocommit off-to-on all validate before physical commit and fully roll back on failure.\n- `TestIssue26113CloneCreatedTableInSameTransaction` preserves DATA BRANCH's existing explicit-transaction atomicity and is the exact coverage-mode regression that caught the rejected-statement design.
- `TestIssue26087ConcurrentDataBranchQuota` uses two CNs to prove an open tenant transaction does not own the global lifecycle row, a completed system snapshot forces both tenant COMMIT and replacement BEGIN validation to fail and fully release its catalog locks, concurrent autocommit table/database branch mutations preserve exact quota outcomes, fixed SI is not advanced, and implicit transaction mode keeps its independent mutation transaction. The upstream matrixorigin#27848 logtail-frontier synchronization remains composed in the same test.
- `BenchmarkComputeAlterLineageCompactionPlan2049` records the remaining single-discovery planner cost and allocation envelope under `-benchmem`.
- `TestCompactExpiredAlterDataBranchLineageWithExecutor` proves discovery precedes lifecycle admission and only the bounded delete pair follows it.
- `TestDataBranchLineageGCExecutorMakesDurableProgressAcrossRuns` proves one independent committed batch per run and eventual cleanup across runs.
- `TestDataBranchLineageGCExecutorScansOnceAndBoundsMutationAtScale` uses 2,049 eligible generations to prove one discovery transaction and a 128-row commit cap instead of 16 complete rescans.
- `TestDataBranchLineageGCExecutorDefersOnLocalTimeBudget`, `...DefersAfterContentionRollback`, `...ParentContextPrecedesContention`, and `...DoesNotSuppressOtherErrors` close timeout, contention, parent-control, rollback, and substantive-error paths.
- `TestDeleteSnapshotWithLifecycleGateIsAtomicAndOrdered` proves CCPR gate/delete/commit order, SQL quoting, rollback on both pre-commit failures, and commit-error propagation.

### Validation

Latest review update, exact head `d6925af23a`:

- `TestLineageOwnerLifecycleValidationCoversEveryTerminalCommitPath`: passed\n- focused lifecycle terminal-path race stress at `-count=100`: passed\n- coverage-mode exact two-CN `TestIssue26087ConcurrentDataBranchQuota`, including replacement BEGIN: passed\n- complete `pkg/frontend`: passed\n- complete `pkg/frontend -race`: passed
- CI-version `golangci-lint 2.6.2 --enable-only prealloc ./pkg/frontend ./pkg/tests/issues`: 0 issues
- `git diff --check`
- post-rebase coverage-mode `TestIssue26087ConcurrentDataBranchQuota` and `TestIssue26113CloneCreatedTableInSameTransaction`: passed together
- post-rebase focused matrixorigin#27849 embed/logservice HAKeeper timeout tests: passed
- post-rebase focused matrixorigin#27154 fresh-clone and ALTER COPY auto-increment allocator tests: passed
- post-rebase focused matrixorigin#27814 LOAD unique-index promotion plus lineage-GC lifecycle tests: passed
- post-rebase complete `pkg/sql/compile`: passed

Earlier series evidence retained:

- full `pkg/frontend`, `pkg/sql/compile`, `pkg/publication`, `pkg/util/executor`, and `pkg/frontend/...` suites; CGo-configured vet
- focused GC, restore, quota, CCPR, and lifecycle race tests
- exact PROXY reproduction twice on the same instance (`204/204` both runs)
- coverage-mode public regressions for snapshot restore and two-CN quota admission
- 2,049-row planner benchmark, three one-second samples: 819-898 µs/op, 463,384 B/op, 8,135 allocs/op
- CI-version SCA correction and focused validation

Freshness:

- current `origin/main` / PR base: `7a87bd69891d498ca72c7eb3a92458da2992f6a1` (matrixorigin#27814)
- exact head: `d6925af23ab02f640ebb815d6a20b2441fb7f052`
- the prior twelve-patch series remains unchanged by the last rebase; the terminal-commit closure is the thirteenth patch
- matrixorigin#27814 directly overlaps `pkg/sql/compile/compile.go` and adds LOAD unique-index lock promotion before source initialization plus retry-owned proof cleanup. The composed diff keeps that state machine unchanged; this PR's nil-plan internal-SQL guard remains isolated in `runSqlWithResultAndOptions` and still preserves DROP DATABASE foreign-key options for non-nil plans. Focused tests for both lock/lifecycle protocols, the complete compile package, and this PR's two exact embedded-cluster regressions passed after rebase.

### Residual risks

The shared write boundary serializes rare owner-lifecycle mutations globally. Autocommit owners hold it only for their mutation transaction; an explicit DATA BRANCH transaction holds no global row while idle and must win fast-fail validation immediately before COMMIT or roll back. Existing ordinary DDL and administrative statements remain prohibited in explicit transactions. GC still performs one complete read-only catalog discovery, but never holds the foreground boundary during that scan; each invocation has a one-minute work budget and can commit no more than 128 paired rows. Remaining eligible lineage advances on later scheduled runs.

Approved by: @XuPeng-SH, @fengttt

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/test-ci size/S Denotes a PR that changes [10,99] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants