Skip to content

fix: eliminate load-sensitive timeout assumptions - #27985

Merged
XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-ut-lifecycle-determinism
Sep 2, 2026
Merged

XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-ut-lifecycle-determinism

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

What changed

  • give each ordinary MORPC unary request a complete read-timeout window from admission/flush, instead of charging it for socket-idle time before the request arrived
  • distinguish admitted, successfully flushed, terminal-send-failed, and expired requests while preserving established idle, internal, and one-way behavior and giving stream writes their own bounded fallback window
  • make tenant-upgrade tests execute the observable pass directly, bound every wait, and retain one end-to-end periodic-loop test
  • make the merge scheduler test synchronize at the exact executor/table-check boundary, use deterministic resource admission, and prevent the test observer from blocking the scheduler
  • separate frontend scheduling-preview computation from its production 100 ms best-effort latency policy so correctness tests do not race CI descheduling

Root cause and design

The embedded-cluster failure was not a restore or privilege failure. CREATE ACCOUNT began during an already-running socket Read window and inherited only the remainder of a configured 20-second timeout. Merely increasing the timeout therefore could not guarantee a newly admitted request a full response window.

For a normal response-expecting unary request, the backend now models four relevant states:

  1. admitted/queued or being flushed: retain the stale idle timeout because work is already pending;
  2. successfully flushed: start one full response window at the successful flush timestamp;
  3. terminal send failure: do not extend the connection lifetime;
  4. expired response window: close the stalled backend; a newer admission cannot rescue it.

The timestamp is published before the terminal send-completion flag. The timeout scanner reads that flag before the timestamp, so it cannot observe an old zero timestamp paired with the new success flag. The hot path adds one atomic store only for normal unary traffic after a successful flush; the cold timeout path scans the existing lifecycle-bounded future set. Internal, one-way, probe-enabled, cancellation, and close semantics remain unchanged. Probe-less streams use one backend-level last-successful-flush window only when no unary response window exists; an expired unary remains authoritative.

The other failures had the same broad symptom but different mechanisms: correctness depended on a 20 ms asynchronous timer, host/cgroup memory plus 3/5 ms scheduler polling, or a production 100 ms best-effort preview timeout. Race instrumentation and package-parallel CI load can delay those operations without changing their business result. Tests now synchronize on observable state transitions, carry bounded parent contexts, and explicitly distinguish expected cancellation from a hang deadline.

The lifecycle audit found no new unbounded state or waits: future ownership remains reference-counted and backend-close bounded; the timeout scan covers only existing live futures; merge observation is nonblocking and overflow-checked; every new test wait has a 10-second guard.

Fixes #27963

Test plan

Passed before rebase:

  • MORPC state matrix under race: TestReadTimeoutDoesNotChargeIdleTimeToNewRequest (-count=100)
  • actual MORPC request tracking under race: TestReadTimeoutTracksRequestsWithoutLivenessProbe (-count=50)
  • merge scheduler under race: TestScheduler (-count=100)
  • frontend strict-pool path under race: TestDirectSessionStrictPoolWithoutLabelSelectorFailsClosed (-count=50)
  • all seven tenant-upgrade tests separately under race (-count=20 each)
  • full package tests: pkg/common/morpc, pkg/bootstrap, pkg/frontend, and pkg/vm/engine/tae/db/merge
  • full pkg/common/morpc package under race
  • targeted go vet for all four owning packages
  • real embedded-cluster regression under race: TestAuthenticatedTestsReuseBaseCluster and TestIssue26640ClusterRestoreRebindsSubscriptionPrivileges

Rebased cleanly onto current main (3f6856cc5f). The two new upstream commits touched only frontend code, so the affected closure was rerun after rebase:

  • full pkg/frontend: passed (13.974 s)
  • strict-pool frontend counterexample under race, -count=50: passed (1.296 s)
  • full pkg/bootstrap: passed (18.523 s)
  • go vet ./pkg/frontend ./pkg/bootstrap: passed
  • real embedded-cluster regressions under race: passed (36.040 s)
  • git diff --check: passed

No SQL result, wire API, or planner contract changes are introduced, so no SQL BVT case is required; the embedded-cluster tests exercise the public transport/session path directly.

CI reruns for the unrelated failures on #27949 and #27946 were triggered separately; this PR does not wait for those reruns.

Post-review deterministic-clock closure (99e9d6c):

  • removed the remaining 25/50 ms wall-clock oracle from TestScheduler; policy composition now uses a lifetime longer than the test hang guard
  • added TestSchedulerPolicyPatchExpirationUsesInjectedClock to prove in-place policy merging, exact-deadline validity, and removal immediately after the injected clock crosses the deadline
  • focused normal tests passed; both scheduler tests passed separately under race detection with count 100; the full merge package passed

@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 (automated, verified findings). 3 correctness issues and 7 quality items; 8 posted inline below. Two findings fall outside diff hunks, so they are recorded here:

[correctness] pkg/vm/engine/tae/db/merge/scheduler_test.go:588 — exact-sized recording channel can overflow via the 10s vacuum recheck. The tables[0] vacuum uses HollowTopK=1 with a persistent testInject; scheduler.go:771-780 schedules clock.AfterFunc(10s) to re-send the vacuum check, whose inject yields another compact task → an extra ExecuteFor(tables[0]) event. If CI descheduling stretches the test ≥10s before the drain completes, expected[tables[0]] underflows (require.Positive fails with "unexpected merge") or the extra event overflows the exactly-sized buffer (t1002TaskCnt+2, require.False(overflow) fails) — a load-dependent failure reintroduced into the very test this PR de-flakes.

[simplification] pkg/frontend/mysql_cmd_executor.go:2496 — the preview stack is three functions deep with a production-dead top layer. previewQueryScheduling has no production callers (only tests at mysql_cmd_executor_test.go:7259/7297/7338; production goes through previewQuerySchedulingWithSQLMode), and this PR's own test switches to the bottom layer — leaving three names and three optional-parameter conventions (variadic statementSQL, *string sqlMode, plain rawSQL) for one computation. Collapsing to the timeout-policy wrapper plus the context-taking core and porting the three test callers removes a dead seam.

Comment thread pkg/common/morpc/backend.go Outdated
// behavior. An admitted unary request keeps the old idle deadline from
// closing its transport while it is queued or being flushed. Once flushed,
// it owns one complete read window; a terminal send failure owns neither.
if oldestWritten == 0 {

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.

[correctness — confirmed] The admitted/queued state (writtenAt==0, waiting==false) grants unlimited consecutive read-window renewals, so a dead connection with a blocked write stays open for the request's full ctx deadline instead of one readTimeout — diverging from the PR's own stated design of "retain the stale idle timeout".

Scenario: probe-less backend, readTimeout=20s. The writeLoop blocks in conn.Write/Flush against a peer that stopped reading; the flush deadline is the batch's earliest future deadline (backend.go:629-637), e.g. a 10-minute remote-lock RPC (defaultRemoteLockTimeout = 10m, pkg/lockservice/cfg.go:30). Every read timeout finds writtenAt==0 && !waiting → writePending=true → conn.Read restarts with a fresh full window. The dead connection is kept open ~10 minutes (pre-PR bound: one readTimeout), delaying reset/failover for every caller multiplexed on this backend.

Comment thread pkg/common/morpc/backend.go Outdated
oldest := int64(0)
writePending := false
for _, f := range rb.mu.futures {
if f.send.internal || f.send.stream || f.oneWay {

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.

[correctness] The fresh-read-window fix covers only unary requests; stream traffic on probe-less backends with a read timeout remains exposed to the exact idle-time-charging bug this PR fixes.

Scenario: pkg/cnservice/cnclient/client.go:106 sets WithBackendReadTimeout(120s) with no liveness probe and uses NewStream (client.go:128-129). A stream request written 119s into an idle 120s read window is invisible to pendingRequestReadWindow (skips f.send.stream, never consults rb.mu.activeStreams) → oldest==0 && !writePending → keepDataConnectionAfterReadTimeout returns false → the connection is closed ~1s after admission — the same root cause the PR names, surviving for the stream half of the transport. Not a regression, but the bug class remains live for production CN-CN pipeline traffic.

Comment thread pkg/common/morpc/backend.go Outdated
return rb.livenessMu.pendingSince
}

func (rb *remoteBackend) pendingRequestReadWindow() (int64, bool) {

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.

[simplification] This adds a second, parallel data-path-progress tracker (per-future writtenAt for probe-less backends) alongside the existing livenessMu.pendingSince machinery (probe backends), with divergent publication points and reset rules: different data sources (future scan vs pending map), timestamps (post-Flush vs pre-Write), refresh semantics (immutable per-future vs recordDataProgress resetting on any read progress), and reset behavior (resetDataProgress clears livenessMu on reconnect; futures rely on makeAllWaitingFutureFailed). A maintainer fixing a timeout bug in one path can silently miss the other; the per-future scan could serve both modes, or at minimum a comment should tie the two trackers together.

Comment thread pkg/common/morpc/backend.go Outdated
}
} else {
for _, f := range written {
if !f.send.internal && !f.send.stream && !f.oneWay &&

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.

[simplification] The user-unary predicate (!internal && !stream && !oneWay) is copy-pasted here and at the pendingRequestReadWindow scan (line 1495), near-missing the pre-existing trackLiveness variant at line 697. Three sites must agree for read-window accounting to stay sound: a future counted by the scan but never stamped by the writeLoop reads as perpetually write-pending (dead connection kept alive indefinitely); a future stamped but not scanned loses its window. A single func (f *Future) isUserUnary() bool removes the drift risk.

Comment thread pkg/common/morpc/backend.go Outdated
// deadline that is already mostly consumed when the next request arrives.
// Idle time is not request latency: give newly written data one complete
// read window before declaring its transport stalled.
var oldestWritten int64

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.

[simplification] keepDataConnectionAfterReadTimeout interleaves the probe and probe-less policies behind three separate probe-nil dispatch points, leaving a shadowed duplicate zero-check whose meaning differs per mode: in probe-less mode the oldestWritten==0 case returns at lines 1367-1369, so the shared if oldestWritten == 0 { return true } at line 1373 is unreachable in that mode and means the opposite (unconditional keep) for probe mode; the if livenessProbe == nil { return false } at 1380 cuts the shared tail again. Splitting into two per-mode functions sharing a withinReadWindow helper expresses the same behavior flat.

Comment thread pkg/common/morpc/backend.go Outdated
// Record only transport-complete writes. A request that merely
// reached the userspace buffer must not extend the read window
// when Flush ultimately fails.
f.writtenAt.Store(rb.livenessTick())

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.

[efficiency] The flush-success loop calls rb.livenessTick() (a time.Now-backed call) and re-evaluates loop-invariant option checks once per future instead of once per flushed batch. Hoisting tick := rb.livenessTick() and the readTimeout>0 && livenessProbe==nil check above the for-range loop does the same job with one clock read per batch and stamps the batch with a single consistent flush timestamp.

}, txnOperator)

s.asyncUpgradeTenantTask(ctx)
drainUpgradeTenants(ctx, s.newTenantUpgradePass(ctx))

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.

[simplification] Five tests repeat the identical drain-then-assert-barrier block (drainUpgradeTenants(ctx, s.newTenantUpgradePass(ctx)) plus a hand-copied ctx.Err() polarity assertion) at lines 340, 416, 477, 541, 600 with copied message strings. The next test author must reverse-engineer which polarity to copy, and changing the barrier convention touches five sites. A small drainToBarrier(t, ctx, s, wantCompleted bool) helper encodes it once.

for _, count := range expected {
remaining += count
}
timer := time.NewTimer(10 * time.Second)

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.

[simplification] The 10-second timer+select hang-guard is hand-rolled twice inline (lines 379-386, 406-412) and the same deadline is separately hard-coded in requireQuery (line 125). Three copies of the same deadline drift independently, and each new synchronization point re-pastes the 8-line block; a waitOrFatal(t, ch, msg) helper plus one named constant (as pkg/bootstrap's tenantUpgradeTestHangTimeout does) removes the duplication.

Close the review findings on the read-timeout window design by restoring
one invariant: every admitted user request owns exactly one complete
read window, starting at admission and restarted once at its successful
flush; a terminal send failure owns none.

- an admitted-but-unflushed unary request now charges its window from
  admission (f.send.createAt), so a write blocked against a dead peer is
  bounded to one window instead of renewing the connection until the
  request deadline
- stream messages get the same protection through one backend-level
  lastStreamFlushAt stamp: a stream write admitted late in an idle read
  window is no longer charged the idle time (CN-CN pipeline client)
- keepDataConnectionAfterReadTimeout is split into per-mode policies
  sharing withinReadWindow; the shadowed mode-dependent zero-check is
  gone, the user-unary predicate is one Future method, the flush loop
  reads the clock once per batch, and the two data-progress trackers
  cross-reference each other

Also de-risk the tests the PR de-flaked: TestScheduler no longer arms
the wall-clock 10s vacuum recheck (its behavior moves to a dedicated
fake-clock test), the scheduler hang guards share one constant/helper,
the bootstrap drain-to-barrier idiom is one helper, and the preview
scheduling stack collapses to the timeout-policy wrapper plus the
context-taking core.

Co-Authored-By: Claude Fable 5 <[email protected]>

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

Deep-reviewed exact head d8912942bf9799d4924471471eb9d9e9a91a35eb against base/merge-base c46d897e9645b80178568ef0783dd8e99e527222, including the full eight-file diff, all historical reviews/inline comments, and the delta after the last reviewed head 99e9d6c499f74e5dabe43aed1431c21cb5fd630a. The earlier queued-write, stream-coverage, scheduler-timer, helper, and preview-seam findings are closed in the current source. The ordinary bug-fix scope is exempt from the feature design gate, but the MORPC timeout lifecycle is R3.

Q1 is closed for the new state: Future ownership remains ref-counted and exactly released, while writtenAt and lastStreamFlushAt are bounded scalars. Q3 is also closed: no new accumulating container was added, and the test observer is capacity-bounded with nonblocking overflow detection. Q2 is not closed because the independent unary and stream windows are combined as an OR: a newer stream flush can keep an already-expired unary request generation alive, contradicting the oldest-window invariant and restoring load-sensitive timeout renewal on a production client that mixes both traffic classes.

Exact-head CI has no failed check. Local exact-head focused MORPC tests passed at -count=10, and each of the three changed timeout tests passed separately under -race -count=20 with the required native artifacts. A deterministic mixed-traffic counterexample fails on the current head as described inline. No other blocker was found in the bootstrap pass extraction, frontend timeout/core separation, or merge-scheduler test synchronization closures.

if rb.withinReadWindow(now, rb.pendingRequestReadWindow()) {
return true
}
return rb.withinReadWindow(now, rb.atomic.lastStreamFlushAt.Load())

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] Do not let a fresh stream stamp rescue an already-expired unary window. pendingRequestReadWindow() can return a nonzero but expired start; line 1394 then falls through to this stream check, so a recent stream flush returns true even though the oldest unary has exceeded its response window. This is reachable on the probe-less txn MORPC client: it configures a 30s read timeout and uses the same backend pool for unary Send and NewStream(..., false). If one unary response stalls for 30s while concurrent transaction streams continue to flush, repeated stream stamps can keep that dead generation alive beyond the promised bound and delay reset/failover. I reproduced it deterministically on this exact head with one waiting=true unary stamped exactly one timeout old plus a fresh lastStreamFlushAt; keepDataConnectionAfterReadTimeout returns true. Preserve the oldest-window rule by distinguishing “no unary window” from “expired unary window” and consult the stream stamp only in the former case; add the mixed unary+stream regression because the existing tests exercise the classes separately.

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.

Fixed in e827077. The finding is valid: the policy now treats any nonzero unary window as authoritative and consults lastStreamFlushAt only when no unary response window exists. Added the deterministic mixed counterexample (expired flushed unary + fresh stream must close) and the inverse control (terminal unary send failure owns no window, so a live stream remains valid). The counterexample failed before the production change and passed after it; focused race count=100, full pkg/common/morpc normal and race, pkg/txn/rpc, go vet, and the original embedded-cluster regression under race all passed locally.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Post-fix deep review at e827077:

  • Accepted the active request-change finding. The first-principles invariant is now: the oldest outstanding unary response window is authoritative for a connection generation; stream activity is a fallback only when no unary owns a response window.
  • Counterexamples closed: an expired flushed unary cannot be rescued by a fresh stream or newer unary admission; a terminal unary send failure owns no response window and therefore does not suppress a healthy stream; pure unary, pure stream, idle, internal, one-way, cancellation, and exact-boundary controls remain covered.
  • Lifecycle audit: no new goroutine, container, or wait; Future ownership/refcount is unchanged; the added state is bounded atomic scalars and the future scan is cold-path O(live futures). Q1/Q2/Q3 are closed after the mixed-traffic precedence fix.
  • Performance: the follow-up adds only one local branch on the read-timeout fault path. The PR hot-path cost remains one flush timestamp store per response-expecting unary (and one backend scalar store per stream batch), with no extra allocation or lock.
  • The bootstrap pass extraction, frontend timeout/core split, and merge-scheduler deterministic barriers were rechecked; no additional blocker found.

Fresh evidence after the fix: focused regression normal count=100 and race count=100; full pkg/common/morpc normal and race; pkg/txn/rpc; go vet for both; and TestIssue26640ClusterRestoreRebindsSubscriptionPrivileges under race. All passed. The previous exact-head green CI and owning-package evidence for the untouched bootstrap/frontend/merge closures remain semantically valid. Ready for re-review; not waiting for the newly triggered CI.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed exact head e827077 against base c46d897. The previous mixed unary/stream blocker is closed: any extant unary window is now authoritative, so neither a fresh stream flush nor a newer admission can rescue an expired oldest unary; terminal send failures correctly own no window and still allow a healthy stream fallback. I rechecked timestamp publication, Future reuse/release, cancellation, close/reset, and the probe-enabled path. Q1-Q3 are closed: ownership remains ref-counted/backend-close bounded, waits retain independent context/transport bounds, and the new state is bounded atomic scalars plus a cold scan of the existing live-future set. The bootstrap pass extraction, frontend timeout/core split, and merge scheduler barrier/fake-clock changes preserve production behavior and remove the load-sensitive test oracles. Exact-head Ubuntu/x86 UT, coverage, compose/standalone BVT, build, and SCA checks are green. No remaining blocker found.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed exact head e827077 against base c46d897. The previous mixed unary/stream blocker is closed: any extant unary window is now authoritative, so neither a fresh stream flush nor a newer admission can rescue an expired oldest unary; terminal send failures correctly own no window and still allow a healthy stream fallback. I rechecked timestamp publication, Future reuse/release, cancellation, close/reset, and the probe-enabled path. Q1-Q3 are closed: ownership remains ref-counted/backend-close bounded, waits retain independent context/transport bounds, and the new state is bounded atomic scalars plus a cold scan of the existing live-future set. The bootstrap pass extraction, frontend timeout/core split, and merge scheduler barrier/fake-clock changes preserve production behavior and remove the load-sensitive test oracles. Exact-head Ubuntu/x86 UT, coverage, compose/standalone BVT, build, and SCA checks are green. No remaining blocker found.

@XuPeng-SH
XuPeng-SH merged commit edd17ec into matrixorigin:main Sep 2, 2026
17 of 21 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/fix-ut-lifecycle-determinism branch September 2, 2026 07:34
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What changed

- give each ordinary MORPC unary request a complete read-timeout window
from admission/flush, instead of charging it for socket-idle time before
the request arrived
- distinguish admitted, successfully flushed, terminal-send-failed, and
expired requests while preserving established idle, internal, and
one-way behavior and giving stream writes their own bounded fallback
window
- make tenant-upgrade tests execute the observable pass directly, bound
every wait, and retain one end-to-end periodic-loop test
- make the merge scheduler test synchronize at the exact
executor/table-check boundary, use deterministic resource admission, and
prevent the test observer from blocking the scheduler
- separate frontend scheduling-preview computation from its production
100 ms best-effort latency policy so correctness tests do not race CI
descheduling

## Root cause and design

The embedded-cluster failure was not a restore or privilege failure.
`CREATE ACCOUNT` began during an already-running socket `Read` window
and inherited only the remainder of a configured 20-second timeout.
Merely increasing the timeout therefore could not guarantee a newly
admitted request a full response window.

For a normal response-expecting unary request, the backend now models
four relevant states:

1. admitted/queued or being flushed: retain the stale idle timeout
because work is already pending;
2. successfully flushed: start one full response window at the
successful flush timestamp;
3. terminal send failure: do not extend the connection lifetime;
4. expired response window: close the stalled backend; a newer admission
cannot rescue it.

The timestamp is published before the terminal send-completion flag. The
timeout scanner reads that flag before the timestamp, so it cannot
observe an old zero timestamp paired with the new success flag. The hot
path adds one atomic store only for normal unary traffic after a
successful flush; the cold timeout path scans the existing
lifecycle-bounded future set. Internal, one-way, probe-enabled,
cancellation, and close semantics remain unchanged. Probe-less streams
use one backend-level last-successful-flush window only when no unary
response window exists; an expired unary remains authoritative.

The other failures had the same broad symptom but different mechanisms:
correctness depended on a 20 ms asynchronous timer, host/cgroup memory
plus 3/5 ms scheduler polling, or a production 100 ms best-effort
preview timeout. Race instrumentation and package-parallel CI load can
delay those operations without changing their business result. Tests now
synchronize on observable state transitions, carry bounded parent
contexts, and explicitly distinguish expected cancellation from a hang
deadline.

The lifecycle audit found no new unbounded state or waits: future
ownership remains reference-counted and backend-close bounded; the
timeout scan covers only existing live futures; merge observation is
nonblocking and overflow-checked; every new test wait has a 10-second
guard.

Fixes matrixorigin#27963

## Test plan

Passed before rebase:

- MORPC state matrix under race:
`TestReadTimeoutDoesNotChargeIdleTimeToNewRequest` (`-count=100`)
- actual MORPC request tracking under race:
`TestReadTimeoutTracksRequestsWithoutLivenessProbe` (`-count=50`)
- merge scheduler under race: `TestScheduler` (`-count=100`)
- frontend strict-pool path under race:
`TestDirectSessionStrictPoolWithoutLabelSelectorFailsClosed`
(`-count=50`)
- all seven tenant-upgrade tests separately under race (`-count=20`
each)
- full package tests: `pkg/common/morpc`, `pkg/bootstrap`,
`pkg/frontend`, and `pkg/vm/engine/tae/db/merge`
- full `pkg/common/morpc` package under race
- targeted `go vet` for all four owning packages
- real embedded-cluster regression under race:
`TestAuthenticatedTestsReuseBaseCluster` and
`TestIssue26640ClusterRestoreRebindsSubscriptionPrivileges`

Rebased cleanly onto current `main` (`3f6856cc5f`). The two new upstream
commits touched only frontend code, so the affected closure was rerun
after rebase:

- full `pkg/frontend`: passed (13.974 s)
- strict-pool frontend counterexample under race, `-count=50`: passed
(1.296 s)
- full `pkg/bootstrap`: passed (18.523 s)
- `go vet ./pkg/frontend ./pkg/bootstrap`: passed
- real embedded-cluster regressions under race: passed (36.040 s)
- `git diff --check`: passed

No SQL result, wire API, or planner contract changes are introduced, so
no SQL BVT case is required; the embedded-cluster tests exercise the
public transport/session path directly.

CI reruns for the unrelated failures on matrixorigin#27949 and matrixorigin#27946 were triggered
separately; this PR does not wait for those reruns.

Post-review deterministic-clock closure (99e9d6c):

- removed the remaining 25/50 ms wall-clock oracle from TestScheduler;
policy composition now uses a lifetime longer than the test hang guard
- added TestSchedulerPolicyPatchExpirationUsesInjectedClock to prove
in-place policy merging, exact-deadline validity, and removal
immediately after the injected clock crosses the deadline
- focused normal tests passed; both scheduler tests passed separately
under race detection with count 100; the full merge package passed

---------

Co-authored-by: Claude Fable 5 <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What changed

- give each ordinary MORPC unary request a complete read-timeout window
from admission/flush, instead of charging it for socket-idle time before
the request arrived
- distinguish admitted, successfully flushed, terminal-send-failed, and
expired requests while preserving established idle, internal, and
one-way behavior and giving stream writes their own bounded fallback
window
- make tenant-upgrade tests execute the observable pass directly, bound
every wait, and retain one end-to-end periodic-loop test
- make the merge scheduler test synchronize at the exact
executor/table-check boundary, use deterministic resource admission, and
prevent the test observer from blocking the scheduler
- separate frontend scheduling-preview computation from its production
100 ms best-effort latency policy so correctness tests do not race CI
descheduling

## Root cause and design

The embedded-cluster failure was not a restore or privilege failure.
`CREATE ACCOUNT` began during an already-running socket `Read` window
and inherited only the remainder of a configured 20-second timeout.
Merely increasing the timeout therefore could not guarantee a newly
admitted request a full response window.

For a normal response-expecting unary request, the backend now models
four relevant states:

1. admitted/queued or being flushed: retain the stale idle timeout
because work is already pending;
2. successfully flushed: start one full response window at the
successful flush timestamp;
3. terminal send failure: do not extend the connection lifetime;
4. expired response window: close the stalled backend; a newer admission
cannot rescue it.

The timestamp is published before the terminal send-completion flag. The
timeout scanner reads that flag before the timestamp, so it cannot
observe an old zero timestamp paired with the new success flag. The hot
path adds one atomic store only for normal unary traffic after a
successful flush; the cold timeout path scans the existing
lifecycle-bounded future set. Internal, one-way, probe-enabled,
cancellation, and close semantics remain unchanged. Probe-less streams
use one backend-level last-successful-flush window only when no unary
response window exists; an expired unary remains authoritative.

The other failures had the same broad symptom but different mechanisms:
correctness depended on a 20 ms asynchronous timer, host/cgroup memory
plus 3/5 ms scheduler polling, or a production 100 ms best-effort
preview timeout. Race instrumentation and package-parallel CI load can
delay those operations without changing their business result. Tests now
synchronize on observable state transitions, carry bounded parent
contexts, and explicitly distinguish expected cancellation from a hang
deadline.

The lifecycle audit found no new unbounded state or waits: future
ownership remains reference-counted and backend-close bounded; the
timeout scan covers only existing live futures; merge observation is
nonblocking and overflow-checked; every new test wait has a 10-second
guard.

Fixes matrixorigin#27963

## Test plan

Passed before rebase:

- MORPC state matrix under race:
`TestReadTimeoutDoesNotChargeIdleTimeToNewRequest` (`-count=100`)
- actual MORPC request tracking under race:
`TestReadTimeoutTracksRequestsWithoutLivenessProbe` (`-count=50`)
- merge scheduler under race: `TestScheduler` (`-count=100`)
- frontend strict-pool path under race:
`TestDirectSessionStrictPoolWithoutLabelSelectorFailsClosed`
(`-count=50`)
- all seven tenant-upgrade tests separately under race (`-count=20`
each)
- full package tests: `pkg/common/morpc`, `pkg/bootstrap`,
`pkg/frontend`, and `pkg/vm/engine/tae/db/merge`
- full `pkg/common/morpc` package under race
- targeted `go vet` for all four owning packages
- real embedded-cluster regression under race:
`TestAuthenticatedTestsReuseBaseCluster` and
`TestIssue26640ClusterRestoreRebindsSubscriptionPrivileges`

Rebased cleanly onto current `main` (`3f6856cc5f`). The two new upstream
commits touched only frontend code, so the affected closure was rerun
after rebase:

- full `pkg/frontend`: passed (13.974 s)
- strict-pool frontend counterexample under race, `-count=50`: passed
(1.296 s)
- full `pkg/bootstrap`: passed (18.523 s)
- `go vet ./pkg/frontend ./pkg/bootstrap`: passed
- real embedded-cluster regressions under race: passed (36.040 s)
- `git diff --check`: passed

No SQL result, wire API, or planner contract changes are introduced, so
no SQL BVT case is required; the embedded-cluster tests exercise the
public transport/session path directly.

CI reruns for the unrelated failures on matrixorigin#27949 and matrixorigin#27946 were triggered
separately; this PR does not wait for those reruns.

Post-review deterministic-clock closure (99e9d6c):

- removed the remaining 25/50 ms wall-clock oracle from TestScheduler;
policy composition now uses a lifetime longer than the test hang guard
- added TestSchedulerPolicyPatchExpirationUsesInjectedClock to prove
in-place policy merging, exact-deadline validity, and removal
immediately after the injected clock crosses the deadline
- focused normal tests passed; both scheduler tests passed separately
under race detection with count 100; the full merge package passed

---------

Co-authored-by: Claude Fable 5 <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What changed

- give each ordinary MORPC unary request a complete read-timeout window
from admission/flush, instead of charging it for socket-idle time before
the request arrived
- distinguish admitted, successfully flushed, terminal-send-failed, and
expired requests while preserving established idle, internal, and
one-way behavior and giving stream writes their own bounded fallback
window
- make tenant-upgrade tests execute the observable pass directly, bound
every wait, and retain one end-to-end periodic-loop test
- make the merge scheduler test synchronize at the exact
executor/table-check boundary, use deterministic resource admission, and
prevent the test observer from blocking the scheduler
- separate frontend scheduling-preview computation from its production
100 ms best-effort latency policy so correctness tests do not race CI
descheduling

## Root cause and design

The embedded-cluster failure was not a restore or privilege failure.
`CREATE ACCOUNT` began during an already-running socket `Read` window
and inherited only the remainder of a configured 20-second timeout.
Merely increasing the timeout therefore could not guarantee a newly
admitted request a full response window.

For a normal response-expecting unary request, the backend now models
four relevant states:

1. admitted/queued or being flushed: retain the stale idle timeout
because work is already pending;
2. successfully flushed: start one full response window at the
successful flush timestamp;
3. terminal send failure: do not extend the connection lifetime;
4. expired response window: close the stalled backend; a newer admission
cannot rescue it.

The timestamp is published before the terminal send-completion flag. The
timeout scanner reads that flag before the timestamp, so it cannot
observe an old zero timestamp paired with the new success flag. The hot
path adds one atomic store only for normal unary traffic after a
successful flush; the cold timeout path scans the existing
lifecycle-bounded future set. Internal, one-way, probe-enabled,
cancellation, and close semantics remain unchanged. Probe-less streams
use one backend-level last-successful-flush window only when no unary
response window exists; an expired unary remains authoritative.

The other failures had the same broad symptom but different mechanisms:
correctness depended on a 20 ms asynchronous timer, host/cgroup memory
plus 3/5 ms scheduler polling, or a production 100 ms best-effort
preview timeout. Race instrumentation and package-parallel CI load can
delay those operations without changing their business result. Tests now
synchronize on observable state transitions, carry bounded parent
contexts, and explicitly distinguish expected cancellation from a hang
deadline.

The lifecycle audit found no new unbounded state or waits: future
ownership remains reference-counted and backend-close bounded; the
timeout scan covers only existing live futures; merge observation is
nonblocking and overflow-checked; every new test wait has a 10-second
guard.

Fixes matrixorigin#27963

## Test plan

Passed before rebase:

- MORPC state matrix under race:
`TestReadTimeoutDoesNotChargeIdleTimeToNewRequest` (`-count=100`)
- actual MORPC request tracking under race:
`TestReadTimeoutTracksRequestsWithoutLivenessProbe` (`-count=50`)
- merge scheduler under race: `TestScheduler` (`-count=100`)
- frontend strict-pool path under race:
`TestDirectSessionStrictPoolWithoutLabelSelectorFailsClosed`
(`-count=50`)
- all seven tenant-upgrade tests separately under race (`-count=20`
each)
- full package tests: `pkg/common/morpc`, `pkg/bootstrap`,
`pkg/frontend`, and `pkg/vm/engine/tae/db/merge`
- full `pkg/common/morpc` package under race
- targeted `go vet` for all four owning packages
- real embedded-cluster regression under race:
`TestAuthenticatedTestsReuseBaseCluster` and
`TestIssue26640ClusterRestoreRebindsSubscriptionPrivileges`

Rebased cleanly onto current `main` (`3f6856cc5f`). The two new upstream
commits touched only frontend code, so the affected closure was rerun
after rebase:

- full `pkg/frontend`: passed (13.974 s)
- strict-pool frontend counterexample under race, `-count=50`: passed
(1.296 s)
- full `pkg/bootstrap`: passed (18.523 s)
- `go vet ./pkg/frontend ./pkg/bootstrap`: passed
- real embedded-cluster regressions under race: passed (36.040 s)
- `git diff --check`: passed

No SQL result, wire API, or planner contract changes are introduced, so
no SQL BVT case is required; the embedded-cluster tests exercise the
public transport/session path directly.

CI reruns for the unrelated failures on matrixorigin#27949 and matrixorigin#27946 were triggered
separately; this PR does not wait for those reruns.

Post-review deterministic-clock closure (99e9d6c):

- removed the remaining 25/50 ms wall-clock oracle from TestScheduler;
policy composition now uses a lifetime longer than the test hang guard
- added TestSchedulerPolicyPatchExpirationUsesInjectedClock to prove
in-place policy merging, exact-deadline validity, and removal
immediately after the injected clock crosses the deadline
- focused normal tests passed; both scheduler tests passed separately
under race detection with count 100; the full merge package passed

---------

Co-authored-by: Claude Fable 5 <[email protected]>

This branch was previously deployed

1 inactive deployment
ci — 9e588702 Deployed Sep 2, 2026 by XuPeng-SH via Matrixone Utils CI / Coverage #50082
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Ubuntu/x86 race UT fails unrelated timing and HAKeeper tests under CI load

4 participants