Skip to content

fix(hakeeper): decouple schedule command progress from heartbeats - #26765

Merged
XuPeng-SH merged 16 commits into
mainfrom
agent/fix-hakeeper-command-progress
Aug 7, 2026
Merged

XuPeng-SH merged 16 commits into
mainfrom
agent/fix-hakeeper-command-progress

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Improvement
  • API-change
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

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:

  1. Heartbeat and read-only polling both read one durable per-service pending batch after activation. Producing an RPC response does not remove it.
  2. CN/TN acknowledges the exact BatchID it accepted in a later heartbeat. HAKeeper removes only that generation, so a stale ACK cannot delete newer work.
  3. Every pending command has a stable 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.
  4. Bootstrap StartReplica retains its stronger retry-until-state-confirmed rule. TN ShutdownStore is applied only after its exact ACK commits.
  5. A two-phase replicated capability barrier enables the protocol only after current HAKeeper members, every live LogStore eligible for admission, and live CN/TN targets support it, with no earlier HAKeeper admission still pending. The replicated barrier clears pre-upgrade LogStore capability observations; later HAKeeper Add/Start commands remain pending until their target advertises support after the barrier. Activation evaluates current targets in the RSM at commit time; old and recovered snapshots are migrated deterministically.
  6. Polling uses a lazy MORPC connection independent from the heartbeat connection, so a synchronous blocked heartbeat handler cannot head-of-line block command reads.
  7. Heartbeat exclusively owns HAKeeper discovery and managed-generation replacement. Polling only uses an already admitted generation, performs one MORPC send attempt per outer cadence, and never invalidates the heartbeat connection after a poll failure.
  8. CN/TN serialize command application, drop stale/cancelled responses, and join the single command worker during shutdown.

Compatibility and failure semantics

  • New client + old HAKeeper: healthy delivery stays on the legacy heartbeat path. During a degraded heartbeat, one additive GET_SCHEDULE_COMMANDS probe is rejected with ErrNotSupported; the new client treats that as an empty compatible result and retains the connection for an in-place upgrade.
  • In-place HAKeeper upgrade: recovery probing is not gated by a capability cached from an older connection. The current endpoint is authoritative, so a blocked post-upgrade heartbeat cannot leave polling permanently short-circuited.
  • Mixed HAKeeper replicas and LogStores: the new replicated update is not proposed until every current voter/non-voter and every live admission candidate advertises support, and earlier HAKeeper admissions have completed. After the barrier, an unsupported Add/Start target is retained without blocking safe commands in the same batch.
  • Mixed CN/TN binaries: activation remains blocked by a live legacy target. After activation, an old target is not destructively served; its work stays pending until it upgrades.
  • Lost heartbeat or poll response: the unacknowledged batch remains replicated and is redelivered.
  • Poll/heartbeat race or generation rollover: stable command IDs provide at-most-once application per service process for ordinary commands. Restart remains intentionally at-least-once.
  • Old snapshots with only batch IDs receive command IDs on the next replicated tick/acknowledged heartbeat. A separate migration marker prevents the earlier batch-only format from being mistaken for fully migrated state.
  • Protocol activation is one-way. Rolling forward is supported; downgrading HAKeeper binaries after activation is not supported.

Performance and resource bounds

  • Healthy steady state has one joined command worker per CN/TN, no active poll timer, no poll RPC, and no extra Raft proposal. The normal heartbeat path adds only atomic state transitions.
  • The first degraded read is stably jittered per service over 750ms-1s. Subsequent reads use a one-second start-to-start cadence because the pull protocol has no server wakeup and a longer backoff violates the command-progress invariant.
  • There is one lazy independent poll connection and at most one poll RPC in flight per service. Its MORPC retry policy is disabled, so one outer cadence cannot expand into a 10ms reconnect loop.
  • If no managed generation is admitted, polling returns NoHAKeeper immediately; it does not enter discovery or construct a replacement. Heartbeat remains the only reconnect/failover owner.
  • A poll transport failure leaves the heartbeat generation intact. The next outer cadence gives the independent MORPC client one new attempt; a slow attempt lowers request rate and never creates overlap.
  • Fleet jitter avoids a synchronized first-poll burst. Degraded load is bounded by O(CN+TN) and one poll send per cadence/service; healthy load is zero.
  • Command-ID maps are bounded by the current pending batch. HAKeeper retains at most one pending generation per service and coalesces retry-equivalent checker output.
  • Capability negotiation runs in the existing checker cycle and is cached after the one-time transition; it is not a permanent log-heartbeat read/sort path.

Validation

Validated through final review; latest head is ca20f380f9:

  • protobuf regeneration repeated with an identical diff hash
  • full normal and package-wide race suites for pkg/pb/logservice and pkg/logservice
  • focused rolling-upgrade/blocked-heartbeat and single-attempt ownership tests with -race -count=100 after the final refinement
  • full normal and package-wide race suites for pkg/pb/logservice, pkg/hakeeper, pkg/logservice, pkg/cnservice, and pkg/tnservice on the final head
  • original pkg/tests/txnexecutor TestPreparedParams -count=3 regression and pkg/embed TestBasicCluster
  • go build and go vet for all five owning packages
  • targeted golangci-lint with the repository CI config: 0 issues
  • git diff --check

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

@mergify mergify Bot added kind/bug Something isn't working kind/enhancement labels Aug 6, 2026

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

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.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Addressed the review findings and reworked the delivery semantics at the protocol boundary in e042cbe:

  • removed the managed-client prepare/get race by using a generation-scoped client snapshot; late failures reset only the generation that failed;
  • strengthened the CN regression to apply a real command and verify poll/heartbeat exact-once behavior;
  • replaced destructive heartbeat delivery with durable pending batches plus exact BatchID acknowledgement for upgraded CN/TN;
  • added a two-phase replicated HAKeeper capability barrier for mixed-version safety;
  • preserved bootstrap StartReplica retry-until-state-confirmed semantics;
  • roll forward same-UUID pending commands into a new generation so one-shot operator dispatches are not dropped;
  • moved ack capability advertisement to CN/TN, so the generic transport cannot claim semantics its caller did not implement;
  • removed the unused CN helper reported by SCA.

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.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Resolved all four blocking findings in bf7551dbb8.

  • Generation rollover: CN/TN now retain a bounded per-command fingerprint multiset for the current unacknowledged lineage. When generation M inherits commands from N, only newly appended occurrences execute. State is cleared only by the exact acknowledged generation; stale/out-of-order heartbeat responses cannot erase a newer lineage. Bootstrap StartReplica keeps its retry-until-state-confirmed contract.
  • Phase-two linearization: the replicated activation entry now carries deterministic timeout ticks, and every RSM evaluates its current CN/TN store state at the entry commit point. A legacy service heartbeat committed between leader precheck and activation therefore blocks activation.
  • Hot path: log heartbeats only advertise the cached enabled bit. Activation progress moved to the existing HAKeeper checker cycle, reuses its checker snapshot, performs no UUID sorting, and adds no worker or healthy-heartbeat read/proposal path.
  • Candidate capability isolation: capability bits are published only after IsHAKeeper accepts the candidate, and an accepted candidate replaces both bits rather than inheriting state from a rejected/previous endpoint.

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:

  • full affected-package tests: pkg/hakeeper, pkg/logservice, pkg/cnservice, pkg/tnservice
  • focused affected tests: -race -count=10
  • package-wide race for all four affected packages
  • go vet for those packages plus pkg/pb/logservice
  • protobuf regeneration reproducibility and git diff --check

@aptend please re-review the updated head.

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

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Addressed both findings in 20a24703d7.

P1 — transport independence:

  • GET_SCHEDULE_COMMANDS now lazily owns a separate MORPC client/backend from the heartbeat transport. Separate goroutines are no longer assumed to imply separate progress on a synchronous per-connection server.
  • The poll client preserves the accepted generation address plus injected backend/client options, and is created/closed under generation-local ownership; close-vs-first-poll cannot leak a client.
  • Added a real MORPC regression whose CN heartbeat handler blocks before writing its response. The schedule-command read returns BatchID 7 while that handler is still blocked, proving progress comes from another connection rather than fake-client independence.

P2 — bounded lifecycle and degraded load:

  • Removed the permanent one-second ticker. Each CN/TN retains one bounded command worker so independent progress has a single joinable owner, but healthy idle has no active command timer and no poll RPC.
  • The first hedge remains exactly one second. Errors, empty reads, and repeats of the same unacknowledged BatchID back off through 2/4/8/16 seconds to a stable UUID-jittered 24-30 second interval. A genuinely new BatchID restores the one-second cadence. There is still at most one poll in flight per service.
  • This changes sustained degraded read load from 1 RPC/s/service to at most one RPC per 24-30s/service after convergence, while UUID jitter avoids a synchronized fleet retry spike.
  • A successful-heartbeat generation resets degraded backoff, so a recovered service cannot carry an old 30-second delay into a later blocked heartbeat.

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 (logservice -count=5, CN/TN -count=3); full pkg/logservice; targeted golangci-lint for all three packages with 0 issues; git diff --check.

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

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.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Systematic follow-up pushed as cd505ee399 after re-checking the two delivery invariants that the previous head still violated.

  • Removed the 24-30s degraded backoff. With a pull-only protocol and no server wakeup, an empty/repeated read does not prove that no command will arrive next; backing off breaks the 1s progress contract. The worker now uses stable 750ms-1s first-poll jitter and a 1s start-to-start cadence, with one connection and one in-flight RPC only while heartbeat delivery is degraded.
  • Replaced payload-fingerprint lineage with replicated per-command identities. HAKeeper preserves IDs for commands inherited by a rollover and assigns a new ID to newly scheduled work, including a later command with identical payload. This closes both replay of inherited work and accidental suppression of legitimate repeated work.
  • Added an independent old-snapshot migration marker because a snapshot from the batch-only implementation can have BatchID populated but no command IDs. Missing/partial/duplicate IDs are repaired deterministically in the RSM; the read-only endpoint fails closed until a batch has complete stable IDs.
  • Added deterministic regressions for empty read followed by new work, migration plus append in the same Raft entry, batch-only snapshot recovery, duplicate/partial ID repair, and delayed old ACK racing with later identical work.

Final validation on this head: affected-package normal and full package-wide race tests passed; focused race repetitions passed; original TestPreparedParams -count=3 and TestBasicCluster passed; protobuf regeneration is reproducible; build, vet, targeted CI-config golangci-lint (0 issues), and diff check passed.

@aptend please re-review the new protocol-identity follow-up.

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

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.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Both P1 findings were valid and are fixed in 0829feefd8 + ec9edaf756.

The fix is based on retry/ownership invariants rather than refreshing another cache:

  • Removed the response-side capability cache and its local admission gate. A degraded read now asks the currently connected endpoint directly, so old admission followed by transparent/in-place server upgrade cannot leave polling permanently short-circuited.
  • An old HAKeeper's default ErrNotSupported response is treated as a compatible empty result. The real rolling-upgrade test exposed that logservice error decoding previously panicked on this code; ErrNotSupported now round-trips normally.
  • Removed the managed client's 10ms retry loop and disabled MORPC retry on the independent poll client. The command worker is the only cadence owner.
  • Tightened ownership further: polling never prepares/replaces a managed HAKeeper generation. With no admitted generation it returns NoHAKeeper; heartbeat alone owns discovery/failover. A poll transport failure also no longer closes the heartbeat generation. Each later cadence gives the independent MORPC client exactly one new send attempt.

Regressions cover:

  1. old endpoint admission -> same endpoint upgrades -> heartbeat handler blocks -> independent poll returns the durable command while heartbeat is still blocked;
  2. two consecutive EOF cadences produce exactly two sends total, zero managed reconnects, and do not close the heartbeat generation;
  3. polling with no admitted generation performs zero discovery/reconnect attempts;
  4. old-server ErrNotSupported conversion does not panic.

Final focused concurrency validation passed for both core cases with -race -count=100; affected full normal/race suites passed serially, build/vet passed, targeted golangci-lint reports 0 issues, and the original TestPreparedParams -count=3 plus TestBasicCluster regressions passed. The one discarded full-suite run failed only because I incorrectly ran normal and race copies concurrently against the tests' fixed gossip port; both suites passed when rerun serially.

@aptend please re-review the latest head ec9edaf756.

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

  1. The current HAKeeper members are upgraded, while a legacy LogService D remains a non-member.
  2. A member expires; healthCheck schedules D as its replacement.
  3. The stale membership snapshot still contains only upgraded members, so phase one commits.
  4. 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 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.

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.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Systemic membership-admission closure pushed in ca20f380f9:

  • activation now establishes phase one before the checker can schedule new membership work;
  • phase one waits for every current HAKeeper member, every live LogStore admission candidate, live CN/TN targets, and completion of earlier HAKeeper admissions;
  • the replicated barrier normalizes pre-upgrade LogStore capability observations, avoiding snapshot-dependent RSM branches;
  • HAKeeper Add/Start voter and non-voter commands are retained until the target advertises support after the barrier, while safe commands in the same batch continue to be delivered;
  • the transition-only scans are removed from steady state; Log heartbeat adds only a batch-hit admission lookup and no extra RPC, goroutine, or unbounded registry.

Final-head validation passed: focused race (pkg/hakeeper x50, pkg/logservice x20), full normal and full -race across pkg/pb/logservice, pkg/hakeeper, pkg/logservice, pkg/cnservice, and pkg/tnservice, plus build, vet, and git diff --check.

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

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.

@mergify

mergify Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@XuPeng-SH XuPeng-SH mentioned this pull request Aug 11, 2026
1 of 7 tasks

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/enhancement kind/refactor Code refactor kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Serial HAKeeper heartbeat RPC can starve schedule-command delivery

4 participants