Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
55 changes: 43 additions & 12 deletions convention/resumablestream/resumablestream.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package resumablestream

import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"io"
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -317,7 +326,7 @@ func (s *Stream[T]) fail(err error) {
}
s.mu.Unlock()
if failed {
s.cancel()
s.stopAndCancel()
}
}

Expand Down Expand Up @@ -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)
}
45 changes: 45 additions & 0 deletions convention/resumablestream/resumablestream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
}