From 36e8f19908e707056d599e141bd17628405aa6f2 Mon Sep 17 00:00:00 2001 From: Aibu <29893417+wssab314@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:15:14 +0800 Subject: [PATCH] fix(resumablestream): use context.AfterFunc and reject permanent TLS url errors Replace the per-stream watcher goroutine in convention/resumablestream with context.AfterFunc so unclosed streams using long-lived contexts do not leak goroutines. Also classify permanent x509/TLS and scheme-mismatch *url.Error failures as non-retryable. Fixes #43 --- CHANGELOG.md | 1 + convention/resumablestream/resumablestream.go | 55 +++++++++++++++---- .../resumablestream/resumablestream_test.go | 45 +++++++++++++++ 3 files changed, 89 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c307f0..bbb8ce9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ existing `0.1.0` release; earlier development prereleases are not listed. ### Fixed +- Replace the per-stream watcher goroutine in `convention/resumablestream` with `context.AfterFunc` so unclosed streams using long-lived contexts do not leak goroutines, and treat permanent TLS/certificate and scheme-mismatch `*url.Error` failures as non-retryable. - Decode Managed tool configurations using case-insensitive canonical names and snake_case aliases, preserving the authored name when round-tripping request parameters. - Preserve unknown fields, malformed members, explicit nulls and authored empty objects when decoding typed Forward Environment and Template A2A parameters. Typed edits replace automatically retained raw values; explicit caller overrides retain precedence. Invalid values reach server validation rather than disappearing from a configuration update. - Clear stale null metadata when reusing a decoded Forward Session multiagent update parameter, so a subsequent roster is sent instead of an unintended clearing request. diff --git a/convention/resumablestream/resumablestream.go b/convention/resumablestream/resumablestream.go index 8357f4c..a8c5b36 100644 --- a/convention/resumablestream/resumablestream.go +++ b/convention/resumablestream/resumablestream.go @@ -3,6 +3,8 @@ package resumablestream import ( "context" + "crypto/tls" + "crypto/x509" "encoding/json" "errors" "io" @@ -70,12 +72,13 @@ func defaultSettings() settings { // Stream reconnects child streams while retaining the latest yielded event cursor. type Stream[T any] struct { - parent context.Context - ctx context.Context - cancel context.CancelFunc - open Open[T] - terminal func(T) bool - config settings + parent context.Context + ctx context.Context + cancel context.CancelFunc + stopWatcher func() bool + open Open[T] + terminal func(T) bool + config settings mu sync.Mutex child Child[T] @@ -118,7 +121,7 @@ func newStream[T any](ctx context.Context, lastEventID string, open Open[T], ter s.err = initialErr[0] cancel() } else { - go s.closeOnContext() + s.stopWatcher = context.AfterFunc(streamCtx, s.closeOnContext) } return s } @@ -152,7 +155,7 @@ func (s *Stream[T]) Next() bool { accepted, terminal := s.checkpoint(child.Current(), child.LastEventID()) if terminal { s.closeChild(child) - s.cancel() + s.stopAndCancel() } return accepted } @@ -208,15 +211,21 @@ func (s *Stream[T]) Close() error { s.child = nil s.mu.Unlock() - s.cancel() + s.stopAndCancel() if child != nil { return child.Close() } return nil } +func (s *Stream[T]) stopAndCancel() { + if s.stopWatcher != nil { + s.stopWatcher() + } + s.cancel() +} + func (s *Stream[T]) closeOnContext() { - <-s.ctx.Done() s.mu.Lock() if err := s.parent.Err(); err != nil && s.err == nil && !s.closed { s.err = err @@ -317,7 +326,7 @@ func (s *Stream[T]) fail(err error) { } s.mu.Unlock() if failed { - s.cancel() + s.stopAndCancel() } } @@ -378,8 +387,30 @@ func retryable(_ context.Context, err error) bool { } var urlErr *url.Error if errors.As(err, &urlErr) { - return true + return !isPermanentURLError(urlErr) } var netErr net.Error return errors.As(err, &netErr) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.ErrClosedPipe) } + +func isPermanentURLError(err error) bool { + if errors.Is(err, http.ErrSchemeMismatch) { + return true + } + var ( + unknownAuthority x509.UnknownAuthorityError + hostnameErr x509.HostnameError + certInvalid x509.CertificateInvalidError + sysRoots x509.SystemRootsError + constraintErr x509.ConstraintViolationError + insecureAlg x509.InsecureAlgorithmError + recordHeader tls.RecordHeaderError + ) + return errors.As(err, &unknownAuthority) || + errors.As(err, &hostnameErr) || + errors.As(err, &certInvalid) || + errors.As(err, &sysRoots) || + errors.As(err, &constraintErr) || + errors.As(err, &insecureAlg) || + errors.As(err, &recordHeader) +} diff --git a/convention/resumablestream/resumablestream_test.go b/convention/resumablestream/resumablestream_test.go index 5b4bcc2..c2583ff 100644 --- a/convention/resumablestream/resumablestream_test.go +++ b/convention/resumablestream/resumablestream_test.go @@ -3,12 +3,15 @@ package resumablestream import ( "bytes" "context" + "crypto/tls" + "crypto/x509" "encoding/json" "errors" "io" "net/http" "net/url" "reflect" + "runtime" "sync" "testing" "time" @@ -333,6 +336,11 @@ func TestRetryClassificationMatchesRequestPolicy(t *testing.T) { {name: "malformed JSON", err: malformedJSON, want: false}, {name: "JSON type error", err: typeJSON, want: false}, {name: "arbitrary validation error", err: errors.New("missing required parameter"), want: false}, + {name: "x509 unknown authority", err: &url.Error{Op: "Get", URL: "https://sdk.test", Err: x509.UnknownAuthorityError{}}, want: false}, + {name: "x509 hostname mismatch", err: &url.Error{Op: "Get", URL: "https://sdk.test", Err: x509.HostnameError{Host: "sdk.test"}}, want: false}, + {name: "x509 invalid cert", err: &url.Error{Op: "Get", URL: "https://sdk.test", Err: x509.CertificateInvalidError{Reason: x509.Expired}}, want: false}, + {name: "tls record header", err: &url.Error{Op: "Get", URL: "https://sdk.test", Err: tls.RecordHeaderError{Msg: "not TLS"}}, want: false}, + {name: "scheme mismatch", err: &url.Error{Op: "Get", URL: "https://sdk.test", Err: http.ErrSchemeMismatch}, want: false}, } { t.Run(tc.name, func(t *testing.T) { if got := retryable(context.Background(), tc.err); got != tc.want { @@ -405,3 +413,40 @@ func TestStreamCloseInterruptsBackoff(t *testing.T) { t.Fatal("close did not interrupt backoff") } } + +func TestNewDoesNotLeakWatcherGoroutineWithoutClose(t *testing.T) { + before := runtime.NumGoroutine() + streams := make([]*Stream[string], 32) + for i := range streams { + streams[i] = New(context.Background(), "", func(context.Context, string, bool) Child[string] { + return &fakeChild[string]{} + }, nil) + } + after := runtime.NumGoroutine() + runtime.KeepAlive(streams) + // Context cancellation is watched via context.AfterFunc without spawning per-stream goroutines. + if delta := after - before; delta >= 8 { + t.Fatalf("unexpected goroutine growth creating 32 streams without Close: before=%d after=%d", before, after) + } +} + +func TestStreamStopsImmediatelyOnPermanentTLSError(t *testing.T) { + tlsErr := &url.Error{Op: "Get", URL: "https://sdk.test", Err: x509.UnknownAuthorityError{}} + calls := 0 + var delays []time.Duration + stream := newStream(context.Background(), "", func(context.Context, string, bool) Child[string] { + calls++ + return &fakeChild[string]{err: tlsErr} + }, nil, immediateSettings(&delays)) + defer stream.Close() + + if stream.Next() { + t.Fatal("expected stream to fail on TLS certificate error") + } + if !errors.Is(stream.Err(), tlsErr) { + t.Fatalf("err = %v, want %v", stream.Err(), tlsErr) + } + if calls != 1 || len(delays) != 0 { + t.Fatalf("calls = %d, delays = %v; want single attempt without retry", calls, delays) + } +}