Skip to content

fix(logservice): isolate HAKeeper client from caller timeout - #25869

Merged
mergify[bot] merged 4 commits into
matrixorigin:mainfrom
LeftHandCold:agent/hakeeper-timeout-isolation
Jul 20, 2026
Merged

mergify[bot] merged 4 commits into
matrixorigin:mainfrom
LeftHandCold:agent/hakeeper-timeout-isolation

Conversation

@LeftHandCold

@LeftHandCold LeftHandCold commented Jul 19, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

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

Which issue(s) this PR fixes:

issue #25868

What this PR does / why we need it:

Managed HAKeeper operations share one MORPC client. Before this change, every request error reset and closed that shared client, including context.Canceled and context.DeadlineExceeded from one caller.

In TKE mergerun job 88168675381, a connection-ID allocation reached its frontend deadline and closed the established HAKeeper connection. Unrelated connection admission, CN heartbeat, task service, and cluster refresh requests were then forced through synchronous HAKeeper rediscovery. The SSB q1.3 connection failed during that cascade even though HAKeeper recovered immediately and the next query succeeded.

A caller context error means only that request can no longer wait; it does not establish that the shared transport is broken. MORPC's backend read loop independently detects EOF, connection errors, and read timeouts and reconnects the transport.

This change:

  • returns caller cancellation/deadline errors unchanged without closing the shared HAKeeper client;
  • applies that rule consistently to all managed HAKeeper operations;
  • preserves existing reset/reconnect/retry behavior for EOF, connection-close, NoHAKeeper, backend timeout, and every other non-context error;
  • completes MORPC cleanup when Send fails before queue admission, so the Future is removed from the backend map instead of retaining its request indefinitely;
  • recycles payload-bearing logservice responses that arrive after their Future has already been removed;
  • does not change connection IDs, allocation batches, public APIs, configuration, timeouts, retry counts, or normal success paths.

The regression coverage proves:

  • caller cancellation/deadline keeps the exact managed HAKeeper client reusable;
  • EOF send errors still reset, rebuild, and retry the client;
  • an admission-stage context error leaves no Future in MORPC's backend map (the test fails on unmodified code with one retained Future);
  • the orphan-response callback releases the RPCResponse payload back through its existing pool lifecycle.

Review follow-up and safety boundary

The requested review at pullrequestreview-4730633356 identified two valid lifecycle gaps. Commit ab3fdb94d4 addresses both with focused cleanup changes:

  1. A Future is registered before doSend. If enqueue fails, no write-loop owner exists, so the synchronous send-error path now performs the single matching send-completion/unref before closing it.
  2. A late payload response whose Future/Stream is already absent now uses WithBackendFreeOrphansResponse and the existing RPCResponse.Release implementation.

Normal queued sends are unchanged: only the write loop calls send completion. Normal responses are unchanged: the caller still owns RPCResponse.Release. The orphan callback runs only when MORPC finds neither a Future nor a Stream, so it does not overlap normal response ownership.

Testing

Tested with MatrixOne macOS CGo header/link settings:

  • go test ./pkg/common/morpc -run '^TestSendContextErrorReleasesFuture$' -count=20
  • go test -race ./pkg/common/morpc -run '^TestSendContextErrorReleasesFuture$' -count=20
  • focused HAKeeper/orphan-response tests: normal count=10, race count=10
  • go test ./pkg/common/morpc -count=1
  • go test -race ./pkg/common/morpc -count=1
  • go test ./pkg/logservice -count=1
  • go test -race ./pkg/logservice -count=1
  • go test ./pkg/frontend ./pkg/cnservice ./pkg/proxy -run '^$' -count=1
  • go build ./pkg/common/morpc ./pkg/logservice ./pkg/frontend ./pkg/cnservice ./pkg/proxy
  • go vet ./pkg/common/morpc ./pkg/logservice
  • 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 →

@LeftHandCold

Copy link
Copy Markdown
Collaborator Author

Completed a first-principles pre-push review of the complete PR diff at d55ab8706c45b7bab96a5f335a8cae60d7670d4a.

Scope and semantic boundary

  • Diff is limited to pkg/logservice/hakeeper_client.go and its package test.
  • No frontend, trace, StatementInfo, timeout, retry-count, allocation-batch, ID-value, API, or configuration behavior changes.
  • The original caller still receives context.Canceled / context.DeadlineExceeded. This PR isolates that caller-scoped failure; it does not claim the original caller can never time out.

Error-path review

  • AllocateID and AllocateIDByKeyWithBatch keep the outer err != nil branch, so context errors return before any ID-cache mutation.
  • EOF, UnexpectedEOF, expected connection-close, NoHAKeeper, backend timeout, and all other non-context errors still reset the shared client.
  • Existing EOF tests prove reset, reconstruction, and retry still occur.
  • The new test proves both context error classes preserve the exact client instance and a following allocation uses it successfully.

Concurrency and lifecycle review

  • No goroutine, channel, timer, lock, state field, generation, or wait edge is added.
  • Avoiding close() on a caller deadline prevents one request from invalidating concurrent heartbeat, cluster, task, and connection-ID users.
  • MORPC closes/removes the timed-out request future independently. Its backend read loop still detects transport EOF/read errors and the configured read timeout and schedules reconnect, so a genuinely failed transport is not made permanent by this change.
  • Managed-client ownership and shutdown ownership are unchanged.

Validation

  • Focused normal tests: count=10, PASS.
  • Focused race tests: count=20, PASS.
  • Full ./pkg/logservice: normal and race, PASS.
  • frontend/CN/proxy test compilation, PASS.
  • logservice/frontend/CN/proxy build, PASS.
  • go vet ./pkg/logservice, PASS.
  • git diff --check, PASS.

Remote verification:

  • PR is ready, targets main, and is mergeable.
  • Remote head equals the locally tested commit.
  • Only the two intended logservice files are present.

No blocking correctness, leak, hang, ownership, retry-regression, cache-corruption, or unintended cross-module semantic issue found. Full GitHub CI is still in progress.

@matrix-meow matrix-meow added the size/S Denotes a PR that changes [10,99] lines label Jul 19, 2026
@mergify

mergify Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Queued — the merge queue status continues in this comment ↓.

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

Codex automated review

The timeout-isolation change is incomplete for MORPC send-stage context failures and also introduces response-pool churn for late replies.

P1 - Clean up futures when Send returns a caller context error (pkg/logservice/hakeeper_client.go:920)

This predicate skips client reset for errors from both c.client.Send and future.Get. In MORPC, Send creates and inserts a Future before attempting to enqueue it. If the write queue is full and the caller context expires, doSend returns the context error before enqueueing; remoteBackend.send only calls f.Close, without messageSent/unRef. Because Future.Close releases only after its reference reaches zero, the Future remains in the backend's futures map and retains the request. Keeping the shared client alive means repeated admission-time cancellations can grow this map and memory without bound. The new test stubs the send function and does not exercise this path. The reset exemption must distinguish send-stage failures, or MORPC must release the Future on this path.

P2 - Recycle orphan responses when retaining timed-out clients (pkg/logservice/hakeeper_client.go:920)

Once the client is retained after a caller timeout, late HAKeeper replies can reach MORPC's orphan-response path. getRPCClient enables payload responses but does not configure WithBackendFreeOrphansResponse; MORPC therefore does not call RPCResponse.Release() for these late replies. Under repeated timeouts this bypasses the response pool and causes avoidable allocations and GC pressure. Configure the orphan-response release callback when constructing this client.

@LeftHandCold

Copy link
Copy Markdown
Collaborator Author

Addressed both findings from review 4730633356 in ab3fdb94d459fe33d5f8fbe024d85d3ef575b9b8.

P1 — pre-enqueue Future retention

Confirmed. getFuture inserts the Future and takes one reference before doSend. When queue admission returned the caller context error, the Future had never reached the write loop, so the old Close could not drop that reference. The synchronous failure path now calls messageSent(err) before Close, matching the ownership transition that the write loop performs only for successfully queued Futures.

Added a deterministic full-queue/canceled-context regression test. It fails before the fix with one Future left in rb.mu.futures; it passes after the fix. Normal and race runs both passed with count=20, and full MORPC normal/race suites passed.

P2 — orphan payload-response recycling

Confirmed. getRPCClient now configures WithBackendFreeOrphansResponse; the callback uses the existing RPCResponse.Release, which clears the protobuf/payload and returns the object to its originating pool. It is invoked only in MORPC's no-Future/no-Stream orphan branch, so normal response ownership remains with the caller and there is no double-release path.

Added focused callback coverage. Full pkg/logservice normal and race suites passed.

Final safety review

  • no API, configuration, timeout, retry-count, ID-allocation, or success-path changes;
  • non-context HAKeeper errors still reset/reconnect exactly as before;
  • no new goroutine, lock, channel, timer, state field, or wait dependency;
  • frontend/CN/proxy compile checks, target-package build, vet, and git diff --check all passed.

The PR description has also been updated with the two lifecycle gaps, ownership boundaries, and complete validation record.

@matrix-meow matrix-meow added size/M Denotes a PR that changes [100,499] lines and removed size/S Denotes a PR that changes [10,99] lines labels Jul 19, 2026
@LeftHandCold
LeftHandCold requested a review from gouhongshen July 19, 2026 15:18

@XuPeng-SH XuPeng-SH 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 the current head ab3fdb94d4 from the transport, lifecycle, concurrency, failure-classification, and performance angles. No blocking issue found.

The previous findings are closed:

  • A Future registered before queue admission now gets the matching send completion/unref only on synchronous doSend failure. Successfully queued Futures remain owned by the write loop, and the existing CAS prevents duplicate send completion.
  • Late payload responses with neither a Future nor a Stream now follow the existing RPCResponse.Release pool lifecycle. Normal response ownership is unchanged.
  • Caller context.Canceled and context.DeadlineExceeded no longer invalidate the shared managed HAKeeper client, while EOF, UnexpectedEOF, connection-close, NoHAKeeper, backend timeout, and other non-context errors preserve reset/reconnect behavior.

Focused regression tests passed repeatedly in normal and race modes; full MORPC normal/race passed; both modified packages build and vet cleanly; git diff --check is clean; GitHub CI is green. The change adds no success-path allocation or wait and only adds constant-time error-path cleanup/classification.

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

Codex automated review

The timeout isolation and synchronous Future cleanup are sound, but payload-response recycling misses a timeout race.

P2 - Release responses discarded while the Future still exists (pkg/logservice/client.go:929)

This callback only handles the requestDone branch where no Future/Stream is found. If a response arrives after the caller context expires but before future.Close, requestDone still finds the Future and Future.done drops the response without invoking freeResponse. Conversely, if the response was queued just before cancellation, Future.Get may select ctx.Done and Future.Close drains it without calling RPCResponse.Release. Retaining the shared client makes these late-response races reachable, so repeated timeouts bypass respPool and increase allocation/GC pressure.

@mergify mergify Bot added the queued label Jul 20, 2026
@mergify
mergify Bot merged commit 9bc6f2a into matrixorigin:main Jul 20, 2026
29 checks passed
@mergify mergify Bot removed the queued label Jul 20, 2026
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…rigin#25869)

Managed HAKeeper operations share one MORPC client. Before this change, every request error reset and closed that shared client, including `context.Canceled` and `context.DeadlineExceeded` from one caller.

In TKE mergerun job 88168675381, a connection-ID allocation reached its frontend deadline and closed the established HAKeeper connection. Unrelated connection admission, CN heartbeat, task service, and cluster refresh requests were then forced through synchronous HAKeeper rediscovery. The SSB `q1.3` connection failed during that cascade even though HAKeeper recovered immediately and the next query succeeded.

A caller context error means only that request can no longer wait; it does not establish that the shared transport is broken. MORPC's backend read loop independently detects EOF, connection errors, and read timeouts and reconnects the transport.

This change:

- returns caller cancellation/deadline errors unchanged without closing the shared HAKeeper client;
- applies that rule consistently to all managed HAKeeper operations;
- preserves existing reset/reconnect/retry behavior for EOF, connection-close, `NoHAKeeper`, backend timeout, and every other non-context error;
- completes MORPC cleanup when `Send` fails before queue admission, so the Future is removed from the backend map instead of retaining its request indefinitely;
- recycles payload-bearing logservice responses that arrive after their Future has already been removed;
- does not change connection IDs, allocation batches, public APIs, configuration, timeouts, retry counts, or normal success paths.

The regression coverage proves:

- caller cancellation/deadline keeps the exact managed HAKeeper client reusable;
- EOF send errors still reset, rebuild, and retry the client;
- an admission-stage context error leaves no Future in MORPC's backend map (the test fails on unmodified code with one retained Future);
- the orphan-response callback releases the `RPCResponse` payload back through its existing pool lifecycle.

Approved by: @volgariver6, @gouhongshen, @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…rigin#25869)

Managed HAKeeper operations share one MORPC client. Before this change, every request error reset and closed that shared client, including `context.Canceled` and `context.DeadlineExceeded` from one caller.

In TKE mergerun job 88168675381, a connection-ID allocation reached its frontend deadline and closed the established HAKeeper connection. Unrelated connection admission, CN heartbeat, task service, and cluster refresh requests were then forced through synchronous HAKeeper rediscovery. The SSB `q1.3` connection failed during that cascade even though HAKeeper recovered immediately and the next query succeeded.

A caller context error means only that request can no longer wait; it does not establish that the shared transport is broken. MORPC's backend read loop independently detects EOF, connection errors, and read timeouts and reconnects the transport.

This change:

- returns caller cancellation/deadline errors unchanged without closing the shared HAKeeper client;
- applies that rule consistently to all managed HAKeeper operations;
- preserves existing reset/reconnect/retry behavior for EOF, connection-close, `NoHAKeeper`, backend timeout, and every other non-context error;
- completes MORPC cleanup when `Send` fails before queue admission, so the Future is removed from the backend map instead of retaining its request indefinitely;
- recycles payload-bearing logservice responses that arrive after their Future has already been removed;
- does not change connection IDs, allocation batches, public APIs, configuration, timeouts, retry counts, or normal success paths.

The regression coverage proves:

- caller cancellation/deadline keeps the exact managed HAKeeper client reusable;
- EOF send errors still reset, rebuild, and retry the client;
- an admission-stage context error leaves no Future in MORPC's backend map (the test fails on unmodified code with one retained Future);
- the orphan-response callback releases the `RPCResponse` payload back through its existing pool lifecycle.

Approved by: @volgariver6, @gouhongshen, @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…rigin#25869)

Managed HAKeeper operations share one MORPC client. Before this change, every request error reset and closed that shared client, including `context.Canceled` and `context.DeadlineExceeded` from one caller.

In TKE mergerun job 88168675381, a connection-ID allocation reached its frontend deadline and closed the established HAKeeper connection. Unrelated connection admission, CN heartbeat, task service, and cluster refresh requests were then forced through synchronous HAKeeper rediscovery. The SSB `q1.3` connection failed during that cascade even though HAKeeper recovered immediately and the next query succeeded.

A caller context error means only that request can no longer wait; it does not establish that the shared transport is broken. MORPC's backend read loop independently detects EOF, connection errors, and read timeouts and reconnects the transport.

This change:

- returns caller cancellation/deadline errors unchanged without closing the shared HAKeeper client;
- applies that rule consistently to all managed HAKeeper operations;
- preserves existing reset/reconnect/retry behavior for EOF, connection-close, `NoHAKeeper`, backend timeout, and every other non-context error;
- completes MORPC cleanup when `Send` fails before queue admission, so the Future is removed from the backend map instead of retaining its request indefinitely;
- recycles payload-bearing logservice responses that arrive after their Future has already been removed;
- does not change connection IDs, allocation batches, public APIs, configuration, timeouts, retry counts, or normal success paths.

The regression coverage proves:

- caller cancellation/deadline keeps the exact managed HAKeeper client reusable;
- EOF send errors still reset, rebuild, and retry the client;
- an admission-stage context error leaves no Future in MORPC's backend map (the test fails on unmodified code with one retained Future);
- the orphan-response callback releases the `RPCResponse` payload back through its existing pool lifecycle.

Approved by: @volgariver6, @gouhongshen, @XuPeng-SH

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/test-ci size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants