Skip to content

scope.go: missing ctx.Done() in select loop causes goroutine leak on query cancellation #24061

Closed

Description

@XuPeng-SH

Summary

The main coordination loop in scope.go:365-384 is missing a ctx.Done() case in its select statement. When a query is cancelled (e.g., client disconnect), the goroutine blocks forever waiting on preScopeResultReceiveChan and notifyMessageResultReceiveChan.

Root Cause

// scope.go:365-384
for {
    select {
    case err := <-preScopeResultReceiveChan:
        // ...
    case result := <-notifyMessageResultReceiveChan:
        // ...
    // MISSING: case <-s.Proc.Ctx.Done():
    }
    if preScopeCount == 0 && remoteScopeCount == 0 {
        return nil
    }
}

While the spawned goroutines (via sendNotifyMessage) DO check context cancellation internally through receiveBatch() and forwardRemoteBatchWithContext(), the main loop that waits for their results has no exit path when context is cancelled.

Leak Scenario

  1. Query starts → main loop enters select at line 365
  2. Context cancelled (client disconnects)
  3. Remote receiver goroutines detect cancellation, try to send results to buffered channels
  4. Main loop still blocked on select — no ctx.Done() case
  5. If all buffer slots are full, goroutines block on channel send
  6. Circular deadlock: main loop waits for goroutines, goroutines wait for main loop to drain channels
  7. Goroutine leak — never cleaned up

Suggested Fix

Add context cancellation case to the select:

for {
    select {
    case <-s.Proc.Ctx.Done():
        return s.Proc.Ctx.Err()
    case err := <-preScopeResultReceiveChan:
        // ...
    case result := <-notifyMessageResultReceiveChan:
        // ...
    }
}

Impact

  • Goroutine accumulation under query cancellation load
  • Memory growth from leaked goroutines holding references to batches, channels, and pipeline state
  • Potential ants goroutine pool exhaustion under sustained cancellation pressure

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s0

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions