Skip to content

fix(cnservice): return bootstrap failures - #26503

Merged
mergify[bot] merged 16 commits into
matrixorigin:mainfrom
ck89119:issue-26489-main
Aug 2, 2026
Merged

mergify[bot] merged 16 commits into
matrixorigin:mainfrom
ck89119:issue-26489-main

Conversation

@ck89119

@ck89119 ck89119 commented Jul 31, 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 #26489

What this PR does / why we need it:

CN bootstrap previously panicked for every failure except context.Canceled.
A transient HAKeeper connection reset therefore terminated the test process.

Returning the error safely requires complete lifecycle ownership. Bootstrap
must run after the embed operator owns the CN; constructor-opened SQL listeners
and bootstrap-created runtime services must be closed on rollback; and trace
consumers must remain alive until every producer has stopped.

This change:

  • returns bootstrap failures while preserving their context causes;
  • moves bootstrap to Service.Start() after operator ownership transfer;
  • closes SQL listeners even when MOServer.Start() was never called;
  • makes CN own bootstrap, auto-increment, and transaction-trace services, with
    generation-safe runtime cleanup;
  • closes pipeline admission atomically with handler registration, including
    requests already read by a goetty session when shutdown starts;
  • registers a server-owned cancellation context for every admitted pipeline and
    cancels all of them before waiting during shutdown;
  • gives fragmented message caches an independent cross-handler lifetime and
    releases every transferred fragment context on assembly, timeout, or session close;
  • cancels rejected and other unowned MORPC requests exactly once;
  • stops frontend, tasks, pipeline RPC, and transaction clients before closing
    trace; and
  • waits for all canceled pipeline handlers, then closes the auto-increment
    producer before the trace consumer.

Validation:

  • real bootstrap rollback, SQL listener reuse, concurrent trace shutdown, and
    real RPC admission-race tests passed 100 times
  • a real TCP/MORPC fragmented pipeline survives two cache cleanup scans and
    assembles all fragments
  • cache delete, request timeout, and session shutdown release transferred
    fragment contexts exactly once
  • focused lifecycle tests pass normally and under the race detector
  • full pkg/common/morpc and pkg/cnservice tests passed
  • full pkg/frontend and runtime tests, plus embedded rollback tests, passed
  • build and vet for affected packages passed
  • targeted golangci-lint passed with 0 issues
  • focused coverage is 94.6% for handleRequest, 88.9% for fragment handling,
    and 85.7% for cancelable cache creation

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

fix(cnservice): return bootstrap failures instead of panicking

🐞 Bug fix 🕐 40+ Minutes

Grey Divider

AI Description

• CN bootstrap now returns errors (preserving context causes) instead of panicking on transient
 failures like HAKeeper connection resets.
• Bootstrap moved into Service.Start() after operator ownership transfer, with full rollback of
 bootstrap-created runtime services (incrservice, txn trace) on failure.
• Pipeline admission is gated and canceled atomically during shutdown, including requests already
 read by goetty sessions, and trace consumers now wait for all pipeline producers before closing.
• Fragmented pipeline message caches gain an independent, cancelable lifetime so cleanup scans or
 handler cancellation no longer destroy in-flight fragment assembly.
• SQL listeners in frontend.MOServer are now closed even if Start() was never called, preventing
 port leaks on bootstrap rollback.
Diagram

graph TD
  A["Service.Start()"] --> B["bootstrap()"] --> C{"Bootstrap OK?"}
  C -- "No" --> D["handleBootstrapErr returns error"] --> E["Service.Close() rollback"]
  C -- "Yes" --> F["MOServer + pipeline admission active"]
  E --> G["closeBootstrapService"] --> H["closeIncrService"] --> I["closeTxnTraceService"]
  F --> J["handleRequest admits pipeline"] --> K["admitPipelineHandler / cancels map"]
  E --> L["closePipelineAdmission cancels pipelines"] --> M["waitPipelineHandlers"] --> I
  N["MORPC ClientSession cache"] --> O["CreateCacheWithCancel"] --> K
Loading
High-Level Assessment

The PR's approach—returning errors with preserved context causes, transferring full lifecycle ownership to Service.Start/Close, and using generation-safe CompareAndDelete for rollback—is the correct fix for the panic-on-transient-error bug. Alternatives like retry-wrapping bootstrap or keeping the panic but filtering more error types were considered implicitly (via the old context.Canceled-only special case) and rejected because they don't generalize to all transient failures; the chosen ownership-transfer design is necessary because rollback correctness requires the caller to control cleanup ordering.

Files changed (20) +884 / -62

Enhancement (5) +42 / -6
types.goAdd txnTraceService field and pipeline admission state to service struct +9/-0

Add txnTraceService field and pipeline admission state to service struct

• Adds a txnTraceService field and extends the pipelines struct with a WaitGroup, mutex, closing flag, cancel map, and a test hook (beforeAdmission) for admission control.

pkg/cnservice/types.go

server.goAdd cancelable message caches with cross-handler cancel ownership +24/-6

Add cancelable message caches with cross-handler cancel ownership

• Introduces CreateCacheWithCancel allowing a cancel function to be attached to a cache; cacheWithContext now tracks multiple cancels and invokes them on close, delete, or timeout so fragment contexts are released exactly once independent of per-handler lifetime.

pkg/common/morpc/server.go

types.goExtend ClientSession interface with CreateCacheWithCancel +2/-0

Extend ClientSession interface with CreateCacheWithCancel

• Adds CreateCacheWithCancel to the ClientSession interface to transfer cancel ownership to the cache.

pkg/common/morpc/types.go

runtime.goAdd CompareAndDeleteGlobalVariables to runtime +4/-0

Add CompareAndDeleteGlobalVariables to runtime

• Implements generation-safe removal of global variables using CompareAndDelete semantics, used for safe service rollback cleanup.

pkg/common/runtime/runtime.go

types.goDeclare CompareAndDeleteGlobalVariables on Runtime interface +3/-0

Declare CompareAndDeleteGlobalVariables on Runtime interface

• Adds the new method signature and documentation to the Runtime interface.

pkg/common/runtime/types.go

Bug fix (2) +152 / -31
server.goReturn bootstrap failures and manage full CN lifecycle ownership +148/-29

Return bootstrap failures and manage full CN lifecycle ownership

• Bootstrap runs after Start()'s operator ownership transfer and returns errors instead of panicking; adds closeBootstrapService/closeIncrService/closeTxnTraceService for generation-safe rollback via CompareAndDeleteGlobalVariables; adds pipeline admission gating (admitPipelineHandler/closePipelineAdmission/waitPipelineHandlers) with per-request cancel tracking, and updates handleRequest/handleWaitingNextMsg to transfer cancel ownership to fragment caches exactly once.

pkg/cnservice/server.go

server.goClose SQL listeners even when MOServer.Start() was never called +4/-2

Close SQL listeners even when MOServer.Start() was never called

• MOServer.Stop() now closes any constructor-opened listeners regardless of the running flag, preventing leaked listeners on early rollback.

pkg/frontend/server.go

Tests (13) +690 / -25
server_bootstrap_test.goUpdate handleBootstrapErr tests to expect returned errors, not panics +36/-20

Update handleBootstrapErr tests to expect returned errors, not panics

• Rewrites test cases so DeadlineExceeded, timeout, generic, moerr-wrapped, and connection-reset errors are returned rather than causing a panic.

pkg/cnservice/server_bootstrap_test.go

server_test.goAdd extensive lifecycle tests for bootstrap rollback, trace draining, and pipeline cancellation +495/-5

Add extensive lifecycle tests for bootstrap rollback, trace draining, and pipeline cancellation

• Adds tests for bootstrap failure rollback, trace-service close ordering relative to pipeline producers, real RPC pipeline admission rejection during close, fragmented pipeline cache survival across cleanup scans, pipeline cancellation on Close, and single-cancellation guarantees for rejected/early-return requests.

pkg/cnservice/server_test.go

method_based_test.goImplement CreateCacheWithCancel on test client session mock +3/-0

Implement CreateCacheWithCancel on test client session mock

• Adds a no-op CreateCacheWithCancel stub to satisfy the extended ClientSession interface.

pkg/common/morpc/method_based_test.go

types_mock.goRegenerate mock for new CreateCacheWithCancel method +15/-0

Regenerate mock for new CreateCacheWithCancel method

• Adds generated mock implementation and recorder for ClientSession.CreateCacheWithCancel.

pkg/common/morpc/mock_morpc/types_mock.go

server_test.goAdd tests for cancelable message cache lifecycle +67/-0

Add tests for cancelable message cache lifecycle

• Adds TestCancelableMessageCacheLifecycle covering cancel invocation on delete, session close, multiple fragments, and request timeout scenarios.

pkg/common/morpc/server_test.go

runtime_test.goTest CompareAndDeleteGlobalVariables behavior +4/-0

Test CompareAndDeleteGlobalVariables behavior

• Adds assertions verifying CompareAndDeleteGlobalVariables only removes matching values.

pkg/common/runtime/runtime_test.go

server_test.goTest listener release when MOServer stops before starting +31/-0

Test listener release when MOServer stops before starting

• Adds TestMOServerStopBeforeStartReleasesListener verifying the listening port is freed even without a prior Start() call.

pkg/frontend/server_test.go

rpc_test.goImplement CreateCacheWithCancel stub for test client session +3/-0

Implement CreateCacheWithCancel stub for test client session

• Adds a no-op implementation to satisfy the updated ClientSession interface.

pkg/lockservice/rpc_test.go

types2_test.goImplement CreateCacheWithCancel stub for mock client session +3/-0

Implement CreateCacheWithCancel stub for mock client session

• Adds a no-op implementation to satisfy the updated ClientSession interface.

pkg/sql/colexec/types2_test.go

server_test.goImplement CreateCacheWithCancel stub for test client session +6/-0

Implement CreateCacheWithCancel stub for test client session

• Adds a panicking stub matching other unimplemented methods to satisfy the interface.

pkg/txn/rpc/server_test.go

session_test.goImplement CreateCacheWithCancel stubs for logtail test streams +21/-0

Implement CreateCacheWithCancel stubs for logtail test streams

• Adds panicking stubs on blockStream, brokenStream, and normalStream to satisfy the updated interface.

pkg/vm/engine/tae/logtail/service/session_test.go

test_fixture_test.goImplement CreateCacheWithCancel stub for capture session fixture +3/-0

Implement CreateCacheWithCancel stub for capture session fixture

• Adds a panicking stub to satisfy the updated ClientSession interface.

pkg/vm/engine/tae/logtail/service/test_fixture_test.go

logtailserver.goImplement CreateCacheWithCancel stub for logtail test client session +3/-0

Implement CreateCacheWithCancel stub for logtail test client session

• Adds a no-op implementation to satisfy the updated ClientSession interface.

pkg/vm/engine/test/testutil/logtailserver.go

@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Cancel executed under mutex 🐞 Bug ☼ Reliability
Description
cacheWithContext.close() now executes transferred context.CancelFunc callbacks, but it is called
while holding clientSession's cs.mu (e.g., in DeleteCache, Close, and timeout cleanup). If
any cancel func blocks or re-enters ClientSession methods, cache deletion/timeout cleanup/session
close can stall or deadlock for that session.
Code

pkg/common/morpc/server.go[R1005-1009]

+func (c cacheWithContext) close() {
+	c.cache.Close()
+	for _, cancel := range c.cancels {
+		cancel()
+	}
Evidence
The code shows cacheWithContext.close() executing cancel callbacks, and multiple callers invoking
it while holding cs.mu, making cancel execution occur inside the session critical section.

pkg/common/morpc/server.go[684-709]
pkg/common/morpc/server.go[835-855]
pkg/common/morpc/server.go[969-983]
pkg/common/morpc/server.go[999-1010]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`cacheWithContext.close()` calls all stored `context.CancelFunc`s. Today it is invoked while holding `clientSession.mu` in multiple paths (`DeleteCache`, `Close`, and `checkCacheTimeout`). Because the API accepts an arbitrary `context.CancelFunc`, executing them inside `cs.mu` can stall cache operations or deadlock if a cancel func (or cancellation-triggered cleanup) blocks or re-enters session methods.

### Issue Context
This PR introduced `CreateCacheWithCancel` and added `cacheWithContext.cancels`, then changed cache cleanup sites to call `c.close()`.

### Fix Focus Areas
Refactor cache removal so that **map mutation happens under `cs.mu`**, but **`cache.Close()` and cancel callbacks run after releasing `cs.mu`**.

- pkg/common/morpc/server.go[684-709]
- pkg/common/morpc/server.go[835-855]
- pkg/common/morpc/server.go[969-983]
- pkg/common/morpc/server.go[999-1010]

### Suggested approach
1. In `DeleteCache` / `Close` / timeout cleanup:
  - under `cs.mu`, fetch `cacheWithContext` and delete the map entry (and adjust metrics).
  - release `cs.mu`.
  - then close the cache and invoke the collected cancels.
2. Optionally split `cacheWithContext.close()` into two methods, e.g. `closeCache()` and `runCancels()` / or `detachCancels()` to make it harder to accidentally run cancels under locks.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

Comment thread pkg/common/morpc/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 review on 53de8f3c39f20da8d23f0549e6e808dc530bcbe9 found two lifecycle blockers.\n\n1. Bootstrap is retired while frontend consumers are still live. service.Close invokes closeBootstrapService before stopFrontend, and closeBootstrapService sets s.bootstrapService = nil before calling Close. At the same time active/new frontend sessions call GetFinalVersion, CheckTenantUpgrade, and UpgradeTenant through BaseService, all of which dereference s.bootstrapService without synchronization. A concrete shutdown interleaving is: Close stores nil -> an authentication/upgrade request enters before the SQL listener/session is stopped -> GetFinalVersion invokes a method on the nil interface and panics (and the field read/write is itself a race). Simply moving the step may still be insufficient if frontend stop closes sessions without joining their handlers; the bootstrap generation must remain stable until every consumer is drained, or access/retirement must be synchronized. Please add a deterministic barrier-based close-vs-upgrade/auth regression.\n\n2. The new returned Start error is not cleanup-safe for all CN owners. The embedded operator now transfers ownership before Start, but pkg/tests/service.(*cnService).Start leaves status as ServiceInitialized on error while its Close only closes ServiceStarted. Therefore the exact bootstrap reset now returned by this PR leaves the constructor-opened SQL listener plus bootstrap-created incr/trace services and clients alive; a later cluster Close is a no-op for that CN. cmd/mo-service.startCNService also panics on s.Start() without first closing the constructed service. Please close the ownership loop for every direct cnservice.NewService caller (or make failed Start transactionally roll itself back), and test failure -> cleanup -> SQL address reuse/runtime globals removed.\n\nThe MORPC cache callback-outside-lock change and pipeline closing + WaitGroup admission boundary look correct; focused CN/MORPC lifecycle tests passed under race locally. While adding the missing regressions, please replace the 2.2s sleep in TestFragmentedPipelineCacheSurvivesHandlerRelease with an observable scan/barrier: elapsed time does not prove that either cleanup scan actually ran under CI scheduling.

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

One lifecycle blocker remains at service.Start / service.Close:

Start rolls a failed attempt back through s.Close(), which permanently consumes closeOnce, but Start has no state/admission guard. A caller that retries the now-returned bootstrap error creates and publishes a new auto-increment service and txn-trace service; when that second attempt fails, the deferred Close is a no-op, so the new goroutines/runtime globals remain live and every later Close is also unable to reclaim them. The Service interface does not document a single-call-only contract or reject a start on a closed instance. The same missing state boundary also permits teardown and publication to overlap if Start and Close race.

I reproduced the sequential case on exact head ac5a2b391f2a1c1653c066d0e4cb69735858b5a6 with a real Start -> bootstrap error -> Start -> bootstrap error counterexample: runtime.AutoIncrementService was still present after the second return (the test failed in 0.05s). Please add an explicit one-shot lifecycle state gate (or make retries transactionally safe), and keep this counterexample as a deterministic regression test.

The previous listener/global cleanup, bootstrap-consumer synchronization, fragmented-cache ownership, cancellation-outside-lock, and trace-producer ordering issues are otherwise closed. The new targeted CN/MORPC/frontend/runtime tests pass locally under -race, and all current CI checks are green.

@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-review completed on af1b2f8. The previous lifecycle blockers are resolved and I found no new merge blocker.

The one-shot Start/Close state gate now makes failed startup cleanup terminal and rejects reuse after close; bootstrap consumers remain protected until retirement; pipeline admission, cancellation, handler draining, trace shutdown, and fragmented-message cancel ownership form a complete shutdown closure. Runtime cleanup is generation-safe through CompareAndDelete, and retained handler/cache state is bounded and reclaimed on completion, timeout, or session close.

Fresh local validation passed: adaptive focused race stress for all changed lifecycle transitions, Test_TxnExecutorExec under race with count=2, full race runs for cnservice, morpc, frontend, runtime, and txnexecutor, plus build and vet for the production packages.

@mergify

mergify Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-02 13:45 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-08-02 13:45 UTC · at af1b2f809955c01eed0abc7ab1103dac87ca3ec4 · 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 Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • 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

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 size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants