Skip to content

feat(view): add durable lifecycle admission fence - #27430

Merged
XuPeng-SH merged 46 commits into
matrixorigin:mainfrom
ck89119:issue-26227-admission-main
Aug 26, 2026
Merged

XuPeng-SH merged 46 commits into
matrixorigin:mainfrom
ck89119:issue-26227-admission-main

Conversation

@ck89119

@ck89119 ck89119 commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #26227

What this PR does / why we need it:

This is stack 3/4 for View metadata lifecycle safety. It establishes the durable admission prerequisite required before the later activation PR can expose lifecycle behavior.

Safety contract

  • Adds a replicated two-phase HAKeeper barrier with a monotonic View metadata epoch, catalog-fence acknowledgement, per-process generations, pending admission, timeout reconciliation, and snapshot recovery.
  • Gates HAKeeper membership changes on post-upgrade LogStore capability so an older RSM cannot join after the new update type becomes active.
  • Makes CN startup obtain a unique generation, observe and drain the local epoch fence, persist the existing REVALIDATE_REQUIRED catalog sentinel after bootstrap, and wait for authoritative admission before starting public listeners.
  • Makes Proxy startup wait for authoritative admission and synchronously refresh its atomic membership snapshot before acknowledging a new epoch.
  • Publishes the global admission state and CN generation/readiness in one ClusterService snapshot; normal routing excludes pending generations while the CN bootstrap path can still find itself.
  • Requires current generation equality for cached Proxy reuse and preserves generation across temporary management connections and plugin-selected routes.

Compatibility and scope

  • The protocol activates only after all current HAKeeper members and live services have reported post-barrier support.
  • This PR is the admission-aware, lifecycle-unaware rollback baseline. Pre-admission binaries are not a supported rollback target after the barrier is enabled.
  • ViewMetadataRefreshEnabled remains disabled, the final refresh capability is not advertised, and no recovery worker or public fail-closed metadata behavior is enabled here.

Validation

  • make generate-pb was run twice and produced an identical protobuf diff.
  • Full ordinary tests passed for pkg/hakeeper, pkg/logservice, pkg/clusterservice, pkg/sql/compile, pkg/cnservice, and pkg/proxy through the repository CGo wrapper.
  • Every added or modified focused regression passed adaptive race stress with a 30-second budget (N=100 for all measured tests), followed by full owning-package race runs.
  • The same owning packages passed go build and go vet with the repository CGo environment.
  • Focused statement coverage for the four new production files is 83.8%, 77.4%, 77.5%, and 78.4%.

Dependency order

  1. refactor(view): add metadata regeneration foundation #27267 - metadata correctness foundation (merged)
  2. refactor(view): add inactive metadata lifecycle #27370 - inactive lifecycle state and durable revalidation markers (merged)
  3. this PR - durable membership/capability epoch and admission fence
  4. the dependent activation Draft - recovery worker and public fail-closed behavior

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

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

Codex automated review

Deep first-principles review of the durable admission fence (stack 3/4 for #26227). No prior reviews/comments existed on this PR. I verified prior behavior from origin/main, traced every new code path, and validated by building thirdparties/libmo from scratch and running the owning packages' tests, including -race.

Design verification

  • Two-phase replicated barrier mirrors the established EnableCommandDeliveryUpdate precedent: phase 1 (Preparing, epoch=1) is only proposed after all non-expired LogStores advertise support and HAKeeper admission is settled; phase 2 requires every live CN/proxy to have observed the epoch, catalog-fence ack at the epoch, and no pending replaced-generation targets. RSM handlers are idempotent against duplicate/stale proposals, and unknown-update panic on old RSMs matches the documented no-rollback-after-barrier contract (same as command delivery).
  • Generation fencing is sound: stale-generation heartbeats are rejected without state mutation (owner keeps its entry), replacements capture the old generation as a target with conservative liveness ticks, reconciliation entries expire abandoned targets deterministically, and delete-CN/proxy prunes historical membership. RecoverFromSnapshot resets all admission fields, so pre-feature snapshots fail closed.
  • CN/proxy startup contracts hold: generation allocated before any listener, epoch fence drained and REVALIDATE_REQUIRED sentinel persisted before Admitted, ingress readiness published only after all listeners are up (CN has a dedicated ViewMetadataIngressReady; legacy CNs keep ready=true during Preparing so rolling upgrades never withdraw serving stores). Proxy synchronously refreshes its authoritative cluster snapshot and proves the refreshed epoch before acking. Revocation closes ingress synchronously and defers full Close off the heartbeat goroutine, avoiding self-deadlock.
  • Routing is consistently fail-closed: clusterservice filters every public inventory, ClusterDetails hides legacy non-ready stores while keeping capable pending ones visible, disttae candidate discovery excludes pending CNs, cached-connection reuse and plugin-selected routes now require generation equality, and conn cache binds the owning handler's cluster (also fixing a stale-runtime-global binding and a plugin-client close leak).
  • Mixed-version compatibility checked: new services against old HAKeeper see nil admission snapshots and proceed (dormant); old binaries against new HAKeeper keep legacy behavior until activation.

Validation
Built thirdparties+libmo locally, then passed: pkg/hakeeper (full and -race), pkg/clusterservice, pkg/sql/compile fence tests (-race), pkg/cnservice (full and -race admission subset), pkg/proxy (full and -race admission subset), pkg/logservice admission/command-delivery/heartbeat tests, pkg/vm/engine/disttae new filter tests. An initial pkg/proxy failure batch (TestKillEvent/TestHandler_HandleErr panic etc.) was proven environmental: the review harness overrides TMPDIR into a 135-char path, exceeding the macOS 104-byte unix-socket limit (bind: invalid argument); identical tests pass with TMPDIR=/tmp.

Two non-blocking observations reported as findings: the per-restart admission blackout window inherent to conservative target reconciliation, and heartbeat command-processing ordering when admission apply fails.

P2 - Restart of a ready CN/proxy blocks admission promotion cluster-wide for ~CNStoreTimeout (~30s default) (pkg/hakeeper/view_metadata_admission.go:456)

When an admission-ready CN/proxy restarts, captureCN/ProxyViewMetadataAdmissionTarget (line 456 for CN) records the replaced generation as a target whose ticks only refresh from heartbeats of that exact generation. Since the old process is gone, the target survives until expireViewMetadataAdmissionTargets ages it out (~CNStoreTimeout = 30s default after the old owner's last tick). viewMetadataAdmissionTargetsReady() (line 231) is evaluated globally, so during that window: (a) the restarted store itself stays ViewMetadataAdmissionReady=false and is excluded from routing even after it is fully started and ingress-ready (tryPromoteViewMetadataAdmissions at line 249 is gated on targetsReady); (b) any other CN/proxy currently in waitForViewMetadataAdmission sees Admitted/Ready=false and can exhaust its DiscoveryTimeout (30s default, pkg/cnservice/server_view_metadata_admission.go:183), failing startup and relying on process restart retries. Already-serving ready stores are unaffected, so this is not a capacity loss of running nodes. I recognize this as the documented fail-closed tradeoff (ViewMetadataAdmissionTargets proto comments; TestViewMetadataAdmissionReplacementKeepsOldGenerationUntilTimeout; TestViewMetadataAdmissionPreparingWaitsForReplacedGenerationTimeout) — the replaced generation must be proven dead by heartbeat timeout before trusting the replacement. Flagging for explicit confirmation of the operational consequence: routine rolling restarts serialize with a >=30s non-routable window per restarted node, and concurrent startups race the target-expiration deadline. If that cost is ever deemed too high, scoping the targetsReady gate to the affected UUIDs (instead of blocking all promotions) would be the natural refinement; not required for this baseline PR.

P2 - Admission-apply failure in CN heartbeat skips command-batch handling for that round (pkg/cnservice/server_heartbeat.go:247)

heartbeat() returns early when applyViewMetadataAdmission errors (line 247), before handleHeartbeatResponse, so schedule commands carried in an otherwise-successful heartbeat response are not applied in that round. There is no command loss: the acked at-least-once protocol redelivers the durable batch on the next successful heartbeat because AckedCommandBatchID was not advanced. Within this PR the exposure is bounded — after the one-time catalog fence succeeds, viewMetadataCatalogFencedEpoch >= snapshot.Epoch short-circuits fenceViewMetadataCatalog and the epoch never advances past 1, so apply effectively cannot fail on later heartbeats. The reason this is worth noting: the dependent activation PR will advance epochs on live CNs, making ViewMetadataEpochFence.Advance (which drains live leases and can block or fail on cancellation) a realistic slow/failure path at exactly this early-return point, repeatedly deferring command application each time. Consider in the activation layer whether command-batch handling (or at least ack bookkeeping) should be ordered independently of admission apply; no change required in this baseline PR.

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

Re-reviewed all history, the delta from prior reviewed head daab92b19abe857746c19271cdff23d007872fd4, and the complete diff at exact head 21dbb9a237021b1f7284c89511cf5fe4f8ec300d. The delta correctly isolates replacement-target admission to the affected UUID and preserves command processing when admission application returns an ordinary error.

The remaining blocker is a CN Start/revocation ordering hole: revocation closes the gates, but an already-running Start sequence can continue and republish/start ingress before its asynchronous Close obtains the lifecycle lock.

Unhappy-path audit: replicated target maps are bounded and pruned; epoch-fence Acquire/Advance/Close termination paths pass; normal startup rollback and proxy revocation ownership pass; CN generation revocation during Start fails the no-reopen invariant below.

Validation with CGO/local thirdparties: full owning-package tests for hakeeper, clusterservice, cnservice, logservice, proxy, sql/compile, and disttae; focused race tests x20; go vet; and git diff --check. A controlled counterexample reproduced the blocker and was removed afterward.

Comment thread pkg/cnservice/server.go Resolved

@XuPeng-SH XuPeng-SH left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deep-reviewed exact head 21dbb9a.

[P1 lifecycle/generation safety] An in-progress CN Start can reopen ingress after a higher-generation heartbeat revokes it. Start holds lifecycleMu from serviceStarting through frontend/query/pipeline startup. revokeViewMetadataGeneration synchronously clears readiness and closes gates/Stop()s the frontend, then queues full Close asynchronously; that Close cannot acquire lifecycleMu until Start returns. Because Start has no irrevocable revoked/canceled-start state or checks after admission, it can continue through queryService.Start, runMoServer, server.Start, write viewMetadataIngressReady=true, and start the task runner after revocation. stopFrontend can also overlap MOServer.Start. The stale generation is therefore briefly republished/running and violates the generation-N-cannot-reopen-N+1 boundary.

Please add an irrevocable generation-revoked/start-canceled state that the startup path checks around every ingress publication/start and before task-runner publication, without making the heartbeat wait on lifecycleMu, and add a deterministic regression that delivers a higher-generation response after admission but during Start and proves no ingress is restarted/readied.

I also traced the epoch-fence owner/wait graph, HAKeeper target reconciliation, Proxy Start/Close serialization, routing filters, snapshot recovery, and command-processing ordering; no second blocker is needed for this verdict.

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

Reviewed exact head 21dbb9a237021b1f7284c89511cf5fe4f8ec300d.

[P1] A generation revocation can still be overwritten by an in-progress Start. Start holds lifecycleMu from admission through Sirius/query/frontend/pipeline startup. A higher-generation heartbeat can synchronously close ingress and queue Close, but that Close cannot acquire lifecycleMu; Start has no revoked/canceled-start state to observe and can continue through server.Start, store viewMetadataIngressReady=true, and start the task runner before the queued close runs. This also permits frontend Stop/Start overlap outside one lifecycle owner. Record an irrevocable revocation/start-cancel state without taking the lifecycle lock in the heartbeat path, check it before and after every ingress start and before readiness publication, and add a deterministic interleaving regression.

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

Re-reviewed all historical reviews, the resolved inline thread, the delta from previously reviewed head 21dbb9a237021b1f7284c89511cf5fe4f8ec300d, and the complete diff at exact head dda117a3a7c2de9844e99011e16a0915c6d40a1b. The new revocation marker plus frontendLifecycleMu closes the reported frontend Start/Stop ordering hole: revocation can no longer return before an in-flight MOServer start is serialized and stopped.

One blocking generation-safety gap remains at task-runner publication. A superseded CN can remain or become task-runner-ready while the higher-generation replacement owns the UUID; the concrete interleavings and exact-head counterexample are in the inline finding.

I re-audited the durable RSM barrier/target ownership, stale-generation heartbeat rejection, CN/proxy admission and shutdown graphs, cluster/proxy routing filters, connection-cache generation binding, epoch-fence wait graph, and partial-construction cleanup. Local verification with CGO and local thirdparties passed full tests for pkg/hakeeper, pkg/logservice, pkg/clusterservice, pkg/cnservice, pkg/proxy, pkg/sql/compile, and pkg/vm/engine/disttae; focused race tests x20; go vet; git diff --check; and a clean merge-tree against current main ba8954d543af0bdfb1948a8b89f77f5235ac9259. The temporary counterexample test was removed after reproduction.

Comment thread pkg/cnservice/server.go Resolved

@aptend aptend 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 re-review of exact head 3b74206. I reread every historical review, both inline findings and resolved/outdated thread state, compared the delta from my prior reviewed head dda117a, and re-audited the complete admission/lifecycle diff. The new task lock and revoked marker close future task-runner publication after revocation, including the prior runnerReady TOCTOU. One blocking generation-safety gap remains: an already-running runner, or one whose Start passed the precheck before revocation, is not stopped or otherwise gated and can continue work until asynchronous full Close reaches stopTask. Full owning-package tests, focused race tests repeated 20 times, go build/vet, gofmt, diff, and current-main merge-tree checks passed. A temporary exact-head counterexample failed as described inline and was removed.

@aptend aptend 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 re-review of exact head 0632570. I reread all historical reviews and all three resolved inline findings, compared the delta from my prior reviewed head 3b74206, and rechecked the complete durable-admission diff. The latest fix closes the remaining task-runner generation gap: revoke and publish/start linearize on task.Lock, revocation irrevocably disables future publication, detaches the existing/in-flight runner under that lock, and synchronously stops it outside the lock before returning. This covers both an already-running runner and revocation while TaskRunner.Start owns the task lock; concurrent Close remains safe via nil/idempotent Stop behavior. Full tests passed for cnservice, hakeeper, logservice, clusterservice, proxy, sql/compile, and disttae; focused race tests passed 20 times; go vet, diff checks, and a clean merge-tree against current main passed.

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

Re-reviewed exact head d738482e173c2d00b27082ec5dafcec64d08a55c against merge base e866c535f5723fca6a8522c8338f7277e4b9e40f.

The prior CN generation-revocation blockers are closed. Revocation is irrevocably published before any shutdown action; every startup ingress step checks it before and after activation. Frontend Start/Stop linearize on frontendLifecycleMu, while pipeline/query admission close synchronously without waiting for the broader lifecycle lock. Task publication/revocation linearize on task.Lock; revocation disables future publication, detaches an existing or in-flight runner, and stops it before returning. A failed/overlapped Start then converges through the single closeOnce owner.

I also rechecked the complete durable protocol: two-phase HAKeeper barrier and capability activation, monotonic epochs/generations, replacement-target scoping and expiry, snapshot recovery, CN/proxy admission acknowledgement, cluster routing filters, proxy connection-cache generation binding, partial-construction rollback, and epoch-fence Acquire/Advance/Close wait termination. Replicated target/history maps have prune/expiry bounds, and every listener/client/fence owner reaches one close path. The latest main merges do not alter these invariants. I found no blocking issue.

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

Re-reviewed exact head d738482 and the complete delta since my prior review.

[P1 unhappy-path / generation fence] Stop physical SQL ingress before waiting indefinitely for task executors.

revokeViewMetadataGeneration currently calls revokeTaskRunner at pkg/cnservice/server_view_metadata_admission.go:126 and only reaches stopFrontendSerialized at line 130 afterward. revokeTaskRunner synchronously calls TaskRunner.Stop; the production implementation waits in stopper.Stop with no completion deadline until every running executor goroutine exits. Executors are allowed to perform long external or SQL work and can ignore/delay cancellation. If one stalls, revocation never reaches MOServer.Stop and never schedules the full Close.

That leaves the superseded CN physical MySQL listener and existing frontend sessions alive indefinitely after HAKeeper has observed generation N+1. viewMetadataIngressReady only withdraws normal Proxy routing; it is not an admission gate in frontend, so direct clients can still submit SQL. queryWork and pipeline admission close only QueryService/pipeline RPC, not MySQL ingress. This violates the comment that scheduling asynchronous Close cannot leave a window for new SQL.

I reproduced this deterministically on this head with a blocking TaskRunner.Stop: after the runner entered Stop, MOServer.Stop had still not been called 100 ms later; it was called only after releasing the runner. The existing revocation tests use testRunner.Stop that returns immediately, so they cannot catch this ordering failure. The ordinary close graph already encodes the required ordering at pkg/cnservice/server.go:517-525: close QueryService, stop frontend, then drain task work.

Please withdraw/serialize physical frontend ingress before the potentially unbounded runner drain (while preserving the task lock linearization), or otherwise make frontend rejection independent and immediate. Add a regression with blocked TaskRunner.Stop proving MOServer.Stop/listener withdrawal occurs first, plus the existing running and Start-in-flight runner cases.

Validation performed:

  • full cnservice, hakeeper, logservice, clusterservice, proxy, and sql/compile packages passed
  • focused CN admission/revocation race matrix x20 passed
  • deterministic blocked-runner counterexample failed as described
  • diff check passed

I found no second blocker in the latest task-runner detach/Stop mechanics themselves; the ownership and double-Stop behavior are otherwise safe.

@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 re-reviewed exact head c46a010, reusing the complete architecture/ownership audit from the prior reviewed head and inspecting the full blocker delta plus subsequent main merges.

The prior P1 is closed. Revocation now irrevocably closes routing/query/pipeline admission, detaches the current or Start-in-flight runner under task.Lock, serializes physical MOServer shutdown with frontend Start, and only then waits for TaskRunner.Stop. Therefore a blocked executor can no longer keep the superseded CN SQL listener open. Runner publication/start and detachment still linearize on the same task lock; Stop remains outside that lock; normal Close observes the detached nil runner and does not double-own cleanup; the generation checks prevent later ingress or runner publication.

The deterministic regression blocks TaskRunner.Stop and proves frontend Stop happens first, while the existing already-running, Start-in-flight, and frontend-Start revocation cases remain covered. The later main merges do not alter the relevant CN files. Exact-head CI is green. No new correctness, hang, double-cleanup, generation, or performance blocker found.

@mergify

mergify Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-26 15:47 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-08-26 15:48 UTC · at 390669142de527aa5e79f27b5e72b370a1e0b8ec

This pull request spent 1 minute in the queue, with no time running CI.

Reason

The pull request can't be updated

This pull request seems to come from a fork, and Mergify needs the author's permission to update its branch.
The author needs to enable "Allow edits from maintainers" on this pull request, or update the branch manually.

Hint

You should update or rebase your pull request manually. If you do, this pull request will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants