Skip to content

(fix): Prevent Silent Data Loss in Multi-CN Dispatch - #22751

Merged
8 commits merged into
matrixorigin:mainfrom
XuPeng-SH:fix-22750
Nov 4, 2025
Merged

8 commits merged into
matrixorigin:mainfrom
XuPeng-SH:fix-22750

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Nov 2, 2025 •

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 #22750 #22727

What this PR does / why we need it:

Problem

When a remote CN becomes unavailable (ReceiverDone=true), data destined for that CN was silently dropped without error in SendToAll/Shuffle scenarios, leading to incomplete query results.

Solution

Introduce receiverFailureMode to distinguish between scenarios:

  • FailureModeStrict (SendToAll/Shuffle): Return error on receiver failure
  • FailureModeTolerant (SendToAny): Allow failover to other receivers

PR Type

Bug fix, Tests


Description

  • Prevent silent data loss when remote CN becomes unavailable in SendToAll/Shuffle scenarios

  • Introduce receiverFailureMode to distinguish strict vs tolerant failure handling

  • Add comprehensive integration tests documenting the data loss bug and fix

  • Return explicit errors in strict mode when receiver is done, protecting data integrity


Diagram Walkthrough

flowchart LR
  A["Remote CN Unavailable<br/>ReceiverDone=true"] --> B{"Failure Mode?"}
  B -->|FailureModeStrict| C["SendToAll/Shuffle<br/>Return Error"]
  B -->|FailureModeTolerant| D["SendToAny<br/>Failover to Other"]
  C --> E["Query Fails<br/>Data Protected"]
  D --> F["Try Next Receiver<br/>Graceful Degradation"]
Loading

File Walkthrough

Relevant files
Tests
data_loss_integration_test.go
Integration tests for silent data loss prevention               

pkg/sql/colexec/dispatch/data_loss_integration_test.go

  • New comprehensive integration test file documenting the silent data
    loss bug
  • Tests cover SendToAll, Shuffle, and real-world scenarios (full table
    scan, shuffle join, GROUP BY aggregation)
  • Demonstrates before/after behavior with clear error messages and data
    integrity protection
  • Includes multiple failure scenarios and comparison tables showing the
    fix effectiveness
+353/-0 
dispatch_test.go
Unit tests for failure mode handling and data loss prevention

pkg/sql/colexec/dispatch/dispatch_test.go

  • Renamed TestReceiverDone to TestReceiverDone_OldBehavior for clarity
  • Updated test expectations to verify strict mode returns errors when
    receiver is done
  • Added new unit tests for sendBatchToClientSession with both strict and
    tolerant modes
  • Added tests for SendToAll, SendToAny, and Shuffle scenarios with
    receiver failures
  • Added comparison table test documenting behavior differences before
    and after fix
+185/-3 
Bug fix
sendfunc.go
Implement failure mode handling and data loss prevention logic

pkg/sql/colexec/dispatch/sendfunc.go

  • Introduced receiverFailureMode enum with FailureModeStrict and
    FailureModeTolerant constants
  • Modified sendBatchToClientSession signature to accept failureMode and
    receiverID parameters
  • Implemented critical fix: when ReceiverDone=true, return error in
    strict mode to prevent silent data loss
  • Updated sendToAllRemoteFunc to use FailureModeStrict for data
    completeness
  • Updated sendBatToIndex and sendBatToMultiMatchedReg to use
    FailureModeStrict for shuffle scenarios
  • Updated sendToAnyRemoteFunc to use FailureModeTolerant allowing
    failover to other receivers
  • Added retry logic and improved error messages with receiver
    identifiers
+124/-27

@qodo-code-review

qodo-code-review Bot commented Nov 2, 2025 •

Copy link
Copy Markdown

PR Compliance Guide 🔍

(Compliance updated until commit 0a1229f)

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
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: Meaningful Naming and Self-Documenting Code

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

Status: Passed

Generic: Robust Error Handling and Edge Case Management

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

Status: Passed

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

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

Generic: Security-First Input Validation and Data Handling

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

Status: Passed

⚪
Generic: Comprehensive Audit Trails

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

Status:
No audit logs: New strict/tolerant failure handling and receiver removal paths do not emit any audit logs
for critical events (e.g., receiver failure, data-loss prevention error), which may be
acceptable for low-level components but warrants verification.

Referred Code
	return false, errEncode
}

// SendToAny can tolerate individual receiver failures
// We can try other receivers if one fails
maxRetries := len(ap.ctr.remoteReceivers)
retriesLeft := maxRetries

for retriesLeft > 0 {
	if ap.ctr.remoteRegsCnt == 0 {
		return false, moerr.NewInternalError(proc.Ctx,
			"sendToAny failed: all remote receivers are unavailable")
	}

	regIdx := ap.ctr.sendCnt % ap.ctr.remoteRegsCnt
	reg := ap.ctr.remoteReceivers[regIdx]
	receiverID := fmt.Sprintf("%s(Idx=%d)", reg.Uid.String(), regIdx)

	// SendToAny uses tolerant mode - can failover to other receivers
	remove, err := sendBatchToClientSession(proc.Ctx, encodeData, reg, FailureModeTolerant, receiverID)
	if err != nil {


 ... (clipped 21 lines)
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

Previous compliance checks

Compliance check up to commit 6752d4c
Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
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: Meaningful Naming and Self-Documenting Code

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

Status: Passed

Generic: Robust Error Handling and Edge Case Management

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

Status: Passed

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

⚪
Generic: Comprehensive Audit Trails

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

Status:
No auditing: The new logic and tests introduce error paths and receiver removal but do not add or
reference audit logging for these critical actions.

Referred Code
{ // send to remote regs
	encodeData, errEncode := bat.MarshalBinaryWithBuffer(&ap.ctr.marshalBuf)
	if errEncode != nil {
		return false, errEncode
	}

	for i := 0; i < len(ap.ctr.remoteReceivers); i++ {
		receiver := ap.ctr.remoteReceivers[i]
		receiverID := fmt.Sprintf("%s(MsgId=%d)", receiver.Uid.String(), receiver.MsgId)

		// SendToAll requires strict failure checking
		// If any receiver fails, we must report error to prevent data loss
		remove, err := sendBatchToClientSession(proc.Ctx, encodeData, receiver, FailureModeStrict, receiverID)
		if err != nil {
			return false, err
		}

		if remove {
			ap.ctr.removeIdxReceiver(i)
			if ap.ctr.remoteRegsCnt == 0 {


 ... (clipped 76 lines)
Generic: Secure Error Handling

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

Status:
Error detail scope: Errors include internal receiver identifiers like UIDs (e.g., "receiver
%s(MsgId=%d)"), which may be sensitive if surfaced to end-users; confirm these remain
internal-only.

Referred Code
{ // send to remote regs
	encodeData, errEncode := bat.MarshalBinaryWithBuffer(&ap.ctr.marshalBuf)
	if errEncode != nil {
		return false, errEncode
	}

	for i := 0; i < len(ap.ctr.remoteReceivers); i++ {
		receiver := ap.ctr.remoteReceivers[i]
		receiverID := fmt.Sprintf("%s(MsgId=%d)", receiver.Uid.String(), receiver.MsgId)

		// SendToAll requires strict failure checking
		// If any receiver fails, we must report error to prevent data loss
		remove, err := sendBatchToClientSession(proc.Ctx, encodeData, receiver, FailureModeStrict, receiverID)
		if err != nil {
			return false, err
		}

		if remove {
			ap.ctr.removeIdxReceiver(i)
			if ap.ctr.remoteRegsCnt == 0 {


 ... (clipped 76 lines)
Generic: Security-First Input Validation and Data Handling

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

Status:
Input validation: The new paths send encoded batch data over RPC without explicit validation or sanitization
in the shown diff; verification is needed that upstream validation and size limits are
sufficient.

Referred Code
// Send data (original logic unchanged)
if len(encodeBatData) <= maxMessageSizeToMoRpc {
	msg := cnclient.AcquireMessage()
	{
		msg.Id = wcs.MsgId
		msg.Data = encodeBatData
		msg.Cmd = pipeline.Method_BatchMessage
		msg.Sid = pipeline.Status_Last
	}
	if err = wcs.Cs.Write(ctx, msg); err != nil {
		return false, err
	}
	return false, nil
}

// Send large message in chunks (original logic unchanged)
start := 0
for start < len(encodeBatData) {
	end := start + maxMessageSizeToMoRpc
	sid := pipeline.Status_WaitingNext


 ... (clipped 9 lines)

@qodo-code-review

qodo-code-review Bot commented Nov 2, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent potential panic with pre-loop check

Move the check for zero remote receivers in sendToAnyRemoteFunc to before the
retry loop to prevent a potential division-by-zero panic.

pkg/sql/colexec/dispatch/sendfunc.go [302-311]

 // SendToAny can tolerate individual receiver failures
 // We can try other receivers if one fails
+if ap.ctr.remoteRegsCnt == 0 {
+    return false, moerr.NewInternalError(proc.Ctx,
+        "sendToAny failed: all remote receivers are unavailable")
+}
+
 maxRetries := len(ap.ctr.remoteReceivers)
 retriesLeft := maxRetries
 
 for retriesLeft > 0 {
-    if ap.ctr.remoteRegsCnt == 0 {
-        return false, moerr.NewInternalError(proc.Ctx,
-            "sendToAny failed: all remote receivers are unavailable")
-    }
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a potential panic due to a division-by-zero error if all remote receivers are removed during the loop's execution. Moving the check for ap.ctr.remoteRegsCnt == 0 before the loop is a critical fix to prevent a crash.

High
General
Remove unreachable error handling code

Remove an unreachable if remove block in sendBatToIndex, as the condition it
checks is already handled by a preceding error check.

pkg/sql/colexec/dispatch/sendfunc.go [142-147]

-if remove {
-    // In shuffle scenario, if target receiver is removed, it's a critical error
-    err = moerr.NewInternalError(proc.Ctx, fmt.Sprintf(
-        "shuffle target receiver %s was removed, data loss may occur", receiverID))
-    break
-}
+// This block is unreachable with FailureModeStrict and can be removed.
+// The `if errSend != nil` check above handles this case.
  • Apply / Chat
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly identifies that the if remove block is unreachable because sendBatchToClientSession in FailureModeStrict returns an error when remove is true, which is caught by the preceding if errSend != nil check. Removing this dead code improves code clarity and maintainability.

Low
  • Update

This pull request was closed.

This branch was previously deployed

1 inactive deployment
ci — 0a1229f8 Deployed Nov 4, 2025 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 3/5 size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants