Skip to content

fix: make backend creation cancellable and bound resolution callbacks - #26914

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-26474-lifecycle
Aug 10, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-26474-lifecycle

Conversation

@XuPeng-SH

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:

Fixes #26474

What this PR does / why we need it:

This closes the two lifecycle gaps deliberately left after #26473.

Contextual backend creation

  • Adds the backward-compatible ContextBackendFactory capability. Existing BackendFactory implementations continue to work; clients prefer contextual creation when supported.
  • Binds every asynchronous create state to its exact client generation and GC-manager incarnation. Client close, targeted/full reset, queue invalidation, and manager replacement cancel that state.
  • Makes the Goetty factory contextual without allowing cancellation to bypass the process-wide concurrency bound: shared workers and lower-level legacy Connect attempts are both capped at four. A cancelled late result retains ownership and is closed before it can escape.
  • Keeps local lifecycle cancellation out of factoryErr, error logs, and peer-breaker evidence. A factory timeout while the generation remains live is still preserved as definitive failure evidence.

Unknown-commit callbacks

  • Defines completion callbacks as prompt, non-blocking external code that may re-enter Close.
  • Reserves callback capacity when ownership transfers and caps accepted-but-not-returned callbacks at 1024. There is no unbounded callback queue or detached-goroutine fan-out.
  • Saturation returns an error before callback ownership transfers, while lock-cleanup ownership is still scheduled so locks are not stranded.
  • Service shutdown seals callback admission, joins the resolver, drains pending callback reservations by transferring invocation out of service ownership, and only then releases the RPC transport. Close never waits on a callback body that may itself call Close.
  • Rolls back callback ownership if resolver task startup fails, preventing double admission release on the caller error path.

Validation

Based on origin/main@fa0ea95aa77.

  • go vet -mod=readonly ./pkg/common/morpc ./pkg/lockservice
  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=15m ./pkg/common/morpc ./pkg/lockservice
  • .agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=15m ./pkg/common/morpc ./pkg/lockservice
  • Each of the 10 new lifecycle regressions measured individually under race (T=0s..0.06s, stress budget B=30s, adaptive N=100) and then passed separately with exact -run, -race, and -count=100.

The local Darwin linker emitted only the pre-existing missing /opt/homebrew/opt/libpqxx/lib/ search-path warning; every command exited successfully.

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

Conclusion: REQUEST_CHANGES. The PR author and the authenticated reviewer are both XuPeng-SH, so GitHub does not allow this account to set the formal Request changes state; this is recorded as a COMMENTED review instead.

  1. [P1] Keep ownership of a successful backend when cancellation wins the outer select

    In boundedBackendCreate, the worker checks ctx.Err() before putting the result into a buffered channel. Cancellation can happen after that check (including after the buffered send) and the caller can then select ctx.Done() and return without receiving the result. The worker releases slots and exits, but nobody closes the successful backend left in resultC. A real remoteBackend owns a connection and stopper goroutines, so repeated reset/close races can leak sockets and goroutines without retaining the intended global bound. The existing late-result test cancels before create() returns, so the worker itself observes cancellation and does not cover this ownership-transfer window. Use an explicit receiver/worker ownership handshake (for example an unbuffered result transfer whose worker also selects ctx.Done() and closes on failed transfer), and add a deterministic regression for cancellation after successful creation but before transfer.

  2. [P1] Do not release unresolved-commit backpressure on callback saturation

    When callback admission fails, enqueue still inserts the transaction into pending without a callback and returns the capacity error. The production caller handles every error by immediately calling releaseInternalUnknownCommitAdmission, which releases the user/internal transaction admission that is documented to remain held until terminal lock cleanup. During an allocator outage, the first 1024 unresolved transactions fill the callback slots; every later unknown Commit is retained in pending/activeTxnHolder but frees its admission, so subsequent transactions can keep adding pending entries and locks without a bound. This moves the overload from callback goroutines to unbounded resolver/lock state and defeats the fail-safe branch. Saturation needs to preserve an independent bounded cleanup/admission owner until resolution (or reject before cleanup ownership transfers with a caller path that continues to retain the admission). Add an outage test that keeps resolution pending beyond capacity and proves both pending state and transaction admission remain bounded.

Validation on exact head debc6eccd78b vs base ff25f27397ab: all 10 new tests were enumerated, measured under race (T=0–0.06s, B=30s, N=100), and passed individually with -race -count=100; full ./pkg/common/morpc and ./pkg/lockservice race runs passed (16.385s / 109.166s), go vet passed, and git diff --check passed. These findings are uncovered semantic interleavings, not race-detector failures.

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

[P1] Cancellation can leak a successfully created backend during result handoff.\n\nboundedBackendCreate uses a buffered result channel. A concrete interleaving is: create returns a Backend; the producer observes ctx.Err() == nil; cancellation happens and the outer select returns through ctx.Done(); then the producer sends the Backend into the buffered channel and exits. No receiver or cleanup owner remains, so Backend.Close is never called. Repeated reset/close races can leak connections and transport goroutines without bound. Please use an explicit ownership handoff, such as an unbuffered result send whose cancellation branch closes the Backend, so either the consumer receives ownership or the producer destroys it.\n\n[P2] A duplicate pending transaction silently loses the new completion callback.\n\nWhen an existing pending txn already has onResolved, enqueue retains the old callback, ignores the callback supplied by the new call, and still returns nil. The new API contract says a nil return transfers callback ownership, but this callback is neither reserved nor invoked. A caller relying on it to release admission can remain held indefinitely. Please either reject an additional callback before ownership transfers, or retain all accepted callbacks under the configured bound and invoke each exactly once.

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

@aptend Addressed both findings in 86329a1.

  1. Backend handoff now uses an unbuffered ownership rendezvous. If cancellation wins before transfer, the producer closes the successful Backend before releasing the shared slot; if transfer wins, the receiver is the sole owner and rechecks cancellation. A deterministic regression covers both ownership outcomes.
  2. A duplicate callback is no longer silently accepted. Capacity/sealed admission failures and duplicate registration now return a typed scheduled-resolution error carrying the shared terminal signal. The caller retains its callback and txn admission until that signal closes; normal resolution, removal, and service Close all publish the signal exactly once. The txn client handles this protocol for both user and internal admissions.

The same pass also made resolver-task startup atomic with pending-state publication, so RunTask failure restores the exact prior state and releases any provisional callback reservation.

Re-reviewed complete PR diff at head 86329a1 against base ff25f27. No remaining correctness, lifecycle, boundedness, or steady-state performance blocker found. Normal RPC/txn paths are unchanged; added allocations/waiters occur only on unknown-commit or backend-creation lifecycle paths.

Validation: all 15 changed lifecycle tests were enumerated; race duration T=0-0.12s with B=30s gave N=100, and every test passed separately with exact -run/-race/-count=100. Full package race passed for morpc (16.354s), lockservice (110.321s), and txn/client (12.787s). Targeted build, vet, and git diff --check passed. This account is also the PR author, so the clean result is submitted as COMMENTED rather than APPROVED.

@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/L Denotes a PR that changes [500,999] lines labels Aug 10, 2026
@XuPeng-SH
XuPeng-SH requested a review from aptend August 10, 2026 12:06

@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 independent re-review of exact head 86329a1: no remaining code-level blocker found. GitHub does not allow the PR author to approve their own PR, so this is submitted as COMMENTED rather than APPROVED.

The still-visible formal CHANGES_REQUESTED review is aptend on old head debc6ec. Both findings are closed on the current head:

  1. Backend result ownership now linearizes at an unbuffered rendezvous. If cancellation wins before transfer, the producer closes the successful Backend before releasing the shared slot. If transfer wins, the receiver is the sole owner and rechecks cancellation before returning. Client close, targeted/full reset, and GC-manager stop cancel the exact create-state generation. Lower-level legacy goetty attempts retain their late result and remain process-wide bounded at four.
  2. Duplicate and saturated unknown-commit callbacks are no longer silently accepted. The typed scheduled-resolution error retains callback ownership at the caller and carries a shared terminal signal. The txn client keeps the existing user/internal transaction admission until that signal closes, then invokes its retained callback exactly once. Normal resolution, active-txn disappearance, resolver removal, and service Close all complete the signal. Accepted callback bodies hold one of 1024 reservations until return and execute outside the resolver/Close wait graph, so callback re-entry into Close does not form a cycle.

Q1/Q2/Q3 closure:

  • Q1: backend, create-state, callback-slot, resolution-signal, lock-cleanup, and txn-admission ownership each have one terminal owner on success, cancellation, saturation, duplicate registration, task-start failure, and shutdown.
  • Q2: client/reset/manager cancellation terminates contextual factory workers; lower-level goetty attempts remain bounded and own late cleanup. Resolver RPC/unlock attempts have deadlines, service Close cancels and joins resolver work, and Close never waits on external callback bodies.
  • Q3: backend workers and lower-level attempts are capped at four, create queues/generation maps are bounded, callbacks are capped at 1024, and overflow resolution remains covered by production user admission plus the independent 1024 internal-unknown-commit admission.

Performance: the Send and ordinary Commit hot paths are unchanged. Context allocation, one bounded goroutine/rendezvous, and slot acquisition occur only during backend creation and are dominated by connection I/O. Resolution channels, callback reservations, and waiter goroutines occur only on unknown Commit. No unbounded logging or metric cardinality was added.

Compatibility: ContextBackendFactory is an optional additive capability; legacy BackendFactory implementations keep working. UnknownCommitResolutionScheduledError is additive and unwrap-aware. There is no SQL, wire, catalog, checkpoint, or on-disk format change. The asynchronous completion behavior is explicitly documented for the exceptional unknown-commit API and its only production caller is updated.

Fresh local validation on this exact head:

  • all 15 changed lifecycle tests were enumerated;
  • measured race T=0-0.12s with B=30s gave N=100, and every exact test passed separately with race count=100;
  • full morpc, lockservice, and txn/client owning packages passed normal and race;
  • targeted build, vet, and git diff check passed.

No CI status was used as a substitute for the code and lifecycle review. The remaining merge gate is for the external reviewer to re-review or dismiss the stale old-head CHANGES_REQUESTED state.

@iamlinjunhong iamlinjunhong 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 86329a108bed against merge-base ff25f27397ab. No P0/P1/P2/P3 findings remain.

The old-head backend handoff and unknown-commit callback findings are closed on the current head: backend ownership linearizes at the unbuffered rendezvous, and callback saturation/duplication retains caller ownership plus bounded txn admission until the shared terminal signal completes.

Validation on the exact head:

  • all 15 changed lifecycle tests passed individually with -race -count=100;
  • full pkg/common/morpc, pkg/lockservice, and pkg/txn/client race runs passed;
  • targeted build, vet, and git diff --check passed.

One initial full morpc race run hit the unrelated timing test TestReadTimeoutWithNormalMessageMissed; it passed 20 exact race repetitions and the next full race run, while the merge-base full race run also passed. It was not reproducible and is not retained as a PR finding. The controlled CGo wrapper could not start because the isolated worktree has no generated libmo.dylib/thirdparty artifacts, so local tests used the same CGO_ENABLED=1 toolchain directly; GitHub CI is fully complete.

@XuPeng-SH
XuPeng-SH merged commit 5a753ba into matrixorigin:main Aug 10, 2026
18 of 23 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/issue-26474-lifecycle branch August 10, 2026 13:39
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…matrixorigin#26914)

## What type of PR is this?

- [x] API-change
- [x] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Fixes matrixorigin#26474

## What this PR does / why we need it:

This closes the two lifecycle gaps deliberately left after matrixorigin#26473.

### Contextual backend creation

- Adds the backward-compatible `ContextBackendFactory` capability.
Existing `BackendFactory` implementations continue to work; clients
prefer contextual creation when supported.
- Binds every asynchronous create state to its exact client generation
and GC-manager incarnation. Client close, targeted/full reset, queue
invalidation, and manager replacement cancel that state.
- Makes the Goetty factory contextual without allowing cancellation to
bypass the process-wide concurrency bound: shared workers and
lower-level legacy Connect attempts are both capped at four. A cancelled
late result retains ownership and is closed before it can escape.
- Keeps local lifecycle cancellation out of `factoryErr`, error logs,
and peer-breaker evidence. A factory timeout while the generation
remains live is still preserved as definitive failure evidence.

### Unknown-commit callbacks

- Defines completion callbacks as prompt, non-blocking external code
that may re-enter `Close`.
- Reserves callback capacity when ownership transfers and caps
accepted-but-not-returned callbacks at 1024. There is no unbounded
callback queue or detached-goroutine fan-out.
- Saturation returns an error before callback ownership transfers, while
lock-cleanup ownership is still scheduled so locks are not stranded.
- Service shutdown seals callback admission, joins the resolver, drains
pending callback reservations by transferring invocation out of service
ownership, and only then releases the RPC transport. `Close` never waits
on a callback body that may itself call `Close`.
- Rolls back callback ownership if resolver task startup fails,
preventing double admission release on the caller error path.

### Validation

Based on `origin/main@fa0ea95`.

- `go vet -mod=readonly ./pkg/common/morpc ./pkg/lockservice`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=15m
./pkg/common/morpc ./pkg/lockservice`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=15m
./pkg/common/morpc ./pkg/lockservice`
- Each of the 10 new lifecycle regressions measured individually under
race (`T=0s..0.06s`, stress budget `B=30s`, adaptive `N=100`) and then
passed separately with exact `-run`, `-race`, and `-count=100`.

The local Darwin linker emitted only the pre-existing missing
`/opt/homebrew/opt/libpqxx/lib/` search-path warning; every command
exited successfully.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…matrixorigin#26914)

## What type of PR is this?

- [x] API-change
- [x] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Fixes matrixorigin#26474

## What this PR does / why we need it:

This closes the two lifecycle gaps deliberately left after matrixorigin#26473.

### Contextual backend creation

- Adds the backward-compatible `ContextBackendFactory` capability.
Existing `BackendFactory` implementations continue to work; clients
prefer contextual creation when supported.
- Binds every asynchronous create state to its exact client generation
and GC-manager incarnation. Client close, targeted/full reset, queue
invalidation, and manager replacement cancel that state.
- Makes the Goetty factory contextual without allowing cancellation to
bypass the process-wide concurrency bound: shared workers and
lower-level legacy Connect attempts are both capped at four. A cancelled
late result retains ownership and is closed before it can escape.
- Keeps local lifecycle cancellation out of `factoryErr`, error logs,
and peer-breaker evidence. A factory timeout while the generation
remains live is still preserved as definitive failure evidence.

### Unknown-commit callbacks

- Defines completion callbacks as prompt, non-blocking external code
that may re-enter `Close`.
- Reserves callback capacity when ownership transfers and caps
accepted-but-not-returned callbacks at 1024. There is no unbounded
callback queue or detached-goroutine fan-out.
- Saturation returns an error before callback ownership transfers, while
lock-cleanup ownership is still scheduled so locks are not stranded.
- Service shutdown seals callback admission, joins the resolver, drains
pending callback reservations by transferring invocation out of service
ownership, and only then releases the RPC transport. `Close` never waits
on a callback body that may itself call `Close`.
- Rolls back callback ownership if resolver task startup fails,
preventing double admission release on the caller error path.

### Validation

Based on `origin/main@fa0ea95`.

- `go vet -mod=readonly ./pkg/common/morpc ./pkg/lockservice`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=15m
./pkg/common/morpc ./pkg/lockservice`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=15m
./pkg/common/morpc ./pkg/lockservice`
- Each of the 10 new lifecycle regressions measured individually under
race (`T=0s..0.06s`, stress budget `B=30s`, adaptive `N=100`) and then
passed separately with exact `-run`, `-race`, and `-count=100`.

The local Darwin linker emitted only the pre-existing missing
`/opt/homebrew/opt/libpqxx/lib/` search-path warning; every command
exited successfully.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…matrixorigin#26914)

## What type of PR is this?

- [x] API-change
- [x] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Fixes matrixorigin#26474

## What this PR does / why we need it:

This closes the two lifecycle gaps deliberately left after matrixorigin#26473.

### Contextual backend creation

- Adds the backward-compatible `ContextBackendFactory` capability.
Existing `BackendFactory` implementations continue to work; clients
prefer contextual creation when supported.
- Binds every asynchronous create state to its exact client generation
and GC-manager incarnation. Client close, targeted/full reset, queue
invalidation, and manager replacement cancel that state.
- Makes the Goetty factory contextual without allowing cancellation to
bypass the process-wide concurrency bound: shared workers and
lower-level legacy Connect attempts are both capped at four. A cancelled
late result retains ownership and is closed before it can escape.
- Keeps local lifecycle cancellation out of `factoryErr`, error logs,
and peer-breaker evidence. A factory timeout while the generation
remains live is still preserved as definitive failure evidence.

### Unknown-commit callbacks

- Defines completion callbacks as prompt, non-blocking external code
that may re-enter `Close`.
- Reserves callback capacity when ownership transfers and caps
accepted-but-not-returned callbacks at 1024. There is no unbounded
callback queue or detached-goroutine fan-out.
- Saturation returns an error before callback ownership transfers, while
lock-cleanup ownership is still scheduled so locks are not stranded.
- Service shutdown seals callback admission, joins the resolver, drains
pending callback reservations by transferring invocation out of service
ownership, and only then releases the RPC transport. `Close` never waits
on a callback body that may itself call `Close`.
- Rolls back callback ownership if resolver task startup fails,
preventing double admission release on the caller error path.

### Validation

Based on `origin/main@fa0ea95`.

- `go vet -mod=readonly ./pkg/common/morpc ./pkg/lockservice`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=15m
./pkg/common/morpc ./pkg/lockservice`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=15m
./pkg/common/morpc ./pkg/lockservice`
- Each of the 10 new lifecycle regressions measured individually under
race (`T=0s..0.06s`, stress budget `B=30s`, adaptive `N=100`) and then
passed separately with exact `-run`, `-race`, and `-count=100`.

The local Darwin linker emitted only the pre-existing missing
`/opt/homebrew/opt/libpqxx/lib/` search-path warning; every command
exited successfully.

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/api-change kind/bug Something isn't working kind/enhancement kind/test-ci size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Follow-up]: make MORPC factory creation cancellable and bound lockservice completion callbacks

4 participants