Skip to content

Fix logservice client fallback from slow replica addresses - #25289

Merged
mergify[bot] merged 6 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix-logservice-stale-replica-fallback
Jul 3, 2026
Merged

mergify[bot] merged 6 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix-logservice-stale-replica-fallback

Conversation

@jiangxinmeng1

@jiangxinmeng1 jiangxinmeng1 commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) this PR fixes:

issue #25274 #25277

What this PR does / why we need it:

This PR improves logservice client creation when candidate replica addresses include stale or unreachable endpoints.

Previously, connectToLogService tried replica addresses sequentially. If one address accepted a TCP connection but did not respond, client creation could wait until the outer context deadline before trying later
candidates.

Changes:

  • Keep the existing shuffled address order.
  • Start connection attempts with staggered fallback instead of strict sequential dialing.
  • Apply a per-address attempt timeout.
  • Return the first successfully connected client.
  • Cancel remaining attempts and close losing clients after a winner is selected.
  • Add a regression test covering a slow/unresponsive address followed by a reachable address.

This reduces the impact of stale or slow replica addresses returned by discovery/gossip without changing HAKeeper or gossip behavior.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Logservice client: staggered fallback when replica addresses are slow/unresponsive

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Shuffle replica addresses and use staggered connection attempts instead of strict sequential
 dialing.
• Enforce per-address attempt timeouts and return the first successfully connected client.
• Add a regression test to ensure fast fallback from a hanging TCP endpoint.
Diagram

graph TD
  A["newClient()"] --> B["connectToLogService()"] --> C["shuffle addresses"] --> D["connectToLogServiceAddresses()"]
  D --> E{Winner?
client connected}
  D --> F["launch attempt (goroutine)"] --> G["connectToLogServiceAddress()"] --> H["getRPCClient() + RW/RO handshake"]
  F -. "per-attempt timeout" .-> D
  E -->|yes| I["cancel others + close losers"]
  E -->|no| D
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Sequential dialing with per-address timeout
  • ➕ Much simpler control flow (no goroutines/results channel)
  • ➕ Still avoids waiting for the outer context deadline on a single bad address
  • ➖ Still serializes attempts; worst-case latency adds up across multiple stale endpoints
  • ➖ Does not opportunistically connect to later addresses while the first is hanging
2. Move timeout/handshake deadline into getRPCClient()
  • ➕ Centralizes connection deadlines in one place
  • ➕ Avoids adding more orchestration logic in client creation
  • ➖ Does not solve the core problem if the hang happens after TCP connect but before higher-level handshake
  • ➖ May affect other callers of getRPCClient() with different expectations
3. Bounded parallelism (N concurrent attempts)
  • ➕ More robust if many endpoints are stale; avoids waiting fallback delay repeatedly
  • ➕ Can cap resource usage explicitly while still parallelizing
  • ➖ More parameters/tuning complexity (choose N, scheduling strategy)
  • ➖ Potentially higher load burst on startup vs staggered approach

Recommendation: The chosen staggered fallback (Happy-Eyeballs-style) is a good balance: it preserves randomized address order, reduces tail latency when an early address hangs, and limits connection bursts via a short fallback delay. Keep this approach, but consider making the attempt timeout/fallback delay configurable (or at least documented) if operators need to tune for different environments.

Files changed (2) +235 / -39

Bug fix (1) +140 / -39
client.goStaggered concurrent dialing with per-address timeouts and cleanup +140/-39

Staggered concurrent dialing with per-address timeouts and cleanup

• Refactors client creation to shuffle candidate replica addresses and connect via staggered concurrent attempts rather than strict sequential dialing. Each attempt runs with its own timeout; the first successful connection cancels remaining attempts and closes losing clients. Adds helper functions to isolate single-address connection logic and to safely stop/drain the fallback timer.

pkg/logservice/client.go

Tests (1) +95 / -0
client_test.goRegression test for fast fallback from a hanging replica endpoint +95/-0

Regression test for fast fallback from a hanging replica endpoint

• Adds a test that starts a TCP listener which accepts connections but never responds, then verifies client creation quickly falls back to a reachable logservice address. Introduces a small helper to run the hanging TCP server and temporarily reduces the fallback delay to keep the test fast.

pkg/logservice/client_test.go

@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Leaking non-winning clients 🐞 Bug ☼ Reliability
Description
connectToLogServiceAddresses can leak RPC clients when multiple connection attempts succeed: a
losing goroutine may successfully send its client into the buffered results channel before
cancellation, and that client is never closed because the winner path returns immediately without
draining/closing remaining successes. This can accumulate open connections/goroutines/FDs over time
and violates the intended “close losing clients” behavior.
Code

pkg/logservice/client.go[R581-623]

+			if err == nil {
+				select {
+				case results <- result{client: c}:
+				case <-ctx.Done():
+					if closeErr := c.close(); closeErr != nil {
+						logutil.Error("failed to close the client", zap.Error(closeErr))
+					}
				}
-				e = err
+				return
			}
-		} else {
-			// TODO: add a test to check whether it works when there is no truncated
-			// LSN known to the logservice.
-			if err := c.connectReadWrite(ctx); err == nil {
-				return c, nil
-			} else {
-				if err := c.close(); err != nil {
-					logutil.Error("failed to close the client", zap.Error(err))
-				}
-				e = err
+			select {
+			case results <- result{err: err}:
+			case <-ctx.Done():
			}
+		}()
+	}
+
+	var lastErr error
+	launched, active := 0, 0
+	for active > 0 || launched < len(addresses) {
+		if active == 0 {
+			launch(addresses[launched])
+			launched++
+			active++
+			continue
+		}
+
+		var fallback <-chan time.Time
+		var timer *time.Timer
+		if launched < len(addresses) {
+			timer = time.NewTimer(logServiceConnectFallbackDelay)
+			fallback = timer.C
+		}
+
+		select {
+		case r := <-results:
+			stopConnectFallbackTimer(timer)
+			active--
+			if r.client != nil {
+				cancel()
+				wg.Wait()
+				return r.client, nil
+			}
Evidence
Attempt goroutines can enqueue a successful client into the buffered results channel without
closing it; the winner path cancels and returns immediately, leaving any already-enqueued successful
clients unreachable but still open (since only the ctx-canceled branch closes them, and
client.close() is otherwise never invoked).

pkg/logservice/client.go[559-641]
pkg/logservice/client.go[655-657]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`connectToLogServiceAddresses` returns immediately after receiving the first successful `result{client: c}`. If another goroutine already sent a successful client into the buffered `results` channel before the cancellation happens, that “losing” client is never closed.

### Issue Context
- Each attempt goroutine sends a successful client to `results` and returns without closing it.
- The main select loop cancels and returns on the first success, but does not drain `results` to close any other successful clients already queued.
- `client.close()` is the only cleanup path for these clients.

### Fix Focus Areas
- pkg/logservice/client.go[559-641]
- pkg/logservice/client.go[655-657]

### Suggested fix approach
- After selecting a winning client, cancel the shared context as you do today.
- Drain any already-available `results` entries (and/or wait for remaining goroutines to report) and close any `r.client` where `r.client != winner`.
 - One simple pattern: after `cancel()`, loop `active-1` times receiving from `results` (or use a `for active > 0` drain loop) and call `close()` on any non-nil `r.client`.
 - Alternatively, use an `atomic.Bool`/`sync.Once` winner selection in goroutines: if not the winner, close the client before returning, regardless of send timing.
- Ensure you still `wg.Wait()` before returning.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Comment thread pkg/logservice/client.go Resolved
@jiangxinmeng1

Copy link
Copy Markdown
Contributor Author

https://github.com/Mergifyio queue

@mergify

mergify Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-03 08:01 UTC · Rule: main · triggered by @jiangxinmeng1 with the @mergifyio queue command
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-07-03 13:51 UTC · at 1590852b9a9089a5b8473de44d5c8c841557798a · squash

This pull request spent 5 hours 49 minutes 6 seconds in the queue, including 1 hour 12 minutes 7 seconds running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • github-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-neutral = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-skipped = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64

@mergify mergify Bot added the queued label Jul 3, 2026

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants