Skip to content
Merged
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
9 changes: 8 additions & 1 deletion acceleration/internal/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}

Expand Down Expand Up @@ -3559,6 +3565,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)
Expand Down
14 changes: 11 additions & 3 deletions acceleration/internal/agent/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down
137 changes: 137 additions & 0 deletions acceleration/internal/agent/harness_stop_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
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
// 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{})
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")

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Nit] R1.2 This catches the panic only through its effect: the second sentence has to reach a voice that releasePipeline already closed. A fix that drops the queued reply at the stop (also correct) would fail it. The comment at lines 8-10 also says the read is a data race under -race, but the forced order reports 0 races (main, 200/200 runs). Suggest logging to s.logs and asserting no a goroutine panicked record (or that the call did not end), and dropping the race claim. Ticket, not this PR.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 761077d: TestAReplyQueuedWhenThePipelineStopsIsSpokenBeforeTheHarnessIsCleared now logs to s.logs and asserts that no "a goroutine panicked" record was logged. The comment now says that the forced order gives a nil read, not a reported race. With the p.replying.Wait() removed, both assertions fail: "the reply queued at the stop was not read to its end" and "the reply goroutine read the harness the stop cleared".

s.Empty(s.logs.records("a goroutine panicked"), "the reply goroutine read the harness the stop cleared")

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit, not blocking. The no-panic assertion is a weak detector: stopPipeline does not wait for the reply goroutine (that is exactly what this test pins), so the panic log can land after this line. With p.replying.Wait() commented out, over 40 -race runs the "not read to its end" assertion fires 40/40 and this one 5/40. The test is still killed by the first assertion, so no mutant survives. Optional: wait for the goroutine to end before asserting, or say in the comment that the first assertion is the one that catches it.

}

// 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))
}

// 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
}
9 changes: 6 additions & 3 deletions acceleration/internal/agent/native.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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
}
Expand Down
7 changes: 7 additions & 0 deletions acceleration/internal/agent/pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions acceleration/internal/agent/telephony.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
}
Expand Down
Loading