Repository navigation
fix(hakeeper): decouple schedule command progress from heartbeats - #26765
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.
Blocking finding:
managedHAKeeperClient.GetScheduleCommands introduces a check/use gap around c.mu.client. prepareClient releases c.mu before line 720 reacquires it through getClient; in that interval the concurrently running heartbeat can return a reset-worthy error and resetClient can set c.mu.client = nil. getClient then legitimately returns nil and line 721 dereferences client.commandPollSupported, panicking the CN/TN process. This interleaving is newly made routine by this PR because poll and heartbeat deliberately share the same managed client concurrently.
Please make acquisition/capability inspection nil-safe and retry against the current client snapshot when it was concurrently cleared. The regression should use barriers around prepare/reset/capability inspection with the real managedHAKeeperClient; the current fake service clients bypass this layer, so the focused race suite cannot expose the panic.
Coverage gap: TestCNCommandPollProgressesWhileHeartbeatIsBlocked returns an empty batch and only asserts that GetScheduleCommands was entered. It would still pass if CN discarded every successful poll response. Please return a real CN command with an observable side effect and assert application plus poll/heartbeat deduplication, matching the TN end-to-end assertion and the issue acceptance criterion.
I otherwise found the bounded single-poll ownership, cancellation join, read-only RSM lookup, stable per-batch Raft index, legacy capability negotiation, and degraded-path-only metrics coherent. Focused normal tests passed, and all newly added command-path tests passed under -race -count=5.
|
Addressed the review findings and reworked the delivery semantics at the protocol boundary in e042cbe:
Validation: all five affected packages pass, targeted race tests pass with count=3, golangci-lint reports 0 issues, TestPreparedParams passes after the protocol change, and TestBasicCluster passes. |
|
Resolved all four blocking findings in
Added deterministic regressions for generation inheritance, identical-command multiplicity, stale ACK ordering, commit-point target revival, expired/live targets, rejected candidate leakage, accepted endpoint replacement, and the invariant that repeated log heartbeats do not drive activation. Validation on the pushed head:
@aptend please re-review the updated head. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep review of head bf7551d. Comment-only review; no code was changed.
P1 — GET_SCHEDULE_COMMANDS is still coupled to a blocked heartbeat handler
hakeeperClient.getScheduleCommands uses the same hakeeperClient.client as SendCNHeartbeat and SendTNHeartbeat. getRPCClient configures exactly one MORPC backend per HAKeeper address with WithClientInitBackends(..., 1) and WithClientMaxBackendPerHost(1). On the server, goetty invokes the MORPC message handler synchronously for each connection, and Service.handleRPCRequest calls handleCNHeartbeat or handleTNHeartbeat inline; those handlers wait in addCNStoreHeartbeat or addTNStoreHeartbeat for the Raft proposal. If that server-side handler is the blocked part of the heartbeat, the queued GET_SCHEDULE_COMMANDS request cannot be read or dispatched until the heartbeat handler returns. The poll worker therefore still waits behind the heartbeat timeout, so the PR does not provide independent progress for the issue acceptance case. The new CN/TN tests use fake clients whose heartbeat and poll methods are independent and do not exercise this transport serialization. This needs an independent backend/connection or an async dispatch design with ordering proof, plus a real MORPC regression where the heartbeat handler blocks before its response.
Relevant paths: pkg/logservice/hakeeper_client.go getScheduleCommands, pkg/logservice/client.go getRPCClient, pkg/logservice/service.go handleRPCRequest and handleCNHeartbeat/handleTNHeartbeat.
P2 — A permanent worker and ticker are added per CN/TN, with continuous polling during an outage
controlTask always starts commandTask, and commandTask always creates a one-second ticker even when no command poll is needed. This adds one goroutine and one timer wakeup per CN/TN in healthy idle operation, contrary to the performance claim that healthy steady state adds no goroutine. When a heartbeat fails, commandPollNeeded remains true after poll failures, so every CN/TN continues one read RPC per second for the entire outage. At fleet scale this is O(CN+TN) periodic wakeups and read requests and can amplify an already overloaded or unavailable HAKeeper. Please quantify and bound this cost, or make the degraded retry load explicitly part of the operational contract.
Validation: affected package tests passed; focused race tests passed for hakeeper, logservice, cnservice, and tnservice; no source changes were made.
|
Addressed both findings in P1 — transport independence:
P2 — bounded lifecycle and degraded load:
The PR performance section now states the worker and lazy extra connection explicitly instead of claiming no added goroutine. Validation: real MORPC regression; focused CN/TN tests; focused race ( |
aptend
left a comment
There was a problem hiding this comment.
Reviewed latest head 20a2470, including the independent MORPC polling transport, client-generation shutdown/reset races, CN/TN timer and wakeup state machines, bounded degraded retry behavior, command deduplication, cancellation, and idle-path resource bounds. No remaining correctness or lifecycle blocker found.
|
Systematic follow-up pushed as
Final validation on this head: affected-package normal and full package-wide race tests passed; focused race repetitions passed; original @aptend please re-review the new protocol-identity follow-up. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep review of cd505ee399 found two blocking issues:
[P1] Refresh the binary delivery capability before using it to gate the independent poll. GetScheduleCommands returns an empty batch locally while commandDeliverySupported is false (pkg/logservice/hakeeper_client.go:816-825). That bit is populated by the initial CHECK_HAKEEPER, or promoted only after a response has CommandPollSupported=true (pkg/logservice/hakeeper_client.go:1588-1594). CN/TN heartbeat responses publish only the phase-two poll bit and never the binary CommandDeliverySupported bit (pkg/logservice/service.go:591-608,622-639). A client connected to an old HAKeeper can therefore keep the same managed generation while MORPC transparently reconnects to the upgraded server: its successful phase-one heartbeats still leave the local delivery bit false. The replicated barrier can then enable because the service advertises ACK support, but if the first post-cutover heartbeat blocks, every hedge remains a local no-op. Heartbeat deadline errors deliberately do not reset the generation, so the original starvation can persist indefinitely. Please publish/consume the binary bit independently of the phase-two bit (or re-run capability admission on transport reconnection), and add a regression covering old admission -> transparent upgraded reconnect -> phase-one heartbeat -> enabled protocol with blocked heartbeat.
[P1] The inner managed-client retry loop defeats the claimed one-read-per-second outage bound. Each outer poll has a 3s context, but GetScheduleCommands retries EOF/connection-close/NoHAKeeper errors after hakeeperClientRetryInterval (10ms) until that context expires (pkg/logservice/hakeeper_client.go:805-833,1153-1158,1224-1232). Once a 3s call returns, the start-to-start scheduler computes a zero delay and immediately starts another call. With an unavailable HAKeeper or immediately refused connections, each CN/TN can therefore perform roughly 100 reconnect/query attempts per second continuously, not one attempt per second; fleet fan-out can amplify an outage and impede recovery. The poll path needs a single/bounded transport attempt per cadence (or an explicit retry budget whose attempts, not just outer calls, satisfy the load bound), plus a persistent-unavailability test that counts connection/request attempts.
Validation completed on this exact head: full tests, focused concurrency tests with -race -count=3, full-package -race, go vet, and go build all pass for pkg/pb/logservice, pkg/hakeeper, pkg/logservice, pkg/cnservice, and pkg/tnservice. These are state-machine/failure-ordering gaps not exercised by the current green suite. GitHub does not allow requesting changes on my own PR, so this is submitted as COMMENTED; please treat both P1 items as blocking.
aptend
left a comment
There was a problem hiding this comment.
Reviewed latest head 0829fee. The recovery probe now performs one bounded outer-owned attempt, preserves the independent poll transport, handles old-server NotSupported responses compatibly, and removes stale capability-cache coupling. Stable command identity, snapshot migration, ACK ordering, single-flight ownership, and shutdown/cancellation invariants remain intact. No remaining correctness or lifecycle blocker found.
|
Both P1 findings were valid and are fixed in The fix is based on retry/ownership invariants rather than refreshing another cache:
Regressions cover:
Final focused concurrency validation passed for both core cases with @aptend please re-review the latest head |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep review of head ec9edaf. Comment-only review because GitHub does not allow requesting changes on my own PR.
P1 — Phase-one is not closed over HAKeeper membership admission
The first activation entry is already incompatible with an old HAKeeper RSM: the old Update switch panics on the unknown EnableCommandDeliveryUpdate tag. However, tryEnableCommandDelivery checks only the HAKeeper voters/non-voters in the checker-state snapshot at pkg/logservice/store.go:918-940, then proposes phase one at lines 960-965. In the same checker cycle, hakeeperCheck runs healthCheck before this check (pkg/logservice/store_hakeeper_check.go:271-287), and healthCheck can enqueue AddReplica/StartReplica work for a live legacy LogService that is not yet present in that snapshot.
A concrete rolling-upgrade interleaving is:
- The current HAKeeper members are upgraded, while a legacy LogService D remains a non-member.
- A member expires; healthCheck schedules D as its replacement.
- The stale membership snapshot still contains only upgraded members, so phase one commits.
- D applies the already-issued StartReplica command and joins the HAKeeper shard.
If D catches up through the log, its old RSM panics on the phase-one tag. If it joins from a later snapshot, protobuf ignores the new delivery fields and D participates with legacy schedule-command semantics, so replicated state can diverge. The phase-two commit-time membership check is too late because phase one is the first incompatible entry.
Please close membership admission over the one-way capability transition: either gate every live LogService that can be selected as a HAKeeper replacement, or make AddReplica/StartReplica admission reject a binary without this capability once preparation can begin. The regression should deterministically interleave replacement scheduling with phase one and cover both log catch-up and snapshot join.
The two latest fixes otherwise resolve the previous blockers: degraded polling now uses only the admitted managed generation, performs one outer-owned attempt without the 10ms discovery/reset loop, and probes the endpoint directly so an in-place old-to-new server upgrade is not hidden by stale capability state. Old servers return ErrNotSupported compatibly.
Validation on this exact head:
- all seven focused command-delivery tests passed normally
- adaptive race stress passed: fast tests at count=100, CN blocked-heartbeat at count=33, TN blocked-heartbeat at count=32
- full normal and full race tests passed for pkg/pb/logservice, pkg/hakeeper, pkg/logservice, pkg/cnservice, and pkg/tnservice
- go build, go vet, and git diff --check passed
No second correctness, lifecycle, hang, OOM, or performance blocker found. CI is still running at submission time.
aptend
left a comment
There was a problem hiding this comment.
Reviewed latest head ec9edaf. Heartbeat is now the sole managed-generation discovery/reset owner; polling snapshots only an admitted generation, performs one bounded transport attempt per cadence, and cannot close or replace a concurrent heartbeat generation. MORPC backend recovery and generation-scoped cleanup preserve liveness without retry fan-out. No remaining correctness or lifecycle blocker found.
|
Systemic membership-admission closure pushed in
Final-head validation passed: focused race ( |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep review completed on exact head ca20f38 against merge-base d0057b3. No blocking correctness, liveness, lifecycle, or performance issue found.
The latest membership closure is coherent:
- phase one is attempted before the checker can schedule new membership work;
- the RSM independently refuses phase one while any HAKeeper Add/Start admission is still pending, closing leader/read snapshot races;
- pre-barrier admission checks include current voters/non-voters and every live LogStore candidate, then the replicated barrier clears capability observations that could differ after old-snapshot recovery;
- once preparing, Add/Start work for the HAKeeper shard is retained until the target advertises the new binary capability, while unrelated safe commands in the same batch can still progress;
- phase two evaluates current CN/TN liveness at the RSM commit point, so a service revival between leader precheck and commit cannot bypass the barrier.
I also rechecked the complete delivery state machine rather than only ca20f38: exact BatchID ACK cannot delete a rolled generation; stable per-command IDs suppress inherited replay without suppressing a later post-ACK identical command; poll/heartbeat response reordering is serialized; TN shutdown advances acknowledgement through generation rollover before termination; old snapshots migrate deterministically; old GET_SCHEDULE_COMMANDS servers return ErrNotSupported compatibly; heartbeat remains the sole managed-generation discovery/reset owner; and the independent no-retry MORPC poll connection has one request in flight and is joined through the CN/TN control worker.
The supported boundaries remain important: process restart is intentionally at-least-once, and HAKeeper downgrade after the phase-one one-way barrier is unsupported. Neither is hidden by the implementation.
Performance review: the normal path adds one joined worker and bounded atomic/channel/timer bookkeeping around heartbeat, but no poll RPC or extra Raft proposal after a healthy response. Degraded polling is one outer-owned transport attempt per cadence with no 10ms reconnect amplification. The PR body phrase that the normal heartbeat adds only atomic transitions is slightly too strong because wakeup/timer arm-disarm also occurs; this is a documentation precision nit, not a performance blocker.
Validation on this exact head:
- adaptive exact race stress: independent MORPC progress x100; single-attempt ownership x100; CN blocked-heartbeat progress x33; TN blocked-heartbeat progress x32; shutdown ACK transport x100;
- package-wide race passed serially for pkg/pb/logservice, pkg/hakeeper, pkg/logservice, pkg/cnservice, and pkg/tnservice;
- latest main c72224b has no overlapping changes in the owning paths, synthetic merge is clean, git diff --check is clean, and the detached review worktree remained unmodified.
Because this is my own PR, GitHub does not permit an approval review; this COMMENTED review records the no-blocker conclusion.
LeftHandCold
left a comment
There was a problem hiding this comment.
Deep review completed on exact head 391a91b2d367562e02b3dc330914f0fa9d85c0c2 (semantic PR head ca20f380f9, merge-base 7f0c723dc2). No blocking correctness, liveness, lifecycle, performance, or normal-path regression issue found.
I rechecked the complete protocol and failure ordering: durable BatchID acknowledgement and stable per-command identity across generation rollover; deterministic old-snapshot migration; phase-one HAKeeper membership/admission closure and phase-two commit-time CN/TN capability evaluation; fail-closed legacy behavior during preparation; independent single-attempt MORPC polling without managed-generation reset/fan-out; poll/heartbeat serialization; and TN ShutdownStore termination only after the exact acknowledgement is observed committed. Resource ownership is bounded: one joined worker and one lazy timer per service, one independent poll client, at most one poll in flight, and close/reset are generation-scoped.
Focused validation passed for lost-response durability, activation commit-state/admission races, real independent-MORPC progress, generation-scoped reset, CN/TN blocked-heartbeat progress, inherited-command replay suppression, and TN shutdown acknowledgement transport. git diff --check is clean, the detached review worktree is unchanged, and there are no unresolved review threads.
The documented boundaries—process restart remains at-least-once and downgrade after the one-way phase-one barrier is unsupported—are explicit and do not constitute hidden regressions.
|
Tick the box to add this pull request to the merge queue (same as
|
What type of PR is this?
Which issue(s) this PR fixes
Fixes #26566
What this PR does / why we need it
A CN/TN schedule command was historically removed from HAKeeper replicated state when a heartbeat proposal committed. If the RPC response was delayed, lost, or blocked after commit, the command had already been consumed and neither heartbeat retry nor a second read could recover it.
This PR closes the delivery loop at the protocol boundary:
BatchIDit accepted in a later heartbeat. HAKeeper removes only that generation, so a stale ACK cannot delete newer work.ScheduleCommandID. Rollover preserves inherited IDs and assigns new IDs only to newly scheduled work. CN/TN can therefore skip inherited work while still executing a later command whose payload intentionally equals an earlier command.StartReplicaretains its stronger retry-until-state-confirmed rule. TNShutdownStoreis applied only after its exact ACK commits.Compatibility and failure semantics
GET_SCHEDULE_COMMANDSprobe is rejected withErrNotSupported; the new client treats that as an empty compatible result and retains the connection for an in-place upgrade.Performance and resource bounds
NoHAKeeperimmediately; it does not enter discovery or construct a replacement. Heartbeat remains the only reconnect/failover owner.O(CN+TN)and one poll send per cadence/service; healthy load is zero.Validation
Validated through final review; latest head is
ca20f380f9:pkg/pb/logserviceandpkg/logservice-race -count=100after the final refinementpkg/pb/logservice,pkg/hakeeper,pkg/logservice,pkg/cnservice, andpkg/tnserviceon the final headpkg/tests/txnexecutor TestPreparedParams -count=3regression andpkg/embed TestBasicClustergo buildandgo vetfor all five owning packagesgit diff --check