Skip to content

fix(shardservice): close owned RPC server and clean test fixtures - #29708

Merged
XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-shard-fixture-lifecycle
Oct 8, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-shard-fixture-lifecycle

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Test and CI

Which issue(s) this PR fixes:

Fixes #29709

Fixes the pkg/shardservice/TestRead listener leak reported by PR #29694's coverage job.

What this PR does / why we need it:

NewService starts an RPC server, but Close only closed the RPC client. A real socket probe against the failing CI revision confirms that the closed service still accepts connections. Close both owned endpoints and preserve both errors, including when server shutdown fails.

The shared test fixture invoked its leak check immediately at entry and released services only after a successful callback. Defer the leak check until teardown; register independent cleanup as each cluster, server, storage timestamp waiter, and CN service is acquired. Assertion failures, callback panic, partial fixture setup, and close errors no longer bypass remaining cleanup. Storage and cluster resources remain owned by the fixture.

Regression tests prove that a live socket is disconnected and refuses new connections after shutdown, and that both RPC endpoints are closed when either or both return an error. No new state machine, public API, or hot-path work is added.

Validation (Go 1.27.1, Linux/amd64, repository CGo wrapper):

  • Owning pkg/shardservice package: normal and race pass, 75 tests/subcases each.
  • Owning package in CI's short / matrixone_test / set-coverage mode passes; instrumentation covers shardservice, morpc, txn/client, and clusterservice.
  • Exact TestRead: race ×15; TestServiceCloseListener: race ×100, using the repository's bounded adaptive repetition budget.
  • Real fixture probes confirm teardown after callback panic, partial setup, t.Fatal, and an injected server close error. Removing server shutdown makes the new regression fail locally with listener leaks and an open connection, rather than a process timeout.
  • Incremental gofmt, vet, molint, and configured golangci-lint pass (0 new issues).

Related: #29676 also closes this server as part of a broader constructor ownership change. This PR is a focused, independently mergeable correction; it does not take on that constructor/API refactor.

New PR CI has not yet run. SQL BVT is not applicable: this change restores component teardown without changing SQL or wire 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 →

@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 — no blocking findings

Code-review recommendation: APPROVE at b293226b8f20878c3ac8a7cb826d8548d7fc4a88. This is submitted as COMMENT, not APPROVE, because the authenticated account is also the PR author. It does not satisfy an independent GitHub approval requirement.

Reviewed both changed files and every hunk against verified main/merge-base f6c86c9c0452db27af1b0c9aceff1aa5b96aabad, including #29709, PR discussion and all review threads. No subagents, production edits, push, or CI wait.

Design and scope

This is an ordinary focused lifecycle repair, exempt from a separate feature-design document. The resource owner was already correct at construction: shardservice creates both RPC endpoints. Its destructor simply failed to release one of them. Calling the existing server/client Close operations and aggregating errors closes that ownership gap without a new state machine, retry, storage path, API or hot-path branch.

I traced NewService/initRemote → service.Close → method-based MORPC Close → RPC stopper/Goetty StopAndWait, and the CN shutdown caller. The new server shutdown closes listeners and disconnects/joins the transport connections using the existing owner. Both endpoint Close calls are evaluated even when the first returns an error; errors.Is retains each error.

The fixture retains ownership of the shared cluster, shard coordinator and test storage waiter. Those resources are not incorrectly moved into the production service destructor. Its independent defers unwind in the useful order: callback context → CN service then its waiter (reverse acquisition order) → coordinator → cluster → leak check. Earlier acquired resources are released when later setup or the callback fails; one assertion about a close error cannot skip the other registered cleanup.

Closure Risk / audit result
Owned server and client teardown R3 / Q1-Q2: existing destruction and transport termination paths reused; no new competing cleanup owner or wait cycle found.
Shared fixture acquisition/unwind/next generation R3 / Q1-Q3: cleanup registered as resources become available; waiter/background resources terminate; independent same-process reuse verified.
Error aggregation and regression oracles R1/R2: success, either endpoint error, both errors and exactly-once calls covered; real socket oracle complements mocked error injection.

This does not claim to redesign constructor-internal failure rollback or concurrent/idempotent service Close. Those are unchanged contracts, and the broader constructor work referenced in #29676 is not silently imported. The one-line endpoint fix overlaps that PR, but introduces no duplicate runtime mechanism.

Engineering, performance and tests

  • Production delta: +1/-1; tests: +88/-7; documents/generated artifacts: 0. The increments were assessed separately.
  • No added SQL execution work, allocations on a query path, persistent format, wire or tenant-boundary change. The additional shutdown work is the release that ownership already required.
  • The real listener test reuses the existing fixture, proves connection termination and refusal of new work, and uses bounded I/O rather than sleep/retry synchronization.
  • The four-cell close-error test proves a different contract and is not redundant with the socket test. The small interface fakes are proportionate.
  • The new listener test was below the Go test event's 0.01-second resolution in the normal and single race runs; its 100-repeat race command completed in 2.242 seconds including process overhead. No material fixture-cost increase was observed. This is not a throughput benchmark or a claimed paired whole-package speedup.
  • SQL BVT/upgrade testing is not required for this component-only teardown repair; no SQL or persisted-data behavior changes.

Independently executed QA

Exact head, Go 1.27.1, Darwin/arm64, fresh worktree-native build and repository CGo wrapper:

Check Result
Focused TestRead + TestServiceCloseListener + TestServiceCloseErrors PASS, exit 0
Complete owning package, normal, count=1 75 tests/subcases PASS, 42.446s, exit 0
Complete owning package, race, count=1, plus review-only fixture probes 78 tests/subcases PASS, 46.572s, exit 0; no detected race
Exact TestRead, race, count=29 29/29 PASS, exit 0
Exact TestServiceCloseListener, race, count=100 100/100 PASS, exit 0
gofmt on both changed files; PR-range diff check PASS

The repeat counts follow the adaptive rule: TestRead measured 1.02s in the first race run, so floor(30/1.02)=29; the listener duration was below resolution, so 100. Actual repeated TestRead execution varied and the command took 56.457s; I did not repeat-stress the whole package.

The review-only whitebox probes inject a callback panic and an interruption during second-CN setup, then verify:

  1. previously created CN and coordinator sockets refuse new connections;
  2. service stoppers reject new tasks;
  3. storage timestamp waiters return ClientClosed, rather than just timing out;
  4. another fixture generation works in the same process.
    Both probes pass normally and under race. They use real constructors and the actual shared fixture, and were injected via a temporary Go overlay, not committed into production.

Negative control: overlaying only the verified base's service.go into the otherwise unchanged test tree makes all four TestServiceCloseErrors cells fail: the server is not closed / its error is lost. Restoring the candidate implementation passes. This establishes that the regression oracle detects the original production defect.

Author-reported Linux/amd64 short/matrixone_test/set-coverage and incremental vet/molint/golangci evidence is retained as author evidence, not relabelled as my local execution. The merge from e2a0db8 to this head changed only three unrelated connection-encoding design/oracle files, so it did not invalidate that lifecycle evidence.

Comments and decision

There are no substantive historical review comments or unresolved review threads on this PR at this head; the sole issue comment is the Qodo service notice. There are no known review findings being blanket-marked resolved.

No blocking correctness, lifecycle, performance or engineering-quality issue found within this PR's contract. No demand for a wider cleanup framework, repeated full-suite validation, mixed-version rolling upgrade, or unrelated refactor. CI was still running when checked; this review is not a claim that CI or independent approval has completed.

Follow-up: incremental SCA and fresh UT race — 2026-10-08

Verified the PR head remains b293226b8f20878c3ac8a7cb826d8548d7fc4a88. Derived changed package from the two-file delta against f6c86c9c0452db27af1b0c9aceff1aa5b96aabad: ./pkg/shardservice.

Independently executed gofmt, go vet -mod=readonly, the repository-pinned molint via vettool, and golangci-lint v2.14.0 with .golangci.yml --new-from-rev f6c86c9c0452db27af1b0c9aceff1aa5b96aabad ./pkg/shardservice: all exit 0; golangci-lint reports 0 issues. Lint tools use Go 1.27 builds; target analysis uses Go 1.27.1 and this worktree's controlled CGo headers/libraries.

Fresh repository-wrapper run -race -count=1 -timeout=180s -json ./pkg/shardservice, with no review overlay: 75 tests/subcases PASS, 0 failures, 44.166s, exit 0, no detected race. Prior TestRead race ×29 and listener race ×100 remain valid for this unchanged head. The default local lint binaries had an obsolete Go version/native loader problem; compatible pinned tools completed the checks. No production edits were required.

XuPeng-SH pushed a commit that referenced this pull request Oct 10, 2026
## What type of PR is this?

- [x] Improvement

## Which issue(s) this PR fixes:

Related to #29205 (partial optimization; does not close the issue).

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

M1 reuses the posting-directory offset already returned by the loaded
FST prefix iterator, avoiding a second exact-key FST lookup. It retains
dictionary traversal order, positional merging, the dense-prefix bitset,
MAX-over-expanded-term scoring, and the existing index format. No
metadata decoder, streaming search, missing-term shortcut, or BOW
algorithm change is included.

Regression coverage compares built, heap-loaded and mmap-loaded
representations, BM25/TfIdf score bits, scored/unscored prefix clauses,
mixed star/exact phrases, update/delete visibility, malformed offsets
and concurrent readers. A literal-start oracle checks mixed-phrase TF
independently. A SQL BVT adds a nonempty mixed CJK prefix phrase.

### Current-head evidence binding after upstream CI cleanup fix

Head `b8a50bd121d104061cc13e55bade0a11ef6af239` normally merges upstream
main `4942f889ef08ae26b2ebeb02a1eda11634eb83fd`, including the
shardservice listener/constructor cleanup fixes in #29708 and #29676.
The M1 FULLTEXT2 and tokenizer source is unchanged from
`4640004eae5294dc8c0964d260868edb507df1f0`; the final feature delta
remains the same six files. No independent shardservice patch or P/S
prototype was added to this PR.

Fresh native Darwin/ARM64 Go1.27.1 checks on the merged tree: full
FULLTEXT2 package with vet (319 top-level tests), full package race with
vet (318), concurrent-reader race stress (100 repetitions), and full
shardservice package with vet under short/matrixone_test/set-coverage
conditions (73) all PASS. The targeted
TestRead/TestServiceCloseListener/TestServiceCloseErrors coverage run
also PASS. The local coverage scope is four related packages, not the
all-repository Linux CI scope. Whitespace checks PASS. Required new-head
remote CI remains pending; no rerun of the known failing old head was
requested. Prior SQL BVT and v5/v6 measurements remain bound to
`b0cdac6e303f9723fed075f45040f7cbd9e8e02d` / Go1.27.0 and are reused
only for unchanged behavior, not relabeled as Go1.27.1 or current-head
binary measurements. DF172 means high-hit, not high-density mixed-phrase
coverage. No new remote experiment was run for this synchronization.

### Current-head CI disposition

[Run37911762603
attempt1](https://github.com/matrixorigin/matrixone/actions/runs/37911762603),
prior head4640004e: **FAILURE**, retained as historical evidence. The
[UT Coverage
job](https://github.com/matrixorigin/matrixone/actions/runs/37911762603/job/113758446883)
fails at `pkg/shardservice/TestRead` with a Goetty listener leak-check
failure, causing the aggregate coverage and CI Required failures.
Ordinary Ubuntu UT, shared build, SCA, executed Compose PROXY and
Pessimistic BVT jobs are SUCCESS.

Source attribution is now established: the old head starts
`remote.server` but never closes it in service.Close, while its fixture
calls leaktest.AfterTest immediately instead of deferring it. [Issue
#29709](#29709) records
the same listener leak / TestRead failure independently of M1. [PR
#29708](#29708), merged as
`ca5008de9aa1569504d593350ed92059217c85e4`, fixes endpoint cleanup and
the fixture;
[#29676](#29676) adds
construction ownership/idempotent Close. Both are present in the new
merged main. This is a known independent lifecycle defect, not a failure
declared flaky from an ARM64 pass. Fresh local tests support the repair,
but new exact-head Linux CI is still required.

New-head [MatrixOne ALL CI
run37968177551](https://github.com/matrixorigin/matrixone/actions/runs/37968177551),
head `b8a50bd121d104061cc13e55bade0a11ef6af239`: **attempt1 FAILURE;
attempt2 IN_PROGRESS; required CI is not green**. Attempt1 shared build,
Ubuntu UT Coverage, merged Coverage and both Compose PROXY/Pessimistic
BVT jobs succeeded. SCA job113947837893 and Ubuntu UT job113947837905
failed during actions/checkout with interrupted Git transport/peer
termination (UT also reports curl receive error56/early EOF), before
their analysis/test commands executed; CI Required failed its dependency
AND gate. This is a checkout/setup failure, not an SCA finding or a
product test failure. After inspecting every completed failure and
verifying the unchanged OPEN Ready exact head, only failed jobs were
retried once. Attempt2 UT job113972071978 and SCA job113972072235 are
now running; no code was changed for the retry, and no old-head run was
retried. The original run was triggered by the normal push, not manual
dispatch.

### Validation on the prior measured head b0cdac6 (reused for unchanged
behavior)

- Native macOS ARM64 CGo build with Go 1.27.0: PASS; package build and
vet: PASS.
- Full `pkg/fulltext2` tests: PASS (319 top-level tests).
- Full package race: PASS (318 top-level tests); concurrent-reader race
stress: PASS, 100 repetitions.
- `git diff --check`: PASS.
- Prefix-enumeration microbenchmark, three repetitions: allocation
108,408 -> 67,128 B/op (-38.1%); allocations 1,644 -> 1,437/op. Baseline
timing was unstable, so this is not a query-speedup claim.
- Prior b0cdac6 exact-head [CI
37757547715](https://github.com/matrixorigin/matrixone/actions/runs/37757547715):
SUCCESS, including CI Required, Ubuntu UT, shared Linux build, SCA, both
multi-CN Compose BVT jobs and coverage. This is not current-head CI. The
superseded run37743249778 failed in concurrent classic FULLTEXT snapshot
restore round2 with `context canceled`; the later success alone does not
establish its root cause.
- The changed fulltext2_cjk_boolean_prefix SQL case actually executed in
Compose BVT: 33 successful checks, zero failed/ignored/abnormal.
- Fresh Linux Go1.27.0 native build and loaded100k corpus: baseline/M1
frozen188-query TopK PK/score-bit digests match. An independently
selected nonempty mixed star/exact control has matching complete
PK/TF/score evidence. Four precheck/streaming variants also pass
loaded-index TF and BM25/TfIdf equivalence, but remain test-only and
outside this PR.

### Historical v5 controlled performance supplement (2026-10-09)

Completed continuation v5 on shared mo-55: candidate
`b0cdac6e303f9723fed075f45040f7cbd9e8e02d`, baseline
`dce60631f8c857ae730a4d2f328df5962e4f2a8d`, native Linux/amd64 Go1.27.0,
loaded100k corpus in ten10k segments, frozen188-query ngram
natural_mixed pack, search-only, C1/GOMAXPROCS4. Fixed-count
measurements, not 180-second SQL/nightly QPS. Three alternating
baseline→M1 / M1→baseline / baseline→M1 pairs; every full-pack cell
completes22,560 requests, every nonempty control cell completes10,000
requests.

| Workload | Pair | Baseline seconds | M1 seconds | Elapsed reduction |
| --- | --- | ---: | ---: | ---: |
| Complete188 pack | 1 | 41.689 | 31.554 | 24.31% |
| Complete188 pack | 2 | 66.891 | 31.302 | 53.20% — unstable baseline,
not a reliable speedup claim |
| Complete188 pack | 3 | 41.142 | 31.041 | 24.55% |
| Nonempty mixed-phrase control | 1 | 13.963 | 10.063 | 27.93% |
| Nonempty mixed-phrase control | 2 | 14.169 | 10.018 | 29.30% |
| Nonempty mixed-phrase control | 3 | 13.642 | 9.858 | 27.74% |

Go allocated bytes/request decrease25.64–25.65% for the full pack
and29.25% for the nonempty control. All28 configured cells returned
PASS; phase reached complete/exit0, final frozen hashes passed, unit
exited successfully/MainPID0, peak cgroup memory1.55GiB. Validator
checks source/input/variant/request coverage and result-count
equivalence. Earlier loaded-index PK/score-bit parity is separate
correctness evidence, not inferred from timing.

Classification: **PASS_EXPLORATORY, full-pack timing stability
INCONCLUSIVE**. Baseline full-pack spread62.58% versus M1 spread1.65%;
nonempty spreads3.86%/2.08% pass the15% stability check. During the full
run, host vmstat recorded average iowait17.8% and maximum68%. This
establishes interference risk, not the precise cause of pair2. Pair2 is
retained explicitly, not silently dropped to manufacture a stable
series. No clean-host/full SQL/nightly acceptance is claimed.

The16 factorial cells are single-pass, test-only direction probes on the
M1 head. P=missing-exact precheck; S=streaming. Empty-query gains
primarily follow P, not S alone. Nonempty and dense-prefix controls
remain nonempty across all variants. **The dense control has no
baseline-arm pair in this run, and is not the required baseline/M1
high-hit non-regression evidence.** P/S are not part of this PR and are
not approved for production by these results.

Raw evidence retained under mo-55 task root
`ft2-m1-delivery-20261008T073424Z/performance-evidence-v5`; previous
v1-v3 interrupted evidence remains separate. Sanitized detailed metrics
and identity hashes are in the accompanying PR comment.

### Measured-head CR performance supplement v6 (2026-10-09)

Fresh BC/CB/BC pairs on the same frozen baseline/candidate binaries and
original100k/ten-segment index completed18 measurement cells/255,360
requests, plus two independent full-result high-hit mixed-phrase oracle
executions. No new production commit or rebuild.

| Workload | Pair/order | Baseline s | M1 s | Elapsed reduction | Go
bytes/request reduction |
| --- | --- | ---: | ---: | ---: | ---: |
| Complete 188-query packet | 1 BC | 41.139 | 31.109 | 24.38% | 25.64% |
| Complete 188-query packet | 2 CB | 41.197 | 31.133 | 24.43% | 25.63% |
| Complete 188-query packet | 3 BC | 41.136 | 31.172 | 24.22% | 25.64% |
| High-hit star+exact mixed phrase (DF172) | 1 BC | 10.701 | 8.696 |
18.73% | 15.21% |
| High-hit star+exact mixed phrase (DF172) | 2 CB | 10.710 | 8.699 |
18.78% | 15.21% |
| High-hit star+exact mixed phrase (DF172) | 3 BC | 10.703 | 8.705 |
18.67% | 15.21% |
| Dense single-prefix / TopK100 control | 1 BC | 25.743 | 15.878 |
38.32% | 30.24% |
| Dense single-prefix / TopK100 control | 2 CB | 25.746 | 15.880 |
38.32% | 30.24% |
| Dense single-prefix / TopK100 control | 3 BC | 25.695 | 15.871 |
38.23% | 30.24% |

All groups pass the original15% stability criterion: maximum within-arm
spread0.202%. High-hit mixed phrase has live global DF172 and matching
complete baseline/M1 PK/TF/score-bit digests; both it and the paired
dense single-prefix control return TopK100 on every measured request.
Stable v5 one-hit mixed controls and unchanged exact-head CI/race/BVT
evidence are reused. The old unstable v5 pack and candidate-only
factorial controls remain historical exploratory evidence, not passing
halves of v6.

Same native Linux/amd64 Go1.27.0, ngram/natural_mixed, BM25/TopK100,
C1/GOMAXPROCS4, search-only/fixed-count/warmup contract. This is
repeatable scoped kernel performance evidence on shared mo-55, **not
exclusive-host, full230万-corpus,180-second SQL/nightly or TKE QA
acceptance**. The packet is predominantly zero-result on this subset;
independent nonempty/high-hit controls prevent presenting it as
high-density coverage.

Runtime receipts retain
active/terminal6GiB/noSwap/CPU400%/45min/stop15s/control-group limits.
Guard600 samples, no additional swap-out, all capacity floors satisfied,
zero OOM/kill/max events, task peak1.39GiB, completion/exit0,
guard/sampler joined, exact cgroup absent and retained owned unit
stopped. Frozen binaries/inputs/index verified before/after. Raw results
remain in the private v6 evidence directory; metrics, identities and
requirements are in the CR response comment.

### QA required / evidence still pending

QA required: **yes**. Loaded-index parity, real SQL BVT, repeatable v6
full-pack comparisons and actual paired high-hit mixed/single-prefix
controls are complete on measured head b0cdac6 and reused only for
unchanged behavior. Formal reviewer acceptance, new-head required CI,
current Go1.27.1 binary performance and Artifact-only TKE focused/weekly
QA remain pending. The old coverage failure has the upstream
lifecycle-fix disposition described above, not a retroactive PASS. V6
supplies the missing scoped developer performance evidence; v5's
unstable timing and incomplete dense comparison remain accurately
classified. Earlier v3 stopped below its25GiB disk floor and remains
excluded; v5 used the author's explicit20GiB disk-reserve relaxation
with all other resource/ownership gates unchanged.

The first measurement wrapper was stopped after finding a
selector-scoping defect, before dense probes ran. Its successor
regression proves all four variants retain the same dense control and
caller selector state. Original interrupted evidence is preserved. Only
this task's reproducible Go caches were reclaimed; corpus, indexes,
binaries, source and evidence remain intact.

Measured baseline is dce6063 and measured candidate is b0cdac6. The
delivery-time main snapshot1a008879 advanced only Go1.27.1 and
associated documentation, not FULLTEXT2/native code; it is historical,
not today's main. Experimental v5/v6 evidence remains frozen on those
measured binaries and Go1.27.0. The current head merges main4942f889 and
uses Go1.27.1; historical measurements are not current-head acceptance.
Dense prefix/position materialization remains intentionally unchanged.

Self-review checked callback/mmap lifetime, iterator close/error
handling, offset bounds, traversal/scoring order and all changed
callers. The experimental precheck/streaming harness is intentionally
excluded from this PR.

### Review sequencing

Ready for code review at the author's request; not full QA/merge
acceptance. The v6 measured-head188-query series is complete and
time-stable across all three pairs; actual high-hit mixed and dense
single-prefix baseline/M1 controls also pass. These developer
performance requirements are supplied for XuPeng-SH re-review, not
self-approved or waived. The measured b0 head's required CI was
successful; the subsequent464 head's coverage failure is fixed via the
upstream main merge and retained as historical FAIL. New exact-head CI
and formal reviewer acceptance remain pending. Full TKE weekly
integration remains later QA, not a prerequisite for code review.

V5 completed normally after the author relaxed only the task-specific
disk floor to20GiB. Limits remained aggregate6GiB memory, swapmax0,
CPU400%, GOMAXPROCS4,45-minute service deadline and exact-unit cleanup.
No129 access or workload was performed. XuPeng-SH's outstanding
performance review is not marked resolved by this evidence update.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

This branch was previously deployed

1 inactive deployment
ci — 82efec7c Deployed Oct 8, 2026 by XuPeng-SH
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.

shardservice: Close leaves RPC listener accepting connections

2 participants