Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix: prevent channel error leaks and iterator panics (#21565)

buua4366ef2656a4daf
diff --git a/internal/channels/whatsapp.go b/internal/channels/whatsapp.go
index 3b421ac795..8b6638238b 100644
--- a/internal/channels/whatsapp.go
+++ b/internal/channels/whatsapp.go
@@ -588,10 +588,10 @@ func (c *whatsappChannel) requestJSONWithClient(ctx context.Context, client *htt
return err
}
defer resp.Body.Close()
- respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1024*1024))
if resp.StatusCode >= 400 {
- return fmt.Errorf("status: %d, response: %s", resp.StatusCode, string(respBody))
+ return fmt.Errorf("WhatsApp gateway returned HTTP status %d", resp.StatusCode)
}
+ respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1024*1024))
if out != nil && len(bytes.TrimSpace(respBody)) > 0 {
return json.Unmarshal(respBody, out)
}
diff --git a/internal/channels/whatsapp_security_test.go b/internal/channels/whatsapp_security_test.go
new file mode 100644
index 0000000000..1a39d8e28f
--- /dev/null
+++ b/internal/channels/whatsapp_security_test.go
@@ -0,0 +1,43 @@
+package channels
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestWhatsAppRuntimeErrorDoesNotExposeGatewayResponseBody(t *testing.T) {
+ const responseSecret = "CHANNEL_RESPONSE_SECRET_SENTINEL"
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusInternalServerError)
+ _, _ = w.Write([]byte(responseSecret))
+ }))
+ defer server.Close()
+ allowChannelURLForTest(t, server.URL)
+
+ channel := newWhatsAppChannel(whatsappAccount{AccountID: "probe", GatewayBaseURL: server.URL})
+ err := channel.requestJSON(context.Background(), http.MethodGet, "whatsapp/probe/status", nil, nil)
+ if err == nil {
+ t.Fatal("requestJSON() succeeded for HTTP 500")
+ }
+ channel.setError(err)
+ if got := *channel.Snapshot().LastError; !strings.Contains(got, "500") {
+ t.Fatalf("runtime last_error = %q, want the HTTP status", got)
+ } else if strings.Contains(got, responseSecret) {
+ t.Fatalf("runtime last_error exposed gateway response body: %q", got)
+ }
+}
+
+func TestWhatsAppRejectsUntrustedGatewayDestination(t *testing.T) {
+ t.Setenv(channelAllowedHostsEnv, "")
+ channel := newWhatsAppChannel(whatsappAccount{
+ AccountID: "probe",
+ GatewayBaseURL: "http://169.254.169.254/",
+ })
+ err := channel.requestJSON(context.Background(), http.MethodGet, "whatsapp/probe/status", nil, nil)
+ if err == nil || !strings.Contains(err.Error(), "not trusted") {
+ t.Fatalf("requestJSON() error = %v, want an untrusted-destination rejection", err)
+ }
+}
diff --git a/internal/harness/core/async_iterator_test.go b/internal/harness/core/async_iterator_test.go
new file mode 100644
index 0000000000..aab0537f58
--- /dev/null
+++ b/internal/harness/core/async_iterator_test.go
@@ -0,0 +1,90 @@
+package core
+
+import (
+ "testing"
+ "time"
+)
+
+func TestAsyncIteratorCloseUnblocksGeneratorSend(t *testing.T) {
+ iter, gen := NewAsyncIteratorPair[int]()
+ for i := 0; i < cap(iter.ch); i++ {
+ gen.Send(i)
+ }
+
+ sent := make(chan struct{})
+ go func() {
+ gen.Send(cap(iter.ch))
+ close(sent)
+ }()
+ iter.Close()
+
+ select {
+ case <-sent:
+ case <-time.After(time.Second):
+ t.Fatal("generator send remained blocked after iterator close")
+ }
+ gen.Close()
+}
+
+func TestAsyncGeneratorCloseDrainsBufferedItems(t *testing.T) {
+ iter, gen := NewAsyncIteratorPair[int]()
+ gen.Send(1)
+ gen.Send(2)
+ gen.Close()
+
+ for _, want := range []int{1, 2} {
+ got, ok := iter.Next()
+ if !ok || got != want {
+ t.Fatalf("Next() = (%d, %t), want (%d, true)", got, ok, want)
+ }
+ }
+ if got, ok := iter.Next(); ok {
+ t.Fatalf("Next() after draining closed generator = (%d, true), want no item", got)
+ }
+}
+
+func TestAsyncGeneratorCloseUnblocksBlockedSend(t *testing.T) {
+ iter, gen := NewAsyncIteratorPair[int]()
+ for i := 0; i < cap(iter.ch); i++ {
+ gen.Send(i)
+ }
+
+ sent := make(chan struct{})
+ go func() {
+ gen.Send(cap(iter.ch))
+ close(sent)
+ }()
+ closed := make(chan struct{})
+ go func() {
+ gen.Close()
+ close(closed)
+ }()
+
+ select {
+ case <-closed:
+ case <-time.After(time.Second):
+ t.Fatal("generator close remained blocked on an in-flight send")
+ }
+ select {
+ case <-sent:
+ case <-time.After(time.Second):
+ t.Fatal("in-flight send did not stop after generator close")
+ }
+ iter.Close()
+}
+
+func TestAsyncGeneratorSendAfterIteratorCloseIsIgnored(t *testing.T) {
+ iter, gen := NewAsyncIteratorPair[int]()
+ iter.Close()
+ if !gen.IsClosed() {
+ t.Fatal("generator should report a closed stream after iterator close")
+ }
+ gen.Send(1)
+ if gen.trySend(2) {
+ t.Fatal("trySend succeeded after the iterator was closed")
+ }
+ if gen.SendCtx(t.Context(), 3) {
+ t.Fatal("SendCtx succeeded after the iterator was closed")
+ }
+ gen.Close()
+}
diff --git a/internal/harness/core/utils.go b/internal/harness/core/utils.go
index 4a3f0606ec..945e3f4b04 100644
--- a/internal/harness/core/utils.go
+++ b/internal/harness/core/utils.go
@@ -9,8 +9,10 @@ import (
// Multiple goroutines reading from the same iterator will receive each item
// exactly once.
type AsyncIterator[T any] struct {
- ch chan iterationItem[T]
- done bool
+ ch chan iterationItem[T]
+ stop chan struct{}
+ done <-chan struct{}
+ closeOnce sync.Once
}
type iterationItem[T any] struct {
@@ -19,54 +21,98 @@ type iterationItem[T any] struct {
}
func NewAsyncIterator[T any]() *AsyncIterator[T] {
- return &AsyncIterator[T]{ch: make(chan iterationItem[T], 64)}
+ return &AsyncIterator[T]{
+ ch: make(chan iterationItem[T], 64),
+ stop: make(chan struct{}),
+ }
}
func (it *AsyncIterator[T]) Next() (T, bool) {
- item, ok := <-it.ch
- if !ok {
- it.done = true
+ select {
+ case <-it.stop:
var zero T
return zero, false
+ default:
+ }
+
+ select {
+ case <-it.stop:
+ var zero T
+ return zero, false
+ case item, ok := <-it.ch:
+ if !ok {
+ var zero T
+ return zero, false
+ }
+ return item.value, item.ok
+ case <-it.done:
+ // The generator closes done only after all in-flight sends have ended.
+ // Drain buffered values before reporting the end of the stream.
+ select {
+ case item, ok := <-it.ch:
+ if !ok {
+ var zero T
+ return zero, false
+ }
+ return item.value, item.ok
+ default:
+ var zero T
+ return zero, false
+ }
}
- return item.value, item.ok
}
func (it *AsyncIterator[T]) Close() {
- if !it.done {
- it.done = true
- close(it.ch)
- }
+ it.closeOnce.Do(func() { close(it.stop) })
}
// AsyncGenerator produces items for an AsyncIterator.
// Multiple goroutines can safely Send to the same generator.
type AsyncGenerator[T any] struct {
- ch chan iterationItem[T]
- closed bool
- mu sync.Mutex
+ ch chan iterationItem[T]
+ stop <-chan struct{}
+ closing chan struct{}
+ done chan struct{}
+ closed bool
+ mu sync.Mutex
+ sends sync.WaitGroup
}
func NewAsyncIteratorPair[T any]() (*AsyncIterator[T], *AsyncGenerator[T]) {
ch := make(chan iterationItem[T], 64)
- return &AsyncIterator[T]{ch: ch}, &AsyncGenerator[T]{ch: ch}
+ stop := make(chan struct{})
+ closing := make(chan struct{})
+ done := make(chan struct{})
+ return &AsyncIterator[T]{ch: ch, stop: stop, done: done}, &AsyncGenerator[T]{
+ ch: ch,
+ stop: stop,
+ closing: closing,
+ done: done,
+ }
}
func (g *AsyncGenerator[T]) Send(value T) {
- g.mu.Lock()
- defer g.mu.Unlock()
- if !g.closed {
- g.ch <- iterationItem[T]{value: value, ok: true}
+ if !g.beginSend() {
+ return
+ }
+ defer g.sends.Done()
+ select {
+ case <-g.stop:
+ case <-g.closing:
+ case g.ch <- iterationItem[T]{value: value, ok: true}:
}
}
func (g *AsyncGenerator[T]) trySend(value T) bool {
- g.mu.Lock()
- defer g.mu.Unlock()
- if g.closed {
+ if !g.beginSend() {
return false
}
+ defer g.sends.Done()
select {
+ case <-g.stop:
+ return false
+ case <-g.closing:
+ return false
case g.ch <- iterationItem[T]{value: value, ok: true}:
return true
default:
@@ -76,30 +122,48 @@ func (g *AsyncGenerator[T]) trySend(value T) bool {
func (g *AsyncGenerator[T]) Close() {
g.mu.Lock()
- defer g.mu.Unlock()
- if !g.closed {
- g.closed = true
- close(g.ch)
+ if g.closed {
+ done := g.done
+ g.mu.Unlock()
+ <-done
+ return
}
+ g.closed = true
+ close(g.closing)
+ g.mu.Unlock()
+
+ g.sends.Wait()
+ close(g.done)
}
func (g *AsyncGenerator[T]) IsClosed() bool {
g.mu.Lock()
- defer g.mu.Unlock()
- return g.closed
+ closed := g.closed
+ g.mu.Unlock()
+ if closed {
+ return true
+ }
+ select {
+ case <-g.stop:
+ return true
+ default:
+ return false
+ }
}
// SendCtx sends a value, respecting context cancellation to prevent goroutine leaks
// when the consumer stops reading from the iterator.
func (g *AsyncGenerator[T]) SendCtx(ctx context.Context, value T) bool {
- g.mu.Lock()
- if g.closed {
- g.mu.Unlock()
+ if !g.beginSend() {
return false
}
- g.mu.Unlock()
+ defer g.sends.Done()
select {
+ case <-g.stop:
+ return false
+ case <-g.closing:
+ return false
case g.ch <- iterationItem[T]{value: value, ok: true}:
return true
case <-ctx.Done():
@@ -107,6 +171,21 @@ func (g *AsyncGenerator[T]) SendCtx(ctx context.Context, value T) bool {
}
}
+func (g *AsyncGenerator[T]) beginSend() bool {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ if g.closed {
+ return false
+ }
+ select {
+ case <-g.stop:
+ return false
+ default:
+ g.sends.Add(1)
+ return true
+ }
+}
+
// ===== Copy helpers =====
func copyTypedAgentEvent[M MessageType](event *TypedAgentEvent[M]) *TypedAgentEvent[M] {
diff --git a/internal/harness/core/workflow_stress_test.go b/internal/harness/core/workflow_stress_test.go
index c5edd0d46d..72ca050e6f 100644
--- a/internal/harness/core/workflow_stress_test.go
+++ b/internal/harness/core/workflow_stress_test.go
@@ -314,35 +314,29 @@ func TestAgentLoop_ConcurrentPushStop_Race(t *testing.T) {
}
}
-// ---- Bug #6: handleIter panic in runner.go may cause double-close ----
-//
-// runner.go handleIter has recover() that sends an error event then calls gen.Close().
-// But gen.Send() after gen.Close() would panic. If the panic occurs during gen.Send(),
-// the recover() would fire again, causing infinite recursion.
-//
-// NOTE: This test confirmed that a panic inside an agent's Run() is NOT caught
-// by runner.go's handleIter, because the panic happens in flowAgent.Run() which
-// is called BEFORE handleIter starts. The panic propagates up to the test.
-// This is itself a bug — agent panics should be caught and converted to error events.
+// ---- Bug #6: closing a paired iterator must not make runner cleanup panic ----
func TestRunner_HandleIter_PanicSafety(t *testing.T) {
- // Instead of using the full runner (which panics outside handleIter),
- // directly test handleIter's recover behavior.
- _, gen := NewAsyncIteratorPair[*TypedAgentEvent[*schema.Message]]()
- ai := NewAsyncIterator[*TypedAgentEvent[*schema.Message]]()
- ai.Close() // closed iterator to simulate quick termination
+ ai, inputGen := NewAsyncIteratorPair[*TypedAgentEvent[*schema.Message]]()
+ outputIter, outputGen := NewAsyncIteratorPair[*TypedAgentEvent[*schema.Message]]()
+ outputIter.Close()
+ inputGen.Send(nil)
+ inputGen.Close()
done := make(chan struct{})
+ var panicValue any
go func() {
defer close(done)
- // This should NOT panic — handleIter has recover()
- handleIter(false, nil, t.Context(), ai, gen, nil, nil)
+ defer func() { panicValue = recover() }()
+ handleIter(false, nil, t.Context(), ai, outputGen, nil, nil)
}()
select {
case <-done:
- // Clean termination
+ if panicValue != nil {
+ t.Fatalf("handleIter panicked after its iterator was closed: %v", panicValue)
+ }
case <-time.After(time.Second * 5):
- t.Errorf("BUG: handleIter deadlocked")
+ t.Fatal("handleIter did not terminate after its iterator was closed")
}
}