Repository navigation
Description
Summary
A healthy Running MORPC backend with an in-flight unary RPC is collected as idle, even though its request context is still live and heartbeat ping/pong succeeds. The pending Future fails with 20502: backend connection closed, while the TN can continue executing the checkpoint.
This is a confirmed backend-lifetime defect, not a checkpoint data-correctness assertion failure. It was found while investigating the 4.2 nightly failures and reproduced independently against the exact tested MO source without modifying production code.
Strongest incident example: C-10's globalcheckpoint('5m') returned backend-closed to the CN after about 59 seconds, but the corresponding TN GCKP successfully finished after 4m59.862750428s.
Version and incident
- Product: 4.2-dev, MO
28f1f02a89339def1b2572dbe07e98144a203167. - MOTR:
957dd0c4a7b82cf12c143a72900045dfe3879728. - Nightly Run 37024396489 / MOTR Job 111002081410.
- Namespace:
mo-42-family-37024396489-1. - CN:
nightly-regression-dis-tp-cn-5d488; TN:nightly-regression-dis-dn-0. - Current main
fcd9686e0de5c71b6cd2913f922ad54e7df0a324contains the same relevant idle-GC predicate (source checked only; the deterministic reproduction below was run against the exact 4.2 SHA).
Real request timeline
All timestamps below are UTC on 2026-10-02 (2026-10-03 early morning in Asia/Shanghai). These are server request timestamps, not the duration of the whole Python Case.
| Case / command | TN request start | CN returns 20502 | Same TN operation finishes |
|---|---|---|---|
C-03 / checkpoint('') |
20:05:39.467186 | 20:06:52.737 | 20:07:09.916: force-flush deadline; total 90.449480441s |
C-10 / globalcheckpoint('5m') |
20:06:57.372816 | 20:07:56.397 (~59s) | 20:11:57.235570: GCKP success; total 4m59.862750428s |
G-02 / checkpoint('') |
20:08:08.295169 | 20:09:06.412 (~58s) | 20:09:38.299055: force-flush deadline; total 90.003879663s |
C-10 TN completion log:
{"level":"INFO","time":"2026/10/02 20:11:57.235570 +0000","caller":"db/db.go:249","msg":"DB-Force-GCKP","total-cost":"4m59.862750428s","force-flush-cost":"4m54.332212135s","history-retention":"0s","requested-ts":"1790971617372816845-0","checkpoint-ts":"1790971617372816845-0","fresh-ickp-retries":0}The INFO/no-error result follows the err == nil logging branch in DB-Force-GCKP. This is server success after the caller had already received an error, not a successful client response.
For locating the statements in query traces:
- C-03:
1718cdd9-fe6e-c351-61a4-2b8db71da1b8. - C-10:
8ffeac19-2463-814d-8100-65b392ef4b5d. - G-02:
af8015f5-b800-dd33-10ce-f7cc6fc28f33.
Why this is not just a Python timeout or pod restart
- C-03/C-10/G-02 use client read timeouts of 300/360/120 seconds respectively; C-03/C-10's script wrapper allows 1800 seconds.
- C-10 explicitly requests a five-minute server budget.
- C-03 can still run SYNCCOMMIT, read count=10001 and clean up through the same PyMySQL connection after receiving 20502. The closed backend is internal RPC, not the SQL client connection.
- Kubernetes metrics show zero restarts and unchanged Pod UIDs throughout 19:45–20:20 UTC.
- C-10 fails at its pre-workload GCKP fence, before its 62-ICKP workload begins.
The CN's mo_rpc_gc_idle_backends_cleaned_total actual 30-second scrapes also bracket all three client errors:
20:06:34 14
20:07:04 15 # C-03 CN error at 20:06:52.737
20:07:34 15
20:08:04 16 # C-10 CN error at 20:07:56.397
20:09:04 16
20:09:34 17 # G-02 CN error at 20:09:06.412
This metric is CN-aggregate, not a per-backend close audit. The attribution is supported by the exact call path and the deterministic real-socket reproduction below, not by that counter alone.
Root cause
Actual checkpoint path in this single-TN deployment:
mo_ctl(checkpoint/globalcheckpoint)
→ MoCtlTNCmdSender / txnOperator.Debug
→ TxnSender.Send (one-TN unary branch)
→ sender.doSend
→ MORPC client.Send
→ Future.Get
- TxnSender uses unary Send/Get. This does not hold a stream's backend lock.
- client.Send obtains an unlocked backend.
- While the server works, there may be no business response traffic. Heartbeat messages intentionally do not update business activity.
- closeIdleBackends protects draining generations, but for an ordinary Running backend checks only
!b.Locked()and the last-business-activity age before cleanup. It does not protect pending unary Futures. - Default idle duration is one minute with ±10% jitter. Once eligible, background GC closes the connection; Close fails all pending Futures.
- This overrides the request's still-valid lifetime, including checkpoint's default 90-second or explicitly requested timeout.
The violated invariant is:
A live, accepted unary request awaiting its response must not be classified as an idle backend merely because no business bytes have arrived recently. Its request context, response, or an actual transport failure must govern completion.
Deterministic reproduction and controls
The diagnostic below uses the real MORPC client, Unix socket, pending Future, and ping/pong on the exact 4.2 SHA. Only the last-business-activity timestamp is aged artificially to avoid a minute-long timing test; idle GC itself is the original production implementation. It is not a full cluster checkpoint reproduction.
Three subtests:
| Scenario | Result |
|---|---|
| Same pending request, aged timestamp and healthy heartbeat; no GC invocation | Response arrives normally |
| Running backend with one pending unary Future; invoke idle GC | Backend collected; Future returns 20502 while request context is still live |
| Same request with backend marked draining; invoke idle GC | Existing draining guard preserves it; response arrives normally |
Commands from an isolated checkout of the exact MO SHA:
GOWORK=off go test -buildvcs=false -mod=readonly -race -v -count=1 -timeout=90s -run '^TestCheckpointIdleGCProof$' ./pkg/common/morpc
GOWORK=off go test -buildvcs=false -mod=readonly -race -count=100 -timeout=90s -run '^TestCheckpointIdleGCProof$' ./pkg/common/morpcFinal result: 100 defect reproductions and 200 successful controls, race run passed in 3.266s. Test PASS means the diagnostic reproduced the bug, not that the product is fixed.
REPRODUCED: backend connection closed; live request context=<nil>; peer pong succeeded; pending unary=1; idle threshold=56.262707791s
ok github.com/matrixorigin/matrixone/pkg/common/morpc 3.266s
No production source was modified, no new TKE run was started. Standard Go/CGo was used for this isolated package after checking its dependency closure; the repository wrapper could not run without libmo, and no stale native library was reused.
Complete diagnostic: pkg/common/morpc/checkpoint_idle_gc_proof_test.go
package morpc
import (
"context"
"path/filepath"
"sync"
"testing"
"time"
"github.com/fagongzi/goetty/v2"
"github.com/matrixorigin/matrixone/pkg/common/moerr"
"github.com/matrixorigin/matrixone/pkg/logutil"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
)
// Diagnostic only: no production code is changed. A live unary RPC must not be
// mistaken for an idle connection while its independent request budget remains.
// The only simulated input is the last-business-activity timestamp. The client,
// socket, heartbeat, pending Future and original idle collector are real.
func TestCheckpointIdleGCProof(t *testing.T) {
for _, scenario := range []string{"no_gc_control", "running_unary_collected", "draining_guard_control"} {
t.Run(scenario, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
t.Cleanup(cancel)
requestReceived := make(chan struct{})
releaseResponse := make(chan struct{})
responseFinished := make(chan struct{})
var releaseOnce sync.Once
var serverWriteMu sync.Mutex // goetty IOSession has one write owner.
release := func() { releaseOnce.Do(func() { close(releaseResponse) }) }
unixFile := filepath.Join(t.TempDir(), "rpc.sock")
addr := "unix://" + unixFile
app := newTestAppWithAddr(t, addr, unixFile, func(conn goetty.IOSession, msg interface{}, _ uint64) error {
request := msg.(RPCMessage)
if request.internal {
serverWriteMu.Lock()
defer serverWriteMu.Unlock()
ping := request.Message.(*flagOnlyMessage)
return conn.Write(RPCMessage{Ctx: request.Ctx, internal: true,
Message: &flagOnlyMessage{flag: flagPong, id: ping.id}}, goetty.WriteOptions{Flush: true})
}
id := request.Message.GetID()
close(requestReceived)
go func() {
defer close(responseFinished)
select {
case <-releaseResponse:
serverWriteMu.Lock()
defer serverWriteMu.Unlock()
// The error in the GC branch is expected: it already destroyed
// the socket before the healthy peer could return its result.
_ = conn.Write(RPCMessage{Ctx: ctx, Message: newTestMessage(id)}, goetty.WriteOptions{Flush: true})
case <-ctx.Done():
}
}()
return nil
})
require.NoError(t, app.Start())
t.Cleanup(func() { require.NoError(t, app.Stop()) })
rpcClient, err := NewClient("checkpoint-idle-proof", NewGoettyBasedBackendFactory(
newTestCodec(), WithBackendReadTimeout(30*time.Second)), WithClientMaxBackendMaxIdleDuration(time.Minute),
WithClientLogger(logutil.GetPanicLoggerWithLevel(zap.FatalLevel)))
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, rpcClient.Close()) })
client := rpcClient.(*client)
f, err := rpcClient.Send(ctx, addr, newTestMessage(1))
require.NoError(t, err)
// Unregister after creation: asynchronous backend creation requires
// registration. Drive subsequent idle collection explicitly.
client.gcManager.unregister(client)
t.Cleanup(f.Close)
t.Cleanup(func() {
release()
select {
case <-responseFinished:
case <-ctx.Done():
t.Errorf("server response worker did not terminate: %v", ctx.Err())
}
})
select {
case <-requestReceived:
case <-ctx.Done():
t.Fatal("server did not receive the unary request")
}
client.mu.Lock()
require.Len(t, client.mu.backends[addr], 1)
backend := client.mu.backends[addr][0].(*remoteBackend)
client.mu.Unlock()
require.False(t, backend.Locked())
require.True(t, backend.admissionAvailable())
backend.mu.RLock()
pending := len(backend.mu.futures)
backend.mu.RUnlock()
require.Equal(t, 1, pending, "the server is still processing a real unary Future")
lastActivity := time.Now().Add(-2 * time.Minute)
backend.atomic.lastActiveTime.Store(lastActivity)
// Natural heartbeat fetch uses getFuture + enqueue, not send/active.
// Exercise that exact distinction and confirm the pong arrives.
ping := backend.getFuture(ctx, &flagOnlyMessage{flag: flagPing}, true)
require.NoError(t, backend.doSend(ping))
_, err = ping.Get()
ping.Close()
require.NoError(t, err, "peer and transport are alive")
require.Equal(t, lastActivity, backend.LastActiveTime(), "heartbeats do not refresh business activity")
if scenario == "draining_guard_control" {
backend.atomic.draining.Store(true)
}
if scenario != "no_gc_control" {
closed := client.closeIdleBackends()
if scenario == "running_unary_collected" {
require.Equal(t, 1, closed)
_, err = f.Get()
require.True(t, moerr.IsMoErrCode(err, moerr.ErrBackendClosed), "unexpected error: %v", err)
require.NoError(t, ctx.Err(), "request deadline must still be live")
t.Logf("REPRODUCED: %v; live request context=%v; peer pong succeeded; pending unary=%d; idle threshold=%v", err, ctx.Err(), pending, client.options.maxIdleDuration)
return
}
require.Zero(t, closed)
}
release()
response, err := f.Get()
require.NoError(t, err)
require.NotNil(t, response)
require.NoError(t, ctx.Err())
t.Log("CONTROL: same healthy server returned its pending unary response")
})
}
}Triggering workload and limits of the diagnosis
The same namespace's Full Concurrent Job ran account creation/deletion, then found 5488 remaining test accounts and started eight-worker cleanup at 20:03:38 UTC. All three checkpoint errors occurred during that cleanup. A TN checkpoint covers global dirty data, not just the Case's small private table. TN force-flush logs contain many tenant catalog tables during this interval.
This establishes concurrent catalog-flush pressure as the observed trigger/background. It does not establish a separate flusher livelock bug or explain every part of the flush duration.
- C-03 and G-02 subsequently reach the TN's real 90-second force-flush deadline. Fixing the premature RPC close alone does not promise those tests will pass under the same load.
- No data loss/corruption is established.
- Both days used the same MO/MOTR SHAs. Yesterday C-03 already reported a force-flush deadline, C-10 was SKIP, not PASS, and G-02 passed. Do not label this as a proven newly introduced regression today.
- The separate failure path involving long flushes should not be hidden by simply increasing the RPC idle timeout or automatically retrying an already-accepted checkpoint command.
Expected fix / validation scope
Preserve accepted in-flight unary requests through idle cleanup, with request admission and cleanup synchronized so a concurrent new request cannot race the decision. Truly idle backends should still be reclaimed. Preserve existing draining and stream behavior.
Focused regression coverage should include the three diagnostic scenarios above, request deadline/cancellation cleanup, and eventual collection after the last request completes. Then recheck the checkpoint command using a controlled slow response; no full 1B/TKE workload is required to prove the RPC fix.
Related, not equivalent:
- [Bug]: TestIndependentControlBackendPreservesSlowDataRequest races global idle GC #26649 documented a test fixture's interaction with idle GC before entering draining; it was a test correction, not a product fix for ordinary Running unary requests.
- [Bug]: lockservice 10s backend read timeout cancels valid long-running lock RPCs and all shared streams #26090 concerns a backend read timeout canceling valid lock operations. Here the confirmed closure owner is idle GC, despite a healthy heartbeat and live context.
Activity
LeftHandCold commentedon Oct 3, 2026
Main verification and fix
Main was not fixed at
6249e488b51f9b6887e8db95ce9bfc92b4eb49e9. I reproduced the idle-collection failure using a real MORPC client/Unix socket and a healthy heartbeat. No-GC and draining controls passed; the ordinary Running backend was collected while its accepted unary request context remained live. Only the last-business-activity timestamp was aged to avoid waiting a minute.The subsequent main commit
b210a0a5fc878e1e7d04c371297687de003ba292changes Prepared SQL planning, not this RPC path. The main-targeted fix is #29586, headb601159d45a5e4fe55858389a6113654eb608c59.Is this merely an acceptable flush timeout?
Two independent events must remain separate:
The issue's C-10 timeline distinguishes them: CN backend-closed at about 59 seconds, TN GCKP success at 4m59.862s. The existing GC metric is aggregate, so it is not independently a per-connection close audit. The source path and real-socket reproduction independently establish the idle-lifetime defect.
Narrow fix and safety boundaries
This addresses early backend-closed failures. It does not optimize TN flushing or guarantee that C-03/G-02's genuine 90-second deadlines disappear under the same load. There is no new evidence of data corruption or a newly introduced regression commit.
Validation and review
All executed locally with Go 1.26.4 on darwin/arm64, matching
make cgonative artifacts, and the repository CGo test wrapper:-race -count=100-race -count=100pkg/common/morpc, normal / racepkg/txn/rpc, normal / raceCoverage includes healthy slow response, cancellation, deadline, existing draining guard, collection after completion, cleanup saturation, both admission/GC orders, fresh activity and locked streams. Default test vet checks remained enabled. Self-review traced lock order, Future ownership, cancellation, explicit Close, response delivery, stream admission and bounded cleanup; no unresolved blocker was found.
This is an RPC-boundary verification, not a claim that the full nightly checkpoint workload or Linux CI has already passed. No 4.2 backport is included.
fix(morpc): preserve live unary requests during idle GC (#29586)