Repository navigation
fix(morpc): unblock FIN teardown when writer exits - #29559
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep review of 9e0d8e7cf22258a2f66ff3bf66360f9d09e3a70b against base 113d374b2e5167238d8411c117dfe879aef8bad6, covering all five changed files. No subagents.
代码结论:未发现阻塞代码缺陷,达到 no-blocker / approve recommendation 标准。当前仍不能合入:CI preflight 的有效 issue 关联门槛未满足。
设计合理性:FIN 的 claim/send/commit 复用已有 receive-stream 状态归属,finishing 必要地保留原锁提供的终止排他性;没有建立新 registry、worker、queue 或重试分支。同步等待期间不再持有关闭所需的锁,成功 flush 后才退休序号。Close、重复 FIN、其他 stream、关闭后迟到请求及指标回收都属于同一生命周期闭包。
| 审查 | 结论 |
|---|---|
| Q1 所有权 | FIN 发送前拒绝 / MORPC 丢弃与排队失败 / goetty 编码释放是不同阶段;CN 回调与已有 Config.NewServer 模式一致,不是重复回收 |
| Q2 活性 | FIN 不持 receive-state 锁跨 cache、admission、I/O 或 Future 等待;writer 退出时 Close 可完成排队 Future |
| Q3 有界性 | terminal flag 使用现有活动 stream entry;队列容量和 Future 回收边界未扩大 |
影响范围已检查:普通 batch、错误/terminal 响应、protocol check 以及 FIN ACK 的发送调用方均不会在交出消息后继续访问它。Future 原有等待语义保留,避免借用 payload 被提前释放。无 wire/protobuf/持久化/catalog 格式变更,不涉及混合升级兼容分支。
性能结论限于消除关闭死锁和网络时长的锁持有,不宣称 SQL 吞吐提升。新增成本是现有 entry 的 inline flag 和校验时的短 RLock;未新增 per-message allocation、payload copy、goroutine、timer。实现、216 行新增测试和零 tracked 文档增量分别审查:测试使用现有轻量 fixture、最小消息量及 admission/filter 屏障,不靠 sleeps/retries 或新增重型集群。没有无实际调用价值的新抽象。
验证:核对源码 fingerprint 后复用当前 head 的基线 red/candidate green、八个独立 FIN 用例 race100、MORPC/CN 整包 normal/race、compile FIN 消费者、真实两 CN join normal/race(含 cluster 清理)及增量 lint。另补两个未由既有随机并发用例确定选中的 QA 反例,各 -race -count=100 通过:
- FIN 编码回收后暂停在 Flush,Close 胜出,再允许 Flush 成功:无状态复活、重复退休或 double release。
- 旧 Future 完成回调立即初始化新一代 one-way Future:旧 cleanSend 不会误关新 owner。
可选测试建议:把上述两个阶段性反例保留到回归套件中;本次探针不修改生产代码,未 push。
历史评论:当前没有 code review thread 或历史代码 review;唯一评论是 Qodo 服务暂停提示,不存在可宣称已逐条修复的代码意见。
合入门槛:CI preflight 明确失败于 there is no valid issue, so return false。描述里的 #29549 是 PR,不是有效 issue,因此 UT 等后续作业被跳过、CI Required 红灯。这不是产品 UT 失败,也不是 CI green;应准确关联此 MORPC 死锁的 issue,不能拿不相关 issue 只为通过校验。不等待 CI。
当前 GitHub 账号为本 PR 作者 XuPeng-SH,GitHub 不允许自我 APPROVE;因此提交正式 COMMENT review。上述代码结论不等同于 GitHub APPROVED 状态。
XuPeng-SH
left a comment
There was a problem hiding this comment.
复核 head 9e0d8e7cf22258a2f66ff3bf66360f9d09e3a70b,声明 base 113d374b2e5167238d8411c117dfe879aef8bad6。全部五个变更文件、调用方、历史评论均已检查;没有使用 subagent。
结论:未发现阻塞代码缺陷,代码达到 no-blocker / approve recommendation 标准。此前 review 的 issue 关联门槛已修复:PR 现在关联实际死锁 issue #29560,CI preflight 已成功。CI 仍有运行中的作业,本评审不等待 CI,也不把 pending/skipped 算作通过。
设计从已有职责归属出发:clientSession 的 receive-stream registry 管理验证和退休,sentStreams 管理发送序号,writer/Future 管理发送完成,goetty 管理编码后的消息释放。finishing 是同一个活动 entry 内的终止声明:释放 receive-state 锁后,仍需拒绝同流后续请求和重复 FIN,因此该字段有明确正确性收益。没有新增 registry、执行路径、队列、worker、timer、retry 或兼容状态机。普通 focused bugfix 不需要额外设计文档;生命周期部分按 R3 审查。
| 审查闭包 | 不变量与结论 |
|---|---|
| FIN / Close / writer(R3,Q2) | 原先 FIN 持锁等 Future、writer 退出后的 Close 等同一锁。现在 claim 后解锁,成功 flush 后才退休;Close 可以清理排队 Future。满队列 admission 仍依靠现有 context deadline 终止,并没有改写 borrowed payload 的等待语义。 |
| receive/send 状态(R3,Q3) | claim 排除同流竞争;无关流继续进展;Close 清空状态,迟到请求不能重新建表项。没有增加保留容器或扩大队列容量。 |
| response / Future 代际(R3,Q1) | 发送前拒绝和 MORPC drop 由现有 release callback 清理;编码交给 goetty 后由 goetty 清理。二者是不同所有权阶段。completion 前缓存 oneWay,编码后使用缓存 ID,避免访问回池对象。 |
| CN 调用边界(R2) | 新 callback 使用已有 responsePool,符合 Config.NewServer 的既有模式。FIN ACK、普通 batch、error/end 和 protocol-check 调用方交出 response 后不再访问或释放它。 |
| 测试、注释(分别审查) | 五个新测试使用既有轻量 session/Future fixture,invalid-authority 用表驱动;admission/filter 是阶段屏障,timeout 只作挂起保护。没有新增重型集群、生产测试 hook 或只为测试建立的抽象。API 注释明确消息消费契约;没有 tracked 文档增量。 |
MORPC 是共享 transport:接收校验也覆盖 txn RPC、logtail 等非 pipeline stream;未调用 FinishStream 的流,finishing 始终为 false,原有序号规则保持一致,关闭后的迟到请求拒绝是合理的生命周期收紧。无 wire/protobuf、catalog、持久化格式、planner 或 SQL rewrite 变更;不需要新增升级/回滚/租户兼容分支。检查最新 main 152a1c4f5f072dab37e5af620b10c7086deeb1f4 的 #29549 后,pipeline terminal publication 继续归 PipelineEdge,FIN 继续归 MORPC;职责没有重叠。
本次新增 Linux amd64 / Go 1.26.4 验证(使用该 worktree 的原生构建与仓库 CGo wrapper):
- 8 个 FIN 测试
-race -count=1全部通过;MORPC 整包 race 361 个顶层测试通过,18.011s。 - 独立白盒 QA:真实 goetty 编码注入 marshal error,release 后消息拒绝 GetID 访问,以模拟立即回池复用。候选
-race -count=100通过,消息/Future 各释放一次、队列和流状态归零;相同探针在基线超时,栈同时显示 release 后的 GetID 访问、FIN 等 Future、writer deferred Close 等 receive-state 锁。该证据不是 fake Write 的释放假设。 - 为验证与最新 main 的组合,用 Go overlay 应用 main 相对声明 base 的全部 8 个 Go 文件;确认 native/module 输入无变化。两 CN
TestJoinCoordinatorStage -race -count=1通过:五个 SQL 场景、LIMIT、空结果和远端物理计划检查保留,测试 27.72s,整包终态 30.701s;集群清理完成,10000 端口 lease 已可重新取得,该区间没有遗留监听。 - 实际 socket 流往返 benchmark 的 fixture 另通过 race 验证。既有同 head 的 Darwin CN owning-package、compile FIN 消费者与增量 lint 记录复用,没有宣称本次重新执行这些检查。
性能实测(相同 fixture,各 5 次,500ms/sample;基线通过 Go overlay 恢复 MORPC 原始源码):
| 指标 | 基线中位数 | 候选中位数 | 解读 |
|---|---|---|---|
| 单流 serial receive validation | 16.69ns/op | 25.42ns/op | 新增约 8.73ns,双方 0 B/op、0 allocs/op;主要是关闭检查的短读锁与终止标志检查。 |
| 真实 Unix socket stream round trip | 14.322µs/op | 14.389µs/op | 约 +0.47%,样本区间重叠;均 25 allocs/op,约 1644 B/op。此次没有观察到稳定退化。 |
上述仅证明该校验路径与小消息流往返的成本,不等于各种 SQL/大 payload/高并发吞吐保证。SQL planner/算子计算路径没有修改;新增成本位于共享 MORPC server 的 stream request validation,pipeline、txn RPC、logtail 等流请求都会经过,不能简单按单 CN/多 CN 宣称整个 SQL 零影响。错误、丢弃和 FIN 清理主要获得回收完整性和活性收益。未增加每条消息的 payload copy 或生产分配,新增复杂度有明确维护收益,当前证据不支持为消除纳秒级局部成本再改一套关闭状态。
历史评论核对:目前没有 code-review thread;唯一普通评论是 Qodo 服务暂停提示。上一份 review 的 preflight blocker 已解决。上一份提出的两个阶段性 QA 探针保留为常驻测试的建议仍未落码;它们是已有 race100 证据的非阻塞测试建议,不能表述成“所有建议都已实现”,也不是未修复的已证实缺陷。
验证环境说明:fresh worktree 缺少 native headers 的首轮链接,以及共享 /tmp/mo-test.cluster 权限错误,均发生在测试执行前;分别通过规范 native build 和任务独立 TMPDIR 修正后重跑成功,未更改产品代码或他人临时文件。本次临时 QA 文件已保存到 /mnt/nvme/pr29559-review 并从 worktree 移除,源码保持干净,未 commit/push 代码。
当前账号为 PR 作者,GitHub 不能自我 APPROVE,因此提交正式 COMMENT review;代码结论不代表 GitHub APPROVED 状态。
## What type of PR is this? - [ ] API-change - [x] BUG - [ ] Improvement - [ ] Documentation - [ ] Feature - [x] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: issue #32157 (first batch only; keep the tracking issue open) ## What this PR does / why we need it: Backport six focused startup, RPC, and memory-lifetime fixes onto `4.2-dev@02fcfbc`. These old paths are still present on that release baseline. This is deliberately not a bulk backport of the tracking issue's 30 entries and is not release approval. | Source PR | Backported behavior | Failure/compatibility boundary | | --- | --- | --- | | #30761 | Hand off a first-catalog-replay disconnect to the existing reconnect owner; do not publish readiness while paused. | Before/during/after replay handoff, retry and cancellation, then actual SQL after recovery. No Main worker-lifecycle refactor. | | #29586 | Preserve live user-unary Futures during idle GC and atomically seal admission when truly idle. | Heartbeats do not keep idle connections alive; completed/canceled work can be reclaimed; saturated cleanup remains capacity-accounted. Retains the source PR's logical-row-count/NULL correction in `readSingleTaskRunner`. | | #29559 | Claim FIN in the existing stream entry without holding its mutex over synchronous send; release rejected responses once. | Writer exit, full queue, invalid/duplicate FIN and later requests; update the CN drop-release callback at the same ownership boundary. | | #30536 | Public session close disconnects transport; only the writer finalizer or failed-start path releases the writer's Goetty reference. | Active Encode/Flush, blocked socket output and failed writer startup; tested together with FIN. | | #28384 | Detach address-keyed ownership/profile state before off-heap realloc can recycle the old address; restore it if allocation fails. | No change to accounted allocation or allocate-copy-free ownership paths; allocator failure and address reuse are explicit oracles. | | #29352 | Drop a completed non-constant Scope's Reader reference after pipeline cleanup. | The existing TableScan/Pipeline owner still closes the Reader; no additional Close call; prepared reuse must rebuild/read correctly. | Each source retains an independent `cherry-pick -x` commit. Release-adaptation commit `72fb70919a9b98213af778cc7a4d6525e97dd7c4` uses 4.2's existing Future predicate and queue instrumentation rather than importing unrelated Main machinery. The real first-replay regression uses 4.2's existing `pkg/embed` cluster owner, with process-wide faults isolated in a dedicated test package, and also checks real MySQL prepared-statement reuse. ### Scope and design review - No wire, catalog or persisted-data format changes, new configuration, external dependency versions, SQL optimization rules, or background cleanup subsystem. - MORPC and mpool are shared code: their changes also affect other roles that use them, not only CN. Excluding TN storage/WAL changes is not a claim that TN executes no changed code. - Resource ownership remains with the existing Pipeline, RPC writer, client cleanup pool, allocator and connector. FIN adds one terminal bit to an existing live stream entry; replay adds one notification channel per connector, not a second recovery state machine. - Idle GC scans existing Futures only after the idle-age check; it does not add per-request bookkeeping. The other changes replace cleanup ordering or remove references. No throughput improvement or zero-regression guarantee is claimed. - Q1: response/Future/transport/Reader cleanup owners checked, including rejected admission and failed startup. Q2: FIN no longer holds the receive-state lock over send completion; disconnect interrupts socket I/O; first replay wakes the existing reconnect path. Q3: no new growing registry or queue; bounded backend cleanup is retained. ### Deliberately not included - #29725: 4.2 already enters allocator recovery on Unlock errors; Main's bypass guard is absent. Do not label this as the same confirmed release-branch Unlock leak. - #29448, the NULL-completeness subset of #29558, and #28693 remain follow-up candidates with separate authentication/planner/transaction-helper validation; absence here does not mean they are unimportant. - The TN/WAL, mixed-lock, HNSW and ISCP task-lifecycle changes need dedicated adaptation and upgrade/recovery coverage. CDC already has #32232; do not duplicate it. No rollback/upgrade of any running cluster is part of this PR. ### Tested with Original backport validation: `72fb70919a9b98213af778cc7a4d6525e97dd7c4`. Local runs used Go 1.26.4, Darwin arm64, native libraries built from this release tree, `GOMAXPROCS=2`, `-p=1` and normally `GOMEMLIMIT=2GiB`. Earlier pre-commit runs retain their working-tree identity; their relevant source content matches that original validation commit. No historical Main test result is presented as a test of this backport. | Evidence | Result | | --- | --- | | MORPC, mpool, ISCP, compile and disttae owning packages | Normal and race PASS. | | CN owning package | Normal and race PASS with the environment-sensitive scalar memory-limit test split as described below; all tests in that partition covered. | | New real embed regression | Normal and race PASS: inject disconnect during first catalog replay, recover startup, observe a fresh TN timestamp, and execute one actual MySQL prepared statement twice with results `[1,2]`, then `[2]`. The dedicated test package isolates faults from the shared embed cluster. | | Existing `TestSingleCNCluster` | Race PASS. | | Linux amd64 on server 50 | Both Linux-only realloc tests PASS in normal/race; full mpool (71 top-level tests) and MORPC (315 top-level tests) normal/race PASS. | | Matched Linux baseline controls | Clean `02fcfbc898` plus only regression probes reproduces three real failures: stale metadata at allocator-cache publication, queued-FIN close deadlock, and buffers freed during active Encode. Candidate passes the same oracles. The baseline physical-allocation-failure test already passes and is retained as compatibility coverage, not claimed as a new failing counterexample. | Linux used existing immutable build image `sha256:44069beb9d61e8d1d6766f1d214eb94843257616bc8c9291ee53fae1edbbd7fa`, fresh candidate/base native builds and separate source/cache directories. Containers had 2 CPUs, 4 GiB memory+swap limit, 512 PIDs and no network. Existing services on 50 were not changed. The first capped full CN runs failed `Test_service_handleGoMemLimit/set_4Gi`: that test assumes the initial Go memory limit is `MaxInt64`, but the explicit test environment supplied 2 GiB. The exact capped case on clean baseline `02fcfbc898` fails with the same expected-MaxInt64/actual-2147483648 signature. We did not weaken its assertion or change product code. The package is run with that one case excluded under the cap, and the exact scalar-only case is separately run in normal/race with `GOMEMLIMIT` unset. Original failed receipts remain failed. Stress: 21 individually selected MORPC/mpool/compile/disttae cases passed independent `-race -count=100` runs on Darwin. The isolated embed recovery case passed its proportional repeat (`T=17.25s`, `B=30s`, `N=1`). Linux cache-publication retirement passed `-race -count=100`; physical allocation failure passed `-race -count=29` (`T=1.03s`, `B=30s`). Selections are non-empty and recorded by individual test name. Commands use the repository CGo wrapper, with serial package builds: ```sh GOMAXPROCS=2 GOMEMLIMIT=2GiB .agents/skills/mo-dev/scripts/mo-cgo-test -p=1 -count=1 -timeout=240s ./pkg/common/morpc ./pkg/common/mpool ./pkg/iscp ./pkg/sql/compile ./pkg/vm/engine/disttae GOMAXPROCS=2 GOMEMLIMIT=2GiB .agents/skills/mo-dev/scripts/mo-cgo-test -p=1 -race -count=1 -timeout=240s ./pkg/common/morpc ./pkg/common/mpool ./pkg/iscp ./pkg/sql/compile ./pkg/vm/engine/disttae # CN package: normal/race separately, then the one default-limit oracle separately. GOMAXPROCS=2 GOMEMLIMIT=2GiB .agents/skills/mo-dev/scripts/mo-cgo-test -p=1 -count=1 -skip '^Test_service_handleGoMemLimit$' ./pkg/cnservice env -u GOMEMLIMIT GOMAXPROCS=2 .agents/skills/mo-dev/scripts/mo-cgo-test -p=1 -count=1 -run '^Test_service_handleGoMemLimit$' ./pkg/cnservice # Also repeated with -race; each stress command selects exactly one test. # Original test path at 72fb; the follow-up moves it to ./pkg/embed/firstreplay. GOMAXPROCS=2 GOMEMLIMIT=2GiB .agents/skills/mo-dev/scripts/mo-cgo-test -p=1 -race -count=1 -timeout=240s -run '^TestCNFirstReplayDisconnect$' ./pkg/embed ``` `go vet` passed for all seven affected production/test packages; `git diff --check` passed. Incremental golangci-lint was **not validated**: locally installed versions are incompatible with the repository's v2 config/Go 1.26 toolchain. No lint configuration or dependencies were changed to bypass this limitation. No full BVT, production workload benchmark or rolling-upgrade qualification is claimed; PR CI and release qualification remain separate. ### Incidental bug findings `pkg/tests/service.buildCNConfig` on the target baseline validates a newly generated CN UUID before registering its service runtime, causing a nil-runtime panic before the cluster starts. This is already addressed upstream by #30380 (`0723ae37b1`); disposition: **Duplicate / not included**. The new regression uses the existing embed fixture, which already registers the runtime and catalog definitions. It does not patch or claim validation of the legacy service fixture, and does not pull in the broader CN-drain changes from #30380. Ordinary off-heap profiling has a separate pre-existing enable/allocate/disable/free boundary: the pool returns to zero but the profile pointer/in-use sample remains recorded. An isolated baseline probe reproduced it; disposition: **Created #32334 / not included**. This is diagnostic metadata retention, not a demonstrated native-buffer leak or customer OOM, and does not change this batch's scope or review conclusion. ### CI test follow-up Follow-up commit: `6404268dae8b5d78a12fb0459b67991c8893a9cd`. After the 4.2-dev merge, [UT](https://github.com/matrixorigin/matrixone/actions/runs/42341756945/job/128310805969) and [coverage](https://github.com/matrixorigin/matrixone/actions/runs/42341756945/job/128310839394) exposed a process-admission deadlock in `TestCNFirstReplayDisconnect`: the shared embed fixture held the runner-wide lock while its test process waited for a child that needed the same lock. Move the existing recovery test into its own test package, remove the recursive subprocess, and acquire the existing process admission before starting replay deadlines. Fault injection remains process-isolated, and the real fresh-TN-timestamp and two prepared-execution result oracles are retained. The coverage run also failed an existing dropped-user authorization assertion across two CNs. The reader uses its locally applied statement snapshot, so the test now fences the committed DROP and verifies through independent CN1 SQL that the user is absent before checking that the already-authenticated session is denied. This establishes denial after visibility; it does not claim instantaneous cross-CN revocation or prove the precise cause of that CI failure. The unmodified 4.2-dev baseline passed three normal repetitions. Follow-up validation on Linux/amd64, Go 1.26.4, matching branch-local native libraries: - The original full-order reproduction fails on `6c7dca5d` after the shared cluster starts; the independent test passes with the same lock held by another process for over 40 seconds, then released, including under `-race`. A separate cancellation control confirms admission times out before faults or a cluster start. - Complete `pkg/embed` and `pkg/embed/firstreplay` suites run together with `-p=2`: PASS (230.547s and 17.923s). Existing process-admission exclusivity, reentrancy and cancellation tests also pass under `-race`. - Full `TestIssue29399AuthorizationScopeAndRevokedRole`: three normal repetitions and one `-race` run pass, including the CN1 public-SQL visibility and retained-session denial checks. - Scoped CI-style `-tags matrixone_test -short -covermode=set` execution of both scenarios passes with cnservice, MORPC, mpool, ISCP, compile, disttae and frontend instrumented. This is not the full CI coverage producer. - Incremental gofmt and `go vet` pass for the affected packages; repository-configured golangci-lint 2.6.2 built with Go 1.26.4 reports 0 issues for the follow-up diff. The original backport diff passed arm64 SCA on `6c7dca5d`. - Independent design: `gpt-6.1-terra/max`. Independent overall review: `gpt-6.1-sol/max`, no material code blocker; final evidence reconciled before delivery. The follow-up changes only tests; it adds no production hot-path work. Full post-push CI and release/upgrade qualification are separate and are not claimed as passed here. --------- Co-authored-by: XuPeng-SH <[email protected]> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
What type of PR is this?
Which issue(s) this PR fixes:
Fixes #29560.
What this PR does / why we need it:
TestJoinCoordinatorStagecompleted its five SQL subtests, but cluster cleanup timed out after 40 minutes. FIN held the receive-state mutex while waiting for synchronous send completion. The exiting writer's deferred session Close needed the same mutex before it could drain and fail the queued FIN Future. Server shutdown then waited forever for that writer.Claim FIN in the existing receive-state registry, release its mutex before cache access/write admission/send completion, and retire receive/send sequence state only after successful flush. The inline terminal claim rejects duplicate FIN and later requests on that stream while unrelated streams can progress. Close can independently drain pending sends; closed sessions cannot recreate receive state.
Complete the same response ownership boundary: release pre-send FIN rejections, configure the pipeline server's existing MORPC drop-release callback, use the cached message ID after goetty encoding, and snapshot Future flags before completion can return them to their pool. Ordinary Future cancellation semantics remain unchanged to protect borrowed payload lifetime.
No new queue, worker, timer, retry, wire format, catalog format, or persisted-data format. The terminal flag lives only in an existing active-stream entry. This removes network-length receive-state lock contention and the shutdown deadlock; no SQL throughput improvement is claimed.
Validation
113d374b2e5167238d8411c117dfe879aef8bad6; explicitly releasing the queued Future allows both blocked calls to finish.-race -count=100runs passed; cleanup-adjusted cases were revalidated.-vet=alland race passed.-vet=alland race passed.TestJoinCoordinatorStage: normal 18.012s and race 23.311s, including cluster teardown and port-lease release. All five SQL subtests retained.Design and final overall review completed using actual
gpt-6.1-sol/xhigh. Final decision: PASS, no unresolved material code or validation blockers. Reviewed base113d374b2e5167238d8411c117dfe879aef8bad6plus all five final delivery files; source fingerprints match the validation ledger. Session01a0f77c-c1ba-76e3-ae82-ba019248459d.