Skip to content

fix: preserve publication references to physical databases - #29423

Merged
XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-29414-publication-integrity
Sep 28, 2026
Merged

XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-29414-publication-integrity

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Improvement
  • Test and CI

Which issue(s) this PR fixes:

Fixes #29414

What this PR does / why we need it:

A sys-owned publication can reference a physical database owned by another account. The old DROP guard checked the publisher account and database name while planning, so the target account could drop a published database; a later same-name database could then be blocked by the stale publication.

CREATE/ALTER PUBLICATION now takes a shared lock on the source account's exact mo_database key and revalidates the resolved database ID. DROP DATABASE takes its existing exclusive lock, refreshes its pessimistic-RC snapshot, reopens the database, and checks all publishers for that physical ID before deleting it. Post-lock index metadata cleanup also uses the reopened ID, so a prepared DROP cannot clean the wrong incarnation after a same-name replacement. The obsolete planner-time publication decision is removed.

The fresh catalog and the 4.0.8 upgrade both add an index on mo_pubs(database_id). Upgrade checks for named publications with missing or stale IDs and stops for explicit repair instead of admitting unprotected historical rows. DATABASE * retains its special ID=0 behavior. Upgrade should run after a stopped cutover; mixed old/new publication writers are not covered. This change addresses pessimistic RC; fixed-SI DROP support remains separate (#29417/#29400).

Validation:

  • make cgo -j4 and make build-with-prebuilt-native -j4 on the feature worktree.
  • Full pkg/frontend, pkg/sql/plan, pkg/sql/compile, and pkg/bootstrap/versions/v4_0_8 Go package tests passed; pkg/frontend also passed with -race.
  • New BVT specifies cross-account/same-name identity, comment-only and source-changing ALTER, prepared DROP, atomic DROP ACCOUNT, and prepared DROP after same-name replacement. The same SQL behavior was exercised twice on an isolated locally built service; the BVT runner itself was not available locally.
  • Ten overlapping CREATE PUBLICATION vs DROP DATABASE runs produced both commit orders without a dangling publication or dual success. This is a timing challenge, not an exhaustive deterministic schedule proof.
  • A committed two-CN integration regression now observes the exact mo_database lock waiter before testing DROP rollback, commit, same-name replacement, and KILL QUERY. It asserts physical-ID binding, rejection of a published source DROP, no dangling publication after failure or cancellation, and successful follow-up work. The focused test passed normally and with -race on 1847a9d8d3.
  • Live EXPLAIN of the runtime literal-ID predicate chose Index Table Scan on mo_pubs.idx_mo_pubs_database_id. The upgrade audit SQL parsed and planned as a one-time MARK join.

Additional validation for the latest fix:

  • DROP DATABASE lookup errors: eight focused cases covering pre/post-lock lookup, missing database vs timeout, and IF EXISTS passed.
  • TestIssue26640ClusterRestoreRebindsSubscriptionPrivileges passed twice before rebase and once on the rebased production head 0e4bcb1c39; the subsequent commit adds only the publication concurrency test. Full pkg/frontend and pkg/sql/compile package tests passed.

CI update: the failed run on e37552ef22 started before #29426 fixed main's missing SendConfig argument and five-point decay test expectation. This PR is rebased onto that fix at head 1847a9d8d3, based on b9013dc6bb. On that base, both previously failing TAE tests and TestIssue26640ClusterRestoreRebindsSubscriptionPrivileges passed. The focused publication concurrency regression passed in normal and race modes. New-head CI is pending; this is not a full CI pass. The PR also fixes its own earlier cluster-restore txnOp is nil failure and cancellation barrier race.

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review of ac4ab88662262a1dc5f3bb8eb66086b363a5aef5 against main / merge-base 9b7c2c23dba737232d975d66bd04628199e1a436.

Recommendation: fix the P2 error-propagation regression below before merging. The physical-ID / shared-catalog-lock approach is appropriate for the declared pessimistic-RC, stopped-cutover scope. I found no other concrete merge blocker in the 14-file diff.

Validation and challenge results:

Contract Result / evidence
Cross-account physical identity; same-name independent DB; ALTER; prepared DROP; failed DROP ACCOUNT rollback Reviewed the full closure and reused the prior local SQL/package evidence. The relevant production/test files are unchanged from a436e28; current head only merges main's TAE change.
Publication waiting behind DROP New public-SQL challenge on the isolated built service: hold DROP in an explicit transaction, observe a lock waiter, then independently test rollback, commit, same-name replacement, and KILL QUERY. Rollback permits the publication; commit/replacement return RC retry and create no dangling reference; cancellation returns promptly and subsequent publication/drop succeed.
Restore / identity rebinding New cluster-snapshot restore challenge passes: restored table data is correct, publication joins the new physical DB ID, and DROP of the restored published DB is rejected.
Wildcard policy New public-SQL controls pass: wildcard-only publication permits DROP; adding a named publication blocks it; removing that named publication permits DROP again.
Unhappy-path error propagation Fails: focused white-box probe injects a post-lock engine database lookup timeout. Both IF EXISTS variants fail the error-preservation assertion on the candidate. The identical probe with baseline ddl.go / ddl_test.go supplied through a Go overlay passes both variants. This is a focused baseline-source comparison, not a full baseline service run.
Resource lifetime / performance Lock ownership stays with the background transaction; process/vector/result cleanup and detached close-time rollback were traced. No new unbounded queue, goroutine, or global serialization mechanism. Prior live literal-ID EXPLAIN selects idx_mo_pubs_database_id; this is plan evidence, not a latency/load benchmark.

Coverage limitations to retain explicitly: the committed frontend tests stub lockPublicationDatabase, and the modified DROP UTs stub ensureDatabaseNotPublished; the new BVT is sequential. The controlled wait/cancel/replacement challenges above should be incorporated into the existing regression structure, with the error-propagation cases below, rather than multiplying happy-path fixtures. A real 4.2-release upgrade and multi-CN timing challenge were not executed in this review; the upgrade test mocks catalog SQL. SI and mixed-version writers remain outside this PR's declared guarantee.

The isolated review data was cleaned up and the temporary probe was removed from the source worktree. Latest head was rechecked; UT/SCA/Coverage/BVT were still running, so this review does not claim green CI. Review is submitted as COMMENT because the authenticated account is also the PR author; the recommendation remains to address the finding before merge.

Comment thread pkg/sql/compile/ddl.go
Comment on lines +209 to +213
if err != nil {
if s.Plan.GetDdl().GetDropDatabase().GetIfExists() {
return nil
}
return moerr.NewErrDropNonExistsDB(c.proc.Ctx, dbName)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve non-missing errors from the post-lock database lookup

This branch converts every failure from the authoritative re-open into either success (IF EXISTS) or “database does not exist”. If the database existed on the first lookup but this second lookup fails with a storage/RPC timeout or an internal engine error, DROP can report success without deleting it, or conceal the real failure. Previously the corresponding post-lock lookup propagated its error.

Verified with a focused white-box probe: first Engine.Database returns a database; the post-lock lookup returns context.DeadlineExceeded while the request context remains live. Candidate results are nil with IF EXISTS and ErrDropNonExistsDB without it. The same probe using baseline DDL source returns the original timeout in both cases.

Suppress/translate only the engine's typed authoritative “database absent” result, and propagate all other errors unchanged. Cover both IF EXISTS values for genuine absence and for injected lookup failures; keep downstream cleanup unreachable on a failed re-open.

XuPeng-SH added a commit that referenced this pull request Sep 28, 2026
## Problem

Current `main` fails UT, Coverage UT, and SCA after #29421. The replay
promotion test calls `SendConfig` with two arguments although the API
requires a snapshot timestamp. A separate replay case accepts five L0
decay points during promotion preflight, but the task-trigger converter
requires exactly four, so it fails later with a different error.

These failures also appear in #29423 CI, but neither failure is
introduced by that PR.

## Change

- Pass the zero timestamp in the scheduler unit test, matching the
current API.
- Enforce the existing four-point trigger contract at promotion
preflight, before workers start; reject extra points instead of silently
truncating them.
- Update the replay regression case to expect that validation error.

## Validation

- `mo-cgo-test -count=1 -timeout=4m ./pkg/vm/engine/tae/db/merge
./pkg/vm/engine/tae/db/test` — passed.
- Focused scheduler and replay promotion tests — passed.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep re-review of 7851401cba9d3f0ee00c2294c80d8550a40d3da7, against main/merge-base b9013dc6bb058ec74935a62ac3a35f57d13c2f98.

Recommendation: no remaining blocking code finding in the declared pessimistic-RC, stopped-cutover scope. Submitted as COMMENT because the authenticated account is also the PR author; this is not an independent GitHub APPROVE and does not waive required CI. No subagents were used. Production sources were not modified; extra QA used a temporary Go overlay and the source worktree remains clean.

Design and scope

The direction is sound: publication ownership and physical database ownership are different concepts, so the DROP guard must use the globally allocated physical database ID across publishers. CREATE/ALTER protects the resolved account/name catalog key with a shared lock and revalidates the identity; DROP uses the existing exclusive key, advances its RC snapshot, reopens the database, and queries references before deletion. Same-name replacement must not inherit the old reference or use the prepared plan's stale ID for index cleanup.

This is a focused integrity fix built on existing transaction/lock ownership, not a new lifecycle protocol or framework; a separate feature-design document is not required for this fix. The R3 review depth still applies to concurrency, cross-account access, catalog upgrade, and restore. Reusing the catalog-lock helper with an explicit mode is preferable to adding another lock namespace, cache, worker, or persistent state machine. Removing the obsolete planner-time decision avoids maintaining two competing authorities.

Accepted boundaries are important: fixed-SI DROP and mixed old/new publication writers are not protected by this PR's contract (#29417/#29400). Historical named NULL/0/stale references stop the upgrade for explicit repair; they are not silently rebound. Wildcard DATABASE * remains ID 0 and does not acquire named-database semantics. This is not a general rolling-upgrade guarantee.

Historical comments

The previous P2 lookup-error finding is fixed. Both initial and post-lock lookups suppress/translate only moerr.OkExpectedEOB; timeout and other engine errors propagate unchanged before downstream deletion/cleanup. I reran all eight committed permutations (initial/post-lock, missing/timeout, IF EXISTS on/off), and all passed.

The prior request to commit controlled concurrency evidence is also addressed by TestIssue29414PublicationWaitsForPhysicalDatabaseDrop: two CNs, an observed database-key waiter, rollback/commit/replacement/KILL QUERY, durable publication-ID/no-orphan assertions, and successful follow-up after cancellation. The previous restore nil-transaction failure is handled by starting publication replay's transaction when account recreation ended the previous one.

The sole historical inline thread is still marked unresolved in GitHub. Its technical defect is closed by source and tests; the UI flag is not an outstanding code defect. No new unresolved technical comment was found.

Validation and adversarial QA

Evidence Result and scope
Local lookup-error regression All 8 cases passed at this head.
Local publication index upgrade test Valid/idempotent creation and invalid-reference refusal passed. This is a mocked upgrade-entry test, not a real release upgrade.
Local committed two-CN CREATE/DROP test, -race -count=1 All four arms passed; test elapsed 21.27s. The 30s adaptive repetition budget selects N=1.
Additional temporary two-CN ALTER-source/DROP challenge, -race -count=1 Rollback and commit arms passed; 18.41s. A rolled-back DROP allows rebinding to the target ID; a committed DROP causes ALTER to fail while retaining its old physical reference. The resulting referenced DB remains non-droppable.
Exact-head coverage UT, run 36389134244 Downloaded report records terminal exit 0, no failed package/test events, and actual execution of TestIssue26640ClusterRestoreRebindsSubscriptionPrivileges (185.940s). Reused rather than rebuilding that expensive restore fixture.
Exact-head compose BVT Downloaded execution log explicitly reports publication_database_identity.sql: 29/29 success, 0 ignored/abnormal, 2.123s. This proves actual normal-comparison selection, not merely a green job name.
Static/delivery Exact-head SCA and both active BVT lanes completed successfully; range whitespace check passed. The separate Ubuntu UT job was still running at the last check, so this does not claim all CI green.

The extra ALTER challenge follows the actual unchanged counterpart: ALTER and DROP first serialize at the existing SNAPSHOT -> View lifecycle gates, before the database key. Initial temporary probe versions observed the wrong physical table and failed their barrier assertion; after tracing catalog.LockViewMetadataLifecycle, the probe observes the actual gate and passes. Those probe-construction failures are not product findings or hidden retries of a flaky product assertion.

Unhappy paths, cost, and engineering quality

Audit Closure
Q1 ownership Lock process and vectors are freed locally; transaction commit/rollback owns lock release; query results are closed; background-session close retains rollback cleanup after request failure/cancellation.
Q2 progress Database/lifecycle waits reach the existing transaction lock service. The committed cancellation test proves the publisher returns while DROP is still held, then waiter retirement and subsequent work complete. ALTER uses the same lifecycle-before-database order as DROP.
Q3 boundedness No new server queue, goroutine, retry loop, cache, or retained global collection. The runtime guard returns at most one row; temporary objects are statement-owned.

Performance impact is on DDL/publication operations, not per-row SELECT execution. The extra shared lock and post-lock lookup are the integrity cost; the literal-ID LIMIT 1 probe has a matching fresh/upgrade index, and the previously recorded live EXPLAIN selected it. No new latency/throughput benchmark is claimed. Upgrade auditing can scan the catalogs, but it is a one-time stopped-cutover check, not a hot-path join. Global View lifecycle serialization already exists in the base and was not added by this PR.

The tests cover distinct error, concurrency, public-SQL, and upgrade contracts with a shared existing two-CN fixture rather than another service harness. A useful non-blocking follow-up is to fold the ALTER rollback/commit oracle into that existing regression, not create another issue-number fixture. A real released-binary upgrade and fixed-SI/mixed-version safety were not exercised here; preserve those explicit release boundaries.

@XuPeng-SH
XuPeng-SH merged commit 239fe81 into matrixorigin:main Sep 28, 2026
3 of 6 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/issue-29414-publication-integrity branch September 28, 2026 08:06

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/enhancement kind/test-ci size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Cross-account publication survives DROP of its physical database

2 participants