Skip to content

fix: morpc client lock contention causing long blocking during CN node terminated - #23435

Merged
15 commits merged into
matrixorigin:mainfrom
XuPeng-SH:fix-rpc-lock-contention
Jan 4, 2026
Merged

15 commits merged into
matrixorigin:mainfrom
XuPeng-SH:fix-rpc-lock-contention

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Jan 3, 2026 •

Copy link
Copy Markdown
Contributor

User description

What type of PR is this?

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

Which issue(s) this PR fixes:

issue #23434

What this PR does / why we need it:

Lock Contention During Backend Creation

  • Problem: Synchronous backend creation in getBackend() caused 27 goroutines to serialize for 135 seconds when CN nodes crashed, reducing CPU utilization to 30%.
  • Solution: Implemented asynchronous backend creation using the existing global client GC mechanism, eliminating lock-held network I/O.
  • Impact: Recovery time improved from 135 seconds to 200ms (675x improvement).

Pool Saturation Immediate Failure

  • Problem: When the backend pool was full but all connections were busy/inactive, getBackend() returned ErrBackendUnavailable, causing immediate failure instead of waiting for connections to become available.
  • Solution: Changed error type to ErrBackendCreating to trigger proper retry logic, allowing requests to wait for free connections under high load.
  • Impact: Improved system availability by preventing request drops during temporary saturation.

Circuit Breaker Not Triggering on Permanent Failures

  • Problem: When backend creation repeatedly failed (e.g., permanently crashed nodes), the circuit breaker never opened because failures during async creation waits weren't recorded.
  • Solution: Added circuit breaker failure recording when auto-create timeouts or retry limits are exceeded.
  • Impact: Permanent failures now trigger circuit breaker protection, enabling fast failure and preventing wasteful retries.

PR Type

Bug fix, Enhancement


Description

  • Implement asynchronous backend creation to eliminate lock contention during CN node failures

  • Add bounded wait timeout for auto-create with circuit breaker integration for fast failure detection

  • Distinguish transient creation states from permanent unavailability via new error types

  • Enhance error classification and observability with metrics for backend health and circuit breaker state


Diagram Walkthrough

flowchart LR
  A["getBackend Request"] --> B{"Circuit Breaker<br/>Check"}
  B -->|Open| C["Return ErrCircuitOpen<br/>Fast Fail"]
  B -->|Closed/HalfOpen| D["Check Pool<br/>& Limits"]
  D -->|Backend Available| E["Return Backend<br/>Success"]
  D -->|Pool Empty| F{"Auto-Create<br/>Enabled?"}
  D -->|Pool Busy| G["Return ErrBackendCreating<br/>Trigger Wait"]
  F -->|Yes| H["Queue Async Creation<br/>Return ErrBackendCreating"]
  F -->|No| I["Return ErrNoAvailableBackend<br/>Fail Fast"]
  H --> J["Caller Retries<br/>with Bounded Wait"]
  J -->|Timeout| K["Record Failure<br/>Return ErrBackendCreateTimeout"]
  J -->|Success| E
  K --> L["Circuit Breaker<br/>May Open"]
Loading

File Walkthrough

Relevant files
Enhancement, bug fix
1 files
client.go
Implement async backend creation and bounded wait logic   
+446/-43
Tests
13 files
client_state_test.go
Add comprehensive tests for error states and transitions 
+506/-0 
client_lock_contention_test.go
Add tests for concurrent access and crash recovery scenarios
+517/-0 
client_test.go
Update existing tests for async creation behavior               
+136/-16
client_gc_test.go
Add helper for async creation and update test expectations
+40/-20 
client_autocreate_test.go
Add tests for auto-create enable/disable behavior               
+210/-0 
circuit_breaker_test.go
Update tests to pass client name parameter                             
+3/-3     
status_test.go
Add test for ErrBackendCreating status classification       
+1/-0     
rpc_test.go
Update test expectations for auto-create timeout behavior
+6/-2     
service_test.go
Update test to expect ErrBackendClosed after timeout         
+2/-2     
query_service_test.go
Add circuit breaker configuration to test client                 
+20/-1   
multi_cn_bug_test.go
Add backend warmup and adjust timeouts for async creation
+41/-7   
server_test.go
Enable auto-create by default in test client                         
+4/-1     
method_based_test.go
Enable auto-create in test configuration                                 
+3/-1     
Enhancement
13 files
circuit_breaker.go
Add GetError method and metrics reporting for state changes
+69/-3   
metrics.go
Add metrics for auto-create timeout and backend unavailable
+4/-0     
status.go
Add status classification for new error types                       
+26/-1   
morpc.go
Add prometheus metrics for backend health and circuit breaker
+48/-0   
grafana_dashboard_rpc.go
Add dashboard rows for backend health and circuit breaker metrics
+62/-0   
metrics.go
Register new RPC metrics in prometheus registry                   
+4/-0     
table_change_stream.go
Use unified error classification for retry logic                 
+7/-13   
lock_op.go
Use unified error classification for lock retry logic       
+11/-3   
rpc.go
Set bounded wait timeout for fast failure detection           
+11/-0   
sender.go
Add read timeout configuration for backend                             
+2/-1     
client.go
Set explicit read timeout instead of zero                               
+1/-1     
shardinfo.go
Set explicit read timeout instead of zero                               
+1/-1     
logtail_consumer.go
Reduce default RPC read timeout from 2 minutes to 30 seconds
+1/-1     
Bug fix
1 files
lock_table_allocator.go
Enforce minimum timeout to prevent misconfiguration           
+4/-2     
Formatting
1 files
Makefile
Fix regex patterns for context timeout/deadline checks     
+2/-2     

@qodo-code-review

qodo-code-review Bot commented Jan 3, 2026 •

Copy link
Copy Markdown

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
⚪
Resource exhaustion

Description: Asynchronous backend auto-creation can be triggered based on the backend string (via
globalClientGC.triggerCreate(c, backend)), which may enable resource-exhaustion (task
queue pressure, repeated connection attempts, and backend pool growth up to configured
limits) if an attacker can influence backend values to cause many distinct endpoints to be
enqueued/created.
client.go [721-740]

Referred Code
// No backend available in pool
canCreate := c.canCreateLocked(backend)
enableAutoCreate := c.options.enableAutoCreate
c.mu.Unlock() // Release lock before any potentially blocking operation

// Strictly gate creation on enableAutoCreate flag
if !enableAutoCreate {
	return nil, moerr.NewNoAvailableBackendNoCtx()
}

if canCreate {
	// Try to enqueue creation task with backpressure handling
	if !globalClientGC.triggerCreate(c, backend) {
		// Queue is full - fallback to existing creation path with proper bookkeeping
		return c.createBackendWithBookkeeping(backend, lock)
	}
}

// Return error to trigger retry in caller
return nil, moerr.NewNoAvailableBackendNoCtx()
Ticket Compliance
⚪
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
⚪
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review

qodo-code-review Bot commented Jan 3, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
✅ Refactor to centralize duplicated retry logic
Suggestion Impact:The commit introduces shared helper functions (isAutoCreateWaitError and handleAutoCreateWait) and updates Send(), NewStream(), and Ping() to call this centralized logic when handling backend auto-creation wait/retry conditions. While the full retry loops are still present in each method (not fully unified into a single "withRetryableBackend" wrapper), a meaningful portion of the previously duplicated retry/wait behavior was extracted and reused.

code diff:

@@ -322,6 +428,7 @@
 	policy := c.options.retryPolicy
 	var backoff time.Duration
 	retryCount := 0
+	var creationStart time.Time
 
 	for {
 		// Check circuit breaker before each retry attempt
@@ -337,13 +444,13 @@
 				return nil, err
 			}
 
-			// Handle NoAvailableBackend error - backend is being created asynchronously
-			if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {
-				// Check context first before retrying
-				select {
-				case <-ctx.Done():
-					return nil, ctx.Err()
-				default:
+			waitingForCreate := c.options.enableAutoCreate && isAutoCreateWaitError(err)
+
+			// Handle backend creation-in-progress with bounded wait
+			if waitingForCreate {
+				shouldContinue, waitErr := c.handleAutoCreateWait(ctx, backend, &creationStart, retryCount)
+				if !shouldContinue {
+					return nil, waitErr
 				}
 
 				retryCount++
@@ -364,13 +471,6 @@
 						return nil, ctx.Err()
 					case <-time.After(backoff):
 					}
-				}
-
-				if retryCount <= 3 || retryCount%10 == 0 {
-					c.logger.Debug("retrying Send after no available backend",
-						zap.String("backend", backend),
-						zap.Int("retry", retryCount),
-						zap.Duration("backoff", backoff))
 				}
 				continue
 			}
@@ -441,6 +541,7 @@
 	policy := c.options.retryPolicy
 	var backoff time.Duration
 	retryCount := 0
+	var creationStart time.Time
 
 	for {
 		// Check circuit breaker before each retry attempt
@@ -463,8 +564,15 @@
 				return nil, err
 			}
 
-			// Handle NoAvailableBackend error - backend is being created asynchronously
-			if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {
+			waitingForCreate := c.options.enableAutoCreate && isAutoCreateWaitError(err)
+
+			// Handle backend creation-in-progress with bounded wait
+			if waitingForCreate {
+				shouldContinue, waitErr := c.handleAutoCreateWait(ctx, backend, &creationStart, retryCount)
+				if !shouldContinue {
+					return nil, waitErr
+				}
+
 				retryCount++
 				// Check if max retries exceeded
 				if policy.MaxRetries > 0 && retryCount >= policy.MaxRetries {
@@ -483,13 +591,6 @@
 						return nil, ctx.Err()
 					case <-time.After(backoff):
 					}
-				}
-
-				if retryCount <= 3 || retryCount%10 == 0 {
-					c.logger.Debug("retrying NewStream after no available backend",
-						zap.String("backend", backend),
-						zap.Int("retry", retryCount),
-						zap.Duration("backoff", backoff))
 				}
 				continue
 			}
@@ -559,17 +660,18 @@
 	policy := c.options.retryPolicy
 	var backoff time.Duration
 	retryCount := 0
+	var creationStart time.Time
 
 	for {
 		b, err := c.getBackend(backend, false)
 		if err != nil {
-			// Handle NoAvailableBackend error - backend is being created asynchronously
-			if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {
-				// Check context first before retrying
-				select {
-				case <-ctx.Done():
-					return ctx.Err()
-				default:
+			waitingForCreate := c.options.enableAutoCreate && isAutoCreateWaitError(err)
+
+			// Handle backend creation-in-progress with bounded wait
+			if waitingForCreate {
+				shouldContinue, waitErr := c.handleAutoCreateWait(ctx, backend, &creationStart, retryCount)
+				if !shouldContinue {
+					return waitErr
 				}
 
 				retryCount++
@@ -590,13 +692,6 @@
 						return ctx.Err()
 					case <-time.After(backoff):
 					}
-				}
-
-				if retryCount <= 3 || retryCount%10 == 0 {
-					c.logger.Debug("retrying Ping after no available backend",
-						zap.String("backend", backend),
-						zap.Int("retry", retryCount),
-						zap.Duration("backoff", backoff))
 				}
 				continue
 			}
@@ -709,6 +804,7 @@
 
 	c.mu.Lock()
 	b, err := c.getBackendLocked(backend, lock)
+	poolSize := len(c.mu.backends[backend])
 	if err != nil {
 		c.mu.Unlock()
 		return nil, err
@@ -721,6 +817,7 @@
 	// No backend available in pool
 	canCreate := c.canCreateLocked(backend)
 	enableAutoCreate := c.options.enableAutoCreate
+	hasBackends := poolSize > 0
 	c.mu.Unlock() // Release lock before any potentially blocking operation
 
 	// Strictly gate creation on enableAutoCreate flag
@@ -728,15 +825,27 @@
 		return nil, moerr.NewNoAvailableBackendNoCtx()
 	}
 
+	creationQueued := false
 	if canCreate {
 		// Try to enqueue creation task with backpressure handling
 		if !globalClientGC.triggerCreate(c, backend) {
 			// Queue is full - fallback to existing creation path with proper bookkeeping
 			return c.createBackendWithBookkeeping(backend, lock)
 		}
-	}
-
-	// Return error to trigger retry in caller
+		creationQueued = true
+	}
+
+	if creationQueued {
+		return nil, ErrBackendCreating
+	}
+
+	if hasBackends {
+		// Pool had entries but none usable; surface as unavailable to differentiate from "creating"
+		c.metrics.backendUnavailableCounter.Inc()
+		return nil, ErrBackendUnavailable
+	}
+
+	// Pool is empty and cannot create - return ErrNoAvailableBackend to trigger wait logic
 	return nil, moerr.NewNoAvailableBackendNoCtx()
 }
 
@@ -778,7 +887,7 @@
 				zap.Int("inactive", inactiveCnt),
 				zap.Int("max", c.options.maxBackendsPerHost))
 			if !c.canCreateLocked(backend) {
-				return nil, moerr.NewNoAvailableBackendNoCtx()
+				return nil, moerr.NewBackendClosedNoCtx()
 			}
 		}
 
@@ -827,7 +936,7 @@
 	}
 	if !c.canCreateLocked(backend) {
 		c.mu.Unlock()
-		return nil, moerr.NewNoAvailableBackendNoCtx()
+		return nil, moerr.NewBackendClosedNoCtx()
 	}
 	c.mu.Unlock()
 
@@ -848,7 +957,7 @@
 	if !c.canCreateLocked(backend) {
 		// Another goroutine may have filled the pool while we were creating.
 		b.Close()
-		return nil, moerr.NewNoAvailableBackendNoCtx()
+		return nil, moerr.NewBackendClosedNoCtx()
 	}
 
 	// Apply lock if requested (only after we know the backend will be kept)
@@ -935,7 +1044,7 @@
 
 func (c *client) createBackendLocked(backend string) (Backend, error) {
 	if !c.canCreateLocked(backend) {
-		return nil, moerr.NewNoAvailableBackendNoCtx()
+		return nil, moerr.NewBackendClosedNoCtx()
 	}
 
 	b, err := c.doCreate(backend)
@@ -972,6 +1081,66 @@
 	c.metrics.poolSizeGauge.Set(float64(n))
 }
 
+func isErrBackendCreating(err error) bool {
+	if err == nil {
+		return false
+	}
+	// Compare directly since ErrBackendCreating is now a moerr error
+	return err == ErrBackendCreating || errors.Is(err, ErrBackendCreating)
+}
+
+// isAutoCreateWaitError checks if the error indicates we should wait for backend creation.
+// State mapping:
+//   - ErrBackendCreating: Backend is being created asynchronously, should wait
+//   - ErrNoAvailableBackend: Pool is empty and cannot create (at capacity), should wait
+//   - ErrBackendClosed: Backend unavailable or wait timeout exceeded, should NOT wait
+func isAutoCreateWaitError(err error) bool {
+	return isErrBackendCreating(err) ||
+		moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend)
+}
+
+// handleAutoCreateWait implements bounded wait logic for backend creation.
+// Returns:
+//   - true: should continue waiting/retrying
+//   - false: should stop (timeout exceeded or context cancelled)
+//   - error: ErrBackendCreateTimeout if timeout exceeded, ctx.Err() if context cancelled
+func (c *client) handleAutoCreateWait(ctx context.Context, backend string, creationStart *time.Time, retryCount int) (bool, error) {
+	// Check context first
+	select {
+	case <-ctx.Done():
+		return false, ctx.Err()
+	default:
+	}
+
+	// Initialize creation start time
+	if creationStart.IsZero() {
+		*creationStart = time.Now()
+	}
+
+	// Check bounded wait timeout
+	if timeout := c.options.autoCreateWaitTimeout; timeout > 0 {
+		elapsed := time.Since(*creationStart)
+		if elapsed >= timeout {
+			c.logger.Warn("auto-create backend timed out",
+				zap.String("backend", backend),
+				zap.Duration("waited", elapsed),
+				zap.Duration("timeout", timeout))
+			c.metrics.autoCreateTimeoutCounter.Inc()
+			return false, ErrBackendCreateTimeout
+		}
+	}
+
+	// Log creation wait progress (sparse logging)
+	if retryCount == 1 || retryCount%10 == 0 {
+		c.logger.Debug("waiting for backend creation",
+			zap.String("backend", backend),
+			zap.Int("retry", retryCount),
+			zap.Duration("waited", time.Since(*creationStart)))
+	}
+
+	return true, nil
+}

The retry logic for handling asynchronous backend creation is duplicated in
Send(), NewStream(), and Ping(). This should be refactored into a single helper
function to reduce redundancy and improve maintainability.

Examples:

pkg/common/morpc/client.go [341-376]
			if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {
				// Check context first before retrying
				select {
				case <-ctx.Done():
					return nil, ctx.Err()
				default:
				}

				retryCount++
				// Check if max retries exceeded (0 means unlimited)

 ... (clipped 26 lines)
pkg/common/morpc/client.go [467-495]
			if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {
				retryCount++
				// Check if max retries exceeded
				if policy.MaxRetries > 0 && retryCount >= policy.MaxRetries {
					c.logger.Warn("max retries exceeded for NewStream",
						zap.String("backend", backend),
						zap.Int("retries", retryCount),
						zap.Error(err))
					return nil, err
				}

 ... (clipped 19 lines)

Solution Walkthrough:

Before:

func (c *client) Send(ctx, backend, request) (*Future, error) {
    // ...
    for {
        b, err := c.getBackend(backend, false)
        if err != nil {
            if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {
                // ... retry logic with backoff ...
                continue
            }
            // ... other error handling ...
        }
        return b.Send(ctx, request)
    }
}

func (c *client) NewStream(ctx, backend, lock) (Stream, error) {
    // ...
    for {
        b, err := c.getBackend(backend, lock)
        if err != nil {
            if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {
                // ... duplicated retry logic with backoff ...
                continue
            }
            // ... other error handling ...
        }
        return b.NewStream(ctx)
    }
}

After:

func (c *client) withRetryableBackend(ctx, backend, lock, action) (any, error) {
    // ...
    for {
        b, err := c.getBackend(backend, lock)
        if err != nil {
            if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {
                // ... centralized retry logic with backoff ...
                continue
            }
            // ... other error handling ...
        }
        return action(b)
    }
}

func (c *client) Send(ctx, backend, request) (*Future, error) {
    res, err := c.withRetryableBackend(ctx, backend, false, func(b Backend) (any, error) {
        return b.Send(ctx, request)
    })
    return res.(*Future), err
}

func (c *client) NewStream(ctx, backend, lock) (Stream, error) {
    res, err := c.withRetryableBackend(ctx, backend, lock, func(b Backend) (any, error) {
        return b.NewStream(ctx)
    })
    return res.(Stream), err
}
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies significant code duplication across Send(), NewStream(), and Ping(), and centralizing this logic would improve maintainability and consistency.

Medium
Possible issue
✅ Add missing circuit breaker check
Suggestion Impact:The commit updated Ping’s retry/error-handling path to treat circuit breaker errors (ErrCircuitOpen and ErrCircuitHalfOpen) as immediate failures and to return the circuit breaker’s specific error via GetError, improving fast-fail behavior during retries. However, it did not add the explicit `Allow()` check at the top of each Ping retry iteration as suggested (unlike Send/NewStream), so the implementation differs from the proposed change.

code diff:

 
 	// Check circuit breaker before attempting
 	if !c.circuitBreakers.Allow(backend) {
-		return ErrCircuitOpen
+		return c.circuitBreakers.GetError(backend)
 	}
 
 	policy := c.options.retryPolicy
 	var backoff time.Duration
 	retryCount := 0
+	var creationStart time.Time
 
 	for {
 		b, err := c.getBackend(backend, false)
 		if err != nil {
-			// Handle NoAvailableBackend error - backend is being created asynchronously
-			if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {
-				// Check context first before retrying
-				select {
-				case <-ctx.Done():
-					return ctx.Err()
-				default:
+			// Handle circuit breaker errors - both open and half-open (exhausted probes) reject immediately
+			if errors.Is(err, ErrCircuitOpen) || errors.Is(err, ErrCircuitHalfOpen) {
+				return err
+			}
+
+			// Wait for backend if:
+			// 1. Auto-create enabled and waiting for creation, OR
+			// 2. ErrBackendCreating (pool has backends but all busy - wait regardless of auto-create)
+			waitingForCreate := (c.options.enableAutoCreate && isAutoCreateWaitError(err)) ||
+				isErrBackendCreating(err)
+
+			// Handle backend creation-in-progress with bounded wait
+			if waitingForCreate {
+				shouldContinue, waitErr := c.handleAutoCreateWait(ctx, backend, &creationStart, retryCount)
+				if !shouldContinue {
+					// Record circuit breaker failure on timeout
+					c.circuitBreakers.RecordFailure(backend)
+					return waitErr
 				}
 
 				retryCount++
@@ -579,6 +716,8 @@
 						zap.String("backend", backend),
 						zap.Int("retries", retryCount),
 						zap.Error(err))
+					// Record circuit breaker failure on max retries
+					c.circuitBreakers.RecordFailure(backend)
 					return err
 				}
 
@@ -590,13 +729,6 @@
 						return ctx.Err()
 					case <-time.After(backoff):
 					}
-				}
-
-				if retryCount <= 3 || retryCount%10 == 0 {
-					c.logger.Debug("retrying Ping after no available backend",
-						zap.String("backend", backend),
-						zap.Int("retry", retryCount),
-						zap.Duration("backoff", backoff))
 				}
 				continue
 			}
@@ -624,7 +756,7 @@
 
 				// Check circuit breaker after failure
 				if !c.circuitBreakers.Allow(backend) {
-					return ErrCircuitOpen
+					return c.circuitBreakers.GetError(backend)
 				}

Add a missing circuit breaker check inside the Ping method's retry loop to
ensure it fails fast, consistent with Send and NewStream.

pkg/common/morpc/client.go [549-568]

 func (c *client) Ping(ctx context.Context, backend string) error {
 	if ctx == nil {
 		panic("client Ping nil context")
 	}
 
 	// Check circuit breaker before attempting
 	if !c.circuitBreakers.Allow(backend) {
 		return ErrCircuitOpen
 	}
 
 	policy := c.options.retryPolicy
 	var backoff time.Duration
 	retryCount := 0
 
 	for {
+		// Check circuit breaker before each retry attempt
+		if !c.circuitBreakers.Allow(backend) {
+			// Don't record failure - circuit is already open
+			return ErrCircuitOpen
+		}
+
 		b, err := c.getBackend(backend, false)
 		if err != nil {
+			// Handle circuit open error without recording additional failure
+			if errors.Is(err, ErrCircuitOpen) {
+				return err
+			}
+
 			// Handle NoAvailableBackend error - backend is being created asynchronously
 			if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {
 ...

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that the Ping method's retry loop lacks a circuit breaker check, unlike Send and NewStream. Adding this check ensures consistent fast-fail behavior across all retryable methods, improving the robustness of the new error-handling logic.

Medium
General
Improve test to cover retry logic

In TestCrashedNodeRecovery, replace the direct call to c.getBackend with c.Ping
to more accurately test the complete retry and recovery mechanism.

pkg/common/morpc/client_lock_contention_test.go [231-270]

 func TestCrashedNodeRecovery(t *testing.T) {
 ...
 	var totalBlockTime atomic.Int64
 	var successCount atomic.Int32
 	var noBackendCount atomic.Int32
 
 	start := time.Now()
 
 	for i := 0; i < numGoroutines; i++ {
 		wg.Add(1)
 		go func(id int) {
 			defer wg.Done()
 
 			goroutineStart := time.Now()
+			ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
+			defer cancel()
 
-			// Try to get backend (should fail quickly)
-			b, err := c.getBackend("crashed-node", false)
+			// Use Ping to test the full retry logic
+			err := c.Ping(ctx, "crashed-node")
 
 			elapsed := time.Since(goroutineStart)
 			totalBlockTime.Add(int64(elapsed))
 
 			if err == nil {
 ...

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out that testing getBackend directly doesn't cover the full retry logic introduced in the PR. Changing the test to use c.Ping would provide a more realistic and comprehensive validation of the user-facing behavior, making the test more robust.

Medium
  • Update

@matrix-meow matrix-meow added the size/XXL Denotes a PR that changes 2000+ lines label Jan 3, 2026
@XuPeng-SH XuPeng-SH changed the title fix: MORPC client lock contention causing long blocking during CN node crashes fix: morpc client lock contention causing long blocking during CN node crashes Jan 4, 2026
@XuPeng-SH XuPeng-SH changed the title fix: morpc client lock contention causing long blocking during CN node crashes fix: morpc client lock contention causing long blocking during CN node terminated Jan 4, 2026
@qodo-code-review

Copy link
Copy Markdown

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
⚪
Metrics cardinality DoS

Description: The new circuit breaker metrics use backend as a metric label via
v2.NewRPCCircuitBreakerStateGauge(m.name, backend) /
v2.NewRPCCircuitBreakerTripsCounter(m.name, backend), which can enable a
metrics-cardinality DoS (memory/CPU exhaustion in the process and/or metrics backend) if
backend can be influenced to generate many unique values (e.g., dynamic addresses or
attacker-controlled strings).
circuit_breaker.go [399-413]

Referred Code
// reportStateChange reports circuit breaker state change to metrics
func (m *CircuitBreakerManager) reportStateChange(backend string, state CircuitState) {
	if m.name == "" {
		return
	}
	v2.NewRPCCircuitBreakerStateGauge(m.name, backend).Set(float64(state))
}

// reportTrip reports circuit breaker trip (closed -> open) to metrics
func (m *CircuitBreakerManager) reportTrip(backend string) {
	if m.name == "" {
		return
	}
	v2.NewRPCCircuitBreakerTripsCounter(m.name, backend).Inc()
}
Ticket Compliance
⚪
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
⚪
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

🔴
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status:
Comment contradicts behavior: The bounded-wait documentation states a timeout returns ErrBackendClosed, but the
implementation returns ErrBackendCreateTimeout, making the code comments misleading.

Referred Code
//   - autoCreateWaitTimeout = 0 (default): Wait until context deadline (legacy behavior)
//   - autoCreateWaitTimeout > 0: Wait up to specified duration, then return ErrBackendClosed
//

Learn more about managing compliance generic rules or creating your own custom rules

⚪
Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Low-context timeout error: ErrBackendCreateTimeout is created via moerr.NewBackendClosedNoCtx() (same code/message as
generic backend-closed), so callers may not receive actionable context distinguishing
create-timeout vs other backend-closed scenarios unless they rely on logs/metrics.

Referred Code
// ErrBackendCreateTimeout indicates that auto-create wait timeout exceeded.
// This typically means backend creation is too slow or queue congestion.
// This is a boundary condition error (NoCtx + Counter for monitoring).
// Uses ErrBackendClosed code for compatibility with existing error handling.
ErrBackendCreateTimeout = moerr.NewBackendClosedNoCtx()

Learn more about managing compliance generic rules or creating your own custom rules

Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent deadlock by checking existing locks

In canRetryLock, move the txn.HasLockTable(table) check to the beginning of the
function to prevent potential deadlocks where a transaction might retry
acquiring a lock on a table it already holds a lock on.

pkg/sql/colexec/lockop/lock_op.go [826-853]

 func canRetryLock(table uint64, txn client.TxnOperator, err error) bool {
+	// If current transaction already hold the lock table, means it is a remote
+	// transaction. And wait and retry will cause deadlock.
+	if txn.HasLockTable(table) {
+		return false
+	}
+
 	if moerr.IsMoErrCode(err, moerr.ErrRetryForCNRollingRestart) {
 		time.Sleep(defaultWaitTimeOnRetryLock)
 		return true
-	}
-	if txn.HasLockTable(table) {
-		return false
 	}
 	if moerr.IsMoErrCode(err, moerr.ErrLockTableBindChanged) ||
 		moerr.IsMoErrCode(err, moerr.ErrLockTableNotFound) {
 		time.Sleep(defaultWaitTimeOnRetryLock)
 		return true
 	}
 
 	// Use morpc.GetStatusCategory for unified RPC error classification
 	// StatusUnknown (non-RPC errors) will fall through to return false
 	status := morpc.GetStatusCategory(err)
 	if status == morpc.StatusTransient || status == morpc.StatusUnavailable {
 		time.Sleep(defaultWaitTimeOnRetryLock)
 		return true
 	}
 	if status == morpc.StatusCancelled {
 		return false // Client closing/closed should not retry
 	}
 
 	// Unknown errors (non-RPC, non-lock errors) should not retry
 	return false
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: This suggestion correctly identifies a potential deadlock scenario where a transaction holding a lock might retry and wait for another lock on the same table. Moving the txn.HasLockTable(table) check to the beginning of the function is a critical fix to prevent this.

Medium
Avoid creating backends when closing

In getBackend, add a check for c.mu.closing before enqueuing a new backend
creation task to prevent new tasks from starting during client shutdown.

pkg/common/morpc/client.go [880-887]

-if canCreate {
+if canCreate && !c.mu.closing {
     // Try to enqueue creation task with backpressure handling
     if !globalClientGC.triggerCreate(c, backend) {
         // Queue is full - fallback to existing creation path with proper bookkeeping
         return c.createBackendWithBookkeeping(backend, lock)
     }
     creationQueued = true
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: This is a good suggestion for improving robustness during client shutdown. Checking c.mu.closing before triggering a new backend creation task prevents unnecessary work and potential race conditions or panics if the client closes while a creation task is in flight.

Medium
General
Add minimal sleep on zero backoff

In the retry logic of Send, NewStream, and Ping, add a small sleep (e.g., 10ms)
when the calculated backoff is zero to prevent a tight loop that consumes high
CPU.

pkg/common/morpc/client.go [483-490]

 backoff = policy.nextBackoff(backoff)
 if backoff > 0 {
     select {
     case <-ctx.Done():
         return nil, ctx.Err()
     case <-time.After(backoff):
     }
+} else {
+    // prevent busy spin when backoff is zero
+    time.Sleep(10 * time.Millisecond)
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that a zero backoff can lead to a busy-wait loop, consuming excessive CPU. Adding a small sleep is a standard and effective way to mitigate this, improving system performance under contention.

Low
  • More

This pull request was closed.

This branch was previously deployed

1 inactive deployment
ci — 14817f2e Deployed Jan 4, 2026 by ghost
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 Review effort 4/5 size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.