From 7d8b53de6ebfbb59972f46b971b1a21d6173ab20 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 14:04:43 -0500 Subject: [PATCH 1/3] AI-3985: clear the harness only after the reply goroutine ends stopPipeline cleared a.harness while consumeLLM still read replies the model had queued before it closed: a data race (pipeline.go:548 against agent.go:3632 under -race) and, once the read saw nil, a nil dereference in say that ended the call. The stop now waits for consumeLLM before it clears the fields. Co-Authored-By: Claude Sonnet 5.5 --- acceleration/internal/agent/agent.go | 1 + .../internal/agent/harness_stop_test.go | 65 +++++++++++++++++++ acceleration/internal/agent/pipeline.go | 7 ++ 3 files changed, 73 insertions(+) create mode 100644 acceleration/internal/agent/harness_stop_test.go diff --git a/acceleration/internal/agent/agent.go b/acceleration/internal/agent/agent.go index c9433b6846..0e8a6aab9d 100644 --- a/acceleration/internal/agent/agent.go +++ b/acceleration/internal/agent/agent.go @@ -3559,6 +3559,7 @@ func sendAll(replies chan<- llm.Event, events []llm.Event) { // It is the only goroutine that speaks. func (a *Agent) consumeLLM(p *pipeline, replies <-chan llm.Event) { defer p.running.Done() + defer p.replying.Done() for event := range replies { a.handle(event) diff --git a/acceleration/internal/agent/harness_stop_test.go b/acceleration/internal/agent/harness_stop_test.go new file mode 100644 index 0000000000..a4d787709b --- /dev/null +++ b/acceleration/internal/agent/harness_stop_test.go @@ -0,0 +1,65 @@ +package agent + +import ( + "sync" + "time" +) + +// A reply the model had already sent when the pipeline stops is still read by the goroutine that +// speaks, so the harness it reads must not be cleared under it: the read is a data race under +// -race, and a nil harness panics it and ends the call. +func (s *AgentSuite) TestAReplyQueuedWhenThePipelineStopsIsSpokenBeforeTheHarnessIsCleared() { + s.join(false) + turn := s.answering("Tell me a story.") + synthesizing, release := make(chan struct{}), make(chan struct{}) + s.voice.mu.Lock() + s.voice.synthesizing, s.voice.synthesisRelease = synthesizing, release + s.voice.mu.Unlock() + released := sync.OnceFunc(func() { close(release) }) + defer released() + s.model.writes(turn, "Once upon a time. ") + <-synthesizing + s.model.writes(turn, "And then it ended. ") + s.eventually(func() bool { + s.agent.mu.Lock() + defer s.agent.mu.Unlock() + return len(s.agent.replies) > 0 + }, "the second delta never queued") + + stopped := make(chan struct{}) + go func() { + defer close(stopped) + s.agent.stopPipeline(false) + }() + s.eventually(func() bool { + s.agent.mu.Lock() + defer s.agent.mu.Unlock() + return s.agent.pipe == nil || s.agent.pipe.ctx.Err() != nil + }, "the pipeline never began to stop") + // A stop that clears the harness at once does it here, and the reply goroutine is let go after + // it. A stop that waits for that goroutine first leaves the harness, and this ends at its limit. + for limit := time.Now().Add(100 * time.Millisecond); time.Now().Before(limit); time.Sleep(time.Millisecond) { + s.agent.mu.Lock() + cleared := s.agent.harness == nil + s.agent.mu.Unlock() + if cleared { + break + } + } + released() + <-stopped + + var said []string + for _, request := range s.voice.spoken() { + said = append(said, request.Text) + } + s.Contains(said, "And then it ended.", "the reply queued at the stop was not read to its end") +} + +// A pipeline that is already stopped has no reply goroutine to wait for. +func (s *AgentSuite) TestStoppingAPipelineThatIsAlreadyStoppedReturns() { + s.join(false) + s.Empty(s.agent.stopPipeline(false)) + + s.Empty(s.agent.stopPipeline(false)) +} diff --git a/acceleration/internal/agent/pipeline.go b/acceleration/internal/agent/pipeline.go index 7206e627a2..400bed53b9 100644 --- a/acceleration/internal/agent/pipeline.go +++ b/acceleration/internal/agent/pipeline.go @@ -40,6 +40,9 @@ type pipeline struct { // speechEnded is set once a native pipeline's speech-to-speech session has stopped // sending, before the agent recovers it (recoverNative). speechEnded atomic.Bool + // replying is the cascade's goroutine that reads the model's replies. It reads the harness + // without the lock, so stopping the pipeline clears the harness only once it has ended. + replying sync.WaitGroup } // ErrSpeechEnded refuses a change of tools whose speech-to-speech session ended while the @@ -491,6 +494,7 @@ func (a *Agent) startCascade(prep *prepared) { a.running.Add(1) goroutine.Go(a.ctx, func() { a.consumeHarness(prep.harness, drained) }) p.running.Add(1) + p.replying.Add(1) goroutine.Go(a.ctx, func() { a.consumeLLM(p, replies) }) // The other three all begin at a microphone or end at a speaker, so a conversation // held in writing runs none of them. @@ -543,6 +547,9 @@ func (a *Agent) startNative(prep *prepared) { // harness survives when kept, and the call is never left. func (a *Agent) stopPipeline(keepHarness bool) []error { p, failures := a.releasePipeline(keepHarness) + if p != nil { + p.replying.Wait() + } a.mu.Lock() if !keepHarness { a.harness, a.harnessDrained = nil, nil From 3193cfc8a1cfd9eb2f963493fac8a90b37a1b729 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 14:27:01 -0500 Subject: [PATCH 2/3] AI-3985: read the harness under the lock in perform, nativeDelegate and executeTool A superseded ruling, a delegation and a tool's picture are handled on goroutines the pipeline stop does not wait for, and each read a.harness while stopPipeline cleared it: a data race, and a nil harness panics. Each now takes a copy under a.mu and lets the work go when it is nil, as performing() does for a.performs. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/agent/agent.go | 8 ++- acceleration/internal/agent/agent_test.go | 14 +++- .../internal/agent/harness_stop_test.go | 70 +++++++++++++++++++ acceleration/internal/agent/native.go | 9 ++- acceleration/internal/agent/telephony.go | 5 +- 5 files changed, 97 insertions(+), 9 deletions(-) diff --git a/acceleration/internal/agent/agent.go b/acceleration/internal/agent/agent.go index 0e8a6aab9d..314b768298 100644 --- a/acceleration/internal/agent/agent.go +++ b/acceleration/internal/agent/agent.go @@ -2223,7 +2223,13 @@ func (a *Agent) perform(action Action) { case ActSupersede: a.dropSpeculation(action.TurnID) - if err := a.harness.CancelDecision(action.TurnID); err != nil { + a.mu.Lock() + current := a.harness + a.mu.Unlock() + if current == nil { + return + } + if err := current.CancelDecision(action.TurnID); err != nil { a.fail(err, "flow") } diff --git a/acceleration/internal/agent/agent_test.go b/acceleration/internal/agent/agent_test.go index a5f6aaf553..c49acff490 100644 --- a/acceleration/internal/agent/agent_test.go +++ b/acceleration/internal/agent/agent_test.go @@ -347,6 +347,9 @@ type stubLLM struct { // capabilities are what the model says it takes: text alone unless a test says more. capabilities llm.Capabilities + // readingCapabilities, if set, is called each time they are read, so a test can act at that + // moment. + readingCapabilities func() // panics, if set, is the value that Create panics with. It is like a bug in a model // adapter. @@ -540,9 +543,14 @@ func (s *stubLLM) Close() error { return nil } -func (s *stubLLM) Provider() string { return "stub" } -func (s *stubLLM) Model() string { return "stub-llm" } -func (s *stubLLM) Capabilities() llm.Capabilities { return s.capabilities } +func (s *stubLLM) Provider() string { return "stub" } +func (s *stubLLM) Model() string { return "stub-llm" } +func (s *stubLLM) Capabilities() llm.Capabilities { + if s.readingCapabilities != nil { + s.readingCapabilities() + } + return s.capabilities +} // sentBy is who each request was asked in the name of. func (s *stubLLM) sentBy() []routing.Caller { diff --git a/acceleration/internal/agent/harness_stop_test.go b/acceleration/internal/agent/harness_stop_test.go index a4d787709b..1f2ff01710 100644 --- a/acceleration/internal/agent/harness_stop_test.go +++ b/acceleration/internal/agent/harness_stop_test.go @@ -1,8 +1,14 @@ package agent import ( + "bytes" + "context" + "runtime" "sync" "time" + + "github.com/GetStream/Vision-Agents/acceleration/internal/harness" + "github.com/GetStream/Vision-Agents/acceleration/internal/llm" ) // A reply the model had already sent when the pipeline stops is still read by the goroutine that @@ -63,3 +69,67 @@ func (s *AgentSuite) TestStoppingAPipelineThatIsAlreadyStoppedReturns() { s.Empty(s.agent.stopPipeline(false)) } + +// A ruling superseded while the pipeline is stopped finds no harness and is let go. +func (s *AgentSuite) TestASupersedeAfterThePipelineStoppedIsLetGo() { + s.join(false) + s.agent.stopPipeline(false) + + s.NotPanics(func() { s.agent.perform(Action{Kind: ActSupersede, TurnID: "candidate"}) }) +} + +// A subagent asked for as the pipeline stops is told there is none, not handed to the harness +// the stop cleared. +func (s *AgentSuite) TestADelegationAsThePipelineStopsFindsNoSubagent() { + s.join(false) + s.agent.mu.Lock() + unlock := sync.OnceFunc(s.agent.mu.Unlock) + defer unlock() + cleared := s.agent.harness + defer cleared.Close() + var err error + var panicked any + answered := make(chan struct{}) + go func() { + defer close(answered) + defer func() { panicked = recover() }() + _, _, err = s.agent.nativeDelegate(s.ctx, llm.ToolCall{ID: "think-1", Name: delegateSkill, Arguments: `{"skill":"think","prompt":"Work out the booking total"}`}) + }() + s.eventually(func() bool { return waitingOnALockIn("nativeDelegate") }, "the delegation never waited on the agent's lock") + // The clear stopPipeline makes, while the delegation waits on the lock. + s.agent.harness = nil + unlock() + <-answered + + s.Nil(panicked, "the delegation read the harness the stop cleared") + s.EqualError(err, "agent: no subagent configured") +} + +// A tool's picture that comes back as the pipeline stops is not handed to the harness the stop +// cleared. +func (s *AgentSuite) TestAToolsPictureAsThePipelineStopsIsNotHandedToAClearedHarness() { + s.runner = &stubToolRunner{run: func(context.Context, llm.ToolCall) ([]llm.ContentPart, error) { + return []llm.ContentPart{{Text: "the room"}, {Image: &llm.ImagePart{MIME: "image/jpeg", Data: []byte{0xff, 0xd8, 0xff}}}}, nil + }} + s.tools = harness.Tools{Tools: []harness.Tool{{Name: "photograph_room", Description: "photograph the room"}}} + s.join(false) + // Whether the model looks at the picture itself is asked after the picture came back: the + // pipeline stops at that moment. + s.model.readingCapabilities = sync.OnceFunc(func() { s.agent.stopPipeline(false) }) + requested := harness.ToolRequested{TurnID: "r1", Call: llm.ToolCall{ID: "photo-1", Name: "photograph_room", Arguments: "{}"}} + ctx, cancel := s.agent.prepareTool(requested) + + s.NotPanics(func() { s.agent.executeTool(ctx, cancel, requested) }) +} + +// waitingOnALockIn reports whether a goroutine running function waits on a mutex. +func waitingOnALockIn(function string) bool { + stacks := make([]byte, 1<<20) + stacks = stacks[:runtime.Stack(stacks, true)] + for _, goroutine := range bytes.Split(stacks, []byte("\n\n")) { + if bytes.Contains(goroutine, []byte("[sync.Mutex.Lock")) && bytes.Contains(goroutine, []byte(")."+function+"(")) { + return true + } + } + return false +} diff --git a/acceleration/internal/agent/native.go b/acceleration/internal/agent/native.go index 55f2ba1c4d..05eb42f7c4 100644 --- a/acceleration/internal/agent/native.go +++ b/acceleration/internal/agent/native.go @@ -834,11 +834,14 @@ func (a *Agent) nativeDelegate(ctx context.Context, call llm.ToolCall) ([]llm.Co if err := json.Unmarshal([]byte(call.Arguments), &arguments); err != nil { return nil, false, harness.Correctable(err) } - if a.harness == nil { + a.mu.Lock() + current := a.harness + a.mu.Unlock() + if current == nil { return nil, false, errors.New("agent: no subagent configured") } if call.Name == cancelSkill { - err := a.harness.CancelSkill(arguments.Skill) + err := current.CancelSkill(arguments.Skill) return llm.TextParts("Cancelled the skill's pending work."), false, err } a.mu.Lock() @@ -850,7 +853,7 @@ func (a *Agent) nativeDelegate(ctx context.Context, call llm.ToolCall) ([]llm.Co } charged := a.chargedLocked(context.WithoutCancel(ctx), a.toolScheduled[call.ID]) a.mu.Unlock() - id, err := a.harness.Delegate(charged, arguments.Skill, arguments.Prompt, call.ID, nil, history) + id, err := current.Delegate(charged, arguments.Skill, arguments.Prompt, call.ID, nil, history) if err != nil { return nil, false, err } diff --git a/acceleration/internal/agent/telephony.go b/acceleration/internal/agent/telephony.go index 666ab26a67..9a842669f8 100644 --- a/acceleration/internal/agent/telephony.go +++ b/acceleration/internal/agent/telephony.go @@ -732,12 +732,13 @@ func (a *Agent) executeTool(ctx context.Context, cancel context.CancelFunc, requ delete(a.toolsRunning, requested.Call.ID) delete(a.toolUpdates, requested.Call.ID) charged := a.chargedLocked(ctx, a.toolScheduled[requested.Call.ID]) + current := a.harness a.mu.Unlock() // Visual tool results go to the vision worker in both native and cascade calls. The // call is still open in the history it is handed, which a provider refuses to replay. // With no worker, as in a chat, a model that sees images is shown them itself. - if err == nil && a.harness != nil && llm.HasImage([]llm.Message{{Parts: parts}}) && !a.looksItself() { - _, err = a.harness.Delegate(charged, visionSkill, "Analyze this tool result for the caller's current question.", requested.TurnID, parts, withOpenCallsAnswered(harness.WithoutNotes(a.History()))) + if err == nil && current != nil && llm.HasImage([]llm.Message{{Parts: parts}}) && !a.looksItself() { + _, err = current.Delegate(charged, visionSkill, "Analyze this tool result for the caller's current question.", requested.TurnID, parts, withOpenCallsAnswered(harness.WithoutNotes(a.History()))) if err == nil { parts = llm.TextParts(llm.TextOf(parts) + "\nVisual analysis requested; wait for the vision findings before interpreting the images.") } From 761077deb1fade7fd39a865263cadd766cf53f7d Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 14:37:16 -0500 Subject: [PATCH 3/3] AI-3985: assert the queued reply's goroutine logs no panic at the stop The test saw the panic only through the second sentence going missing, which a stop that drops the queued reply would also cause. It now reads the log for the panic itself, and its comment says what the forced order shows: a nil read, not a reported race. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/agent/harness_stop_test.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/acceleration/internal/agent/harness_stop_test.go b/acceleration/internal/agent/harness_stop_test.go index 1f2ff01710..4125d29892 100644 --- a/acceleration/internal/agent/harness_stop_test.go +++ b/acceleration/internal/agent/harness_stop_test.go @@ -12,9 +12,10 @@ import ( ) // A reply the model had already sent when the pipeline stops is still read by the goroutine that -// speaks, so the harness it reads must not be cleared under it: the read is a data race under -// -race, and a nil harness panics it and ends the call. +// speaks, so the harness it reads must not be cleared under it: in the order forced here that +// goroutine reads a nil harness, which panics it. func (s *AgentSuite) TestAReplyQueuedWhenThePipelineStopsIsSpokenBeforeTheHarnessIsCleared() { + s.logs = &logLines{} s.join(false) turn := s.answering("Tell me a story.") synthesizing, release := make(chan struct{}), make(chan struct{}) @@ -60,6 +61,7 @@ func (s *AgentSuite) TestAReplyQueuedWhenThePipelineStopsIsSpokenBeforeTheHarnes said = append(said, request.Text) } s.Contains(said, "And then it ended.", "the reply queued at the stop was not read to its end") + s.Empty(s.logs.records("a goroutine panicked"), "the reply goroutine read the harness the stop cleared") } // A pipeline that is already stopped has no reply goroutine to wait for.