From ed3f5dc64ccbb779d96d2fb674c40ba2a6a26650 Mon Sep 17 00:00:00 2001 From: Peter Steinberger Date: Wed, 23 Sep 2026 00:18:36 -0700 Subject: [PATCH] fix: drain bridge replies before reporting disconnects Publish the reader error through frame-stream closure so EOF cannot win a select against pending pair-ok, hello-ok, or event frames. Closing the stream also avoids needing a separate blocking error send after consumer shutdown. Replace the artificial saturated-client tests with one-reader pipe regressions for reply ordering, EOF, read errors, and departed consumers. Co-authored-by: Sebastien Tardif --- CHANGELOG.md | 1 + README.md | 2 + cmd/clawgo/main.go | 38 +++++------ cmd/clawgo/readloop_test.go | 133 ++++++++++++++++++++++++++++++++++++ cmd/clawgo/wait_test.go | 1 - 5 files changed, 155 insertions(+), 20 deletions(-) create mode 100644 cmd/clawgo/readloop_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 137e7bc..20802aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Deliver buffered bridge frames before reporting disconnects, preventing lost pairing and hello replies, and let bridge readers exit without an error consumer. Thanks @SebTardif! (#9) - Stop speech queues and cancel active system TTS when the bridge disconnects or the node exits. Thanks @SebTardif! (#7) - Forward only final speech transcripts to quick actions, voice events, and agent requests. Thanks @SebTardif! (#12) - Treat leading dashes in spoken text as words instead of espeak options. Thanks @SebTardif! (#11) diff --git a/README.md b/README.md index 87451e2..f05ca87 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,8 @@ With `-stt-engine brabble`, only final utterances are routed or sent to the brid SIGINT and SIGTERM interrupt reconnect backoff immediately, including when the bridge is unavailable. They also cancel bridge dialing and pairing/hello waits in `run` and `pair`, closing the connection before exit. +Bridge replies already received are processed before a disconnect is reported, including pairing and hello replies sent immediately before the bridge closes the connection. + Spoken text is passed after `--` so leading dashes are treated as words. Custom `-tts-system-command` wrappers must preserve the option separator when forwarding arguments to espeak-ng. ## systemd example diff --git a/cmd/clawgo/main.go b/cmd/clawgo/main.go index 4df1534..7ef3cbd 100644 --- a/cmd/clawgo/main.go +++ b/cmd/clawgo/main.go @@ -40,8 +40,8 @@ type BridgeClient struct { mu sync.Mutex logf func(string, ...any) done chan struct{} - errs chan error frames chan map[string]any + readErr error // Read only after frames closes. eventMu sync.RWMutex eventHandler func(string, string) closeOnce sync.Once @@ -495,14 +495,13 @@ func runNode(cfg NodeConfig) error { mdnsCleanup() } return nil - case err := <-client.errs: - if err != nil { - client.logf("bridge error: %v", err) + case frame, ok := <-client.frames: + if !ok { + client.logf("bridge error: %v", client.readErr) + connCancel() + client.Close() + goto reconnect } - connCancel() - client.Close() - goto reconnect - case frame := <-client.frames: if frame == nil { continue } @@ -552,7 +551,6 @@ func connectBridge(ctx context.Context, addr string) (*BridgeClient, error) { conn: conn, logf: func(format string, args ...any) { fmt.Fprintf(os.Stderr, format+"\n", args...) }, done: make(chan struct{}), - errs: make(chan error, 1), frames: make(chan map[string]any, 16), } go client.readLoop() @@ -600,6 +598,8 @@ func (c *BridgeClient) dispatchEvent(evt, payload string) { } func (c *BridgeClient) readLoop() { + defer close(c.frames) + c.readErr = io.EOF scanner := bufio.NewScanner(c.conn) scanner.Buffer(make([]byte, 0, 64*1024), 8*1024*1024) for scanner.Scan() { @@ -618,11 +618,9 @@ func (c *BridgeClient) readLoop() { return } } - if err := scanner.Err(); err != nil && !errors.Is(err, io.EOF) { - c.errs <- err - return + if err := scanner.Err(); err != nil { + c.readErr = err } - c.errs <- io.EOF } func sendPairRequest(c *BridgeClient, cfg NodeConfig, state *NodeState) error { @@ -684,9 +682,10 @@ func waitForPair(ctx context.Context, c *BridgeClient) (string, error) { return "", ctx.Err() case <-deadline: return "", errors.New("pairing timeout") - case err := <-c.errs: - return "", err - case frame := <-c.frames: + case frame, ok := <-c.frames: + if !ok { + return "", c.readErr + } if frame == nil { continue } @@ -712,9 +711,10 @@ func waitForHello(ctx context.Context, c *BridgeClient) error { return ctx.Err() case <-deadline: return errors.New("hello timeout") - case err := <-c.errs: - return err - case frame := <-c.frames: + case frame, ok := <-c.frames: + if !ok { + return c.readErr + } if frame == nil { continue } diff --git a/cmd/clawgo/readloop_test.go b/cmd/clawgo/readloop_test.go new file mode 100644 index 0000000..7637239 --- /dev/null +++ b/cmd/clawgo/readloop_test.go @@ -0,0 +1,133 @@ +package main + +import ( + "context" + "encoding/json" + "io" + "net" + "testing" + "time" +) + +func readLoopFixture(t *testing.T) (*BridgeClient, net.Conn, <-chan struct{}) { + t.Helper() + conn, peer := net.Pipe() + c := &BridgeClient{ + conn: conn, + logf: func(string, ...any) {}, + done: make(chan struct{}), + frames: make(chan map[string]any, 16), + } + finished := make(chan struct{}) + go func() { + c.readLoop() + close(finished) + }() + t.Cleanup(func() { + c.Close() + _ = peer.Close() + select { + case <-finished: + case <-time.After(2 * time.Second): + t.Error("bridge reader did not stop") + } + }) + return c, peer, finished +} + +func TestBridgeHandshakeBeforeEOF(t *testing.T) { + for _, kind := range []string{"pair", "hello"} { + t.Run(kind, func(t *testing.T) { + for i := 0; i < 32; i++ { + c, peer, finished := readLoopFixture(t) + frame := map[string]any{"type": kind + "-ok", "token": "synthetic-token"} + if err := json.NewEncoder(peer).Encode(frame); err != nil { + t.Fatal(err) + } + _ = peer.Close() + select { + case <-finished: + case <-time.After(2 * time.Second): + t.Fatal("bridge reader did not finish after EOF") + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + if kind == "pair" { + token, err := waitForPair(ctx, c) + cancel() + if err != nil || token != "synthetic-token" { + t.Fatalf("iteration %d: pair = %q, %v; want token before EOF", i, token, err) + } + } else { + err := waitForHello(ctx, c) + cancel() + if err != nil { + t.Fatalf("iteration %d: hello = %v; want hello-ok before EOF", i, err) + } + } + } + }) + } +} + +func TestBridgeReaderStopsWithoutConsumer(t *testing.T) { + for _, frames := range []int{0, 17} { + c, peer, finished := readLoopFixture(t) + writerDone := make(chan struct{}) + go func() { + defer close(writerDone) + for i := 0; i < frames; i++ { + if _, err := io.WriteString(peer, "{\"type\":\"event\"}\n"); err != nil { + return + } + } + }() + select { + case <-writerDone: + case <-time.After(2 * time.Second): + t.Fatal("could not fill frame buffer") + } + c.Close() + select { + case <-finished: + case <-time.After(2 * time.Second): + t.Fatal("reader blocked after consumer left") + } + } +} + +func TestBridgeWaitReportsEOF(t *testing.T) { + c, peer, _ := readLoopFixture(t) + _ = peer.Close() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + if _, err := waitForPair(ctx, c); err != io.EOF { + t.Fatalf("pair error = %v, want EOF", err) + } + if err := waitForHello(ctx, c); err != io.EOF { + t.Fatalf("hello error = %v, want EOF", err) + } +} + +type failedReadConn struct { + net.Conn + err error +} + +func (c failedReadConn) Read([]byte) (int, error) { return 0, c.err } + +func TestBridgeReaderPreservesReadError(t *testing.T) { + want := io.ErrUnexpectedEOF + c := &BridgeClient{ + conn: failedReadConn{err: want}, + frames: make(chan map[string]any, 1), + } + c.readLoop() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + if _, err := waitForPair(ctx, c); err != want { + t.Fatalf("pair error = %v, want %v", err, want) + } + if err := waitForHello(ctx, c); err != want { + t.Fatalf("hello error = %v, want %v", err, want) + } +} diff --git a/cmd/clawgo/wait_test.go b/cmd/clawgo/wait_test.go index afa96c7..578ccc7 100644 --- a/cmd/clawgo/wait_test.go +++ b/cmd/clawgo/wait_test.go @@ -63,7 +63,6 @@ func TestConnectBridgeCancellationClosesConnection(t *testing.T) { func testBridgeClient() *BridgeClient { return &BridgeClient{ logf: func(string, ...any) {}, - errs: make(chan error), frames: make(chan map[string]any), } }