-
Notifications
You must be signed in to change notification settings - Fork 31
fix(acp): serialize wakeup prompts to prevent turn misalignment #1202
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
206 changes: 206 additions & 0 deletions
206
apps/backend/internal/agentctl/server/adapter/transport/acp/wakeup_concurrency_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,206 @@ | ||
| package acp | ||
|
|
||
| import ( | ||
| "context" | ||
| "io" | ||
| "sync" | ||
| "sync/atomic" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/coder/acp-go-sdk" | ||
| ) | ||
|
|
||
| // concurrencyFakeAgent is a minimal acp.Agent whose Prompt handler blocks until | ||
| // released, recording how many Prompt calls are in flight simultaneously. It | ||
| // lets a test observe whether kandev issues two overlapping conn.Prompt() calls. | ||
| type concurrencyFakeAgent struct { | ||
| entered chan struct{} // one signal per Prompt entry | ||
| release chan struct{} // closed to unblock all parked Prompts | ||
| inFlight atomic.Int32 | ||
| maxInFlight atomic.Int32 | ||
| } | ||
|
|
||
| func (f *concurrencyFakeAgent) Prompt(_ context.Context, _ acp.PromptRequest) (acp.PromptResponse, error) { | ||
| cur := f.inFlight.Add(1) | ||
| for { | ||
| old := f.maxInFlight.Load() | ||
| if cur <= old || f.maxInFlight.CompareAndSwap(old, cur) { | ||
| break | ||
| } | ||
| } | ||
| f.entered <- struct{}{} | ||
| <-f.release | ||
| f.inFlight.Add(-1) | ||
| return acp.PromptResponse{StopReason: acp.StopReasonEndTurn}, nil | ||
| } | ||
|
|
||
| func (f *concurrencyFakeAgent) Initialize(_ context.Context, params acp.InitializeRequest) (acp.InitializeResponse, error) { | ||
| return acp.InitializeResponse{ProtocolVersion: params.ProtocolVersion}, nil | ||
| } | ||
|
|
||
| func (f *concurrencyFakeAgent) NewSession(_ context.Context, _ acp.NewSessionRequest) (acp.NewSessionResponse, error) { | ||
| return acp.NewSessionResponse{SessionId: "sess-concurrency-test"}, nil | ||
| } | ||
|
|
||
| func (f *concurrencyFakeAgent) Authenticate(_ context.Context, _ acp.AuthenticateRequest) (acp.AuthenticateResponse, error) { | ||
| return acp.AuthenticateResponse{}, nil | ||
| } | ||
| func (f *concurrencyFakeAgent) Cancel(_ context.Context, _ acp.CancelNotification) error { return nil } | ||
| func (f *concurrencyFakeAgent) CloseSession(_ context.Context, _ acp.CloseSessionRequest) (acp.CloseSessionResponse, error) { | ||
| return acp.CloseSessionResponse{}, nil | ||
| } | ||
| func (f *concurrencyFakeAgent) ListSessions(_ context.Context, _ acp.ListSessionsRequest) (acp.ListSessionsResponse, error) { | ||
| return acp.ListSessionsResponse{}, nil | ||
| } | ||
| func (f *concurrencyFakeAgent) ResumeSession(_ context.Context, _ acp.ResumeSessionRequest) (acp.ResumeSessionResponse, error) { | ||
| return acp.ResumeSessionResponse{}, nil | ||
| } | ||
| func (f *concurrencyFakeAgent) SetSessionConfigOption(_ context.Context, _ acp.SetSessionConfigOptionRequest) (acp.SetSessionConfigOptionResponse, error) { | ||
| return acp.SetSessionConfigOptionResponse{}, nil | ||
| } | ||
| func (f *concurrencyFakeAgent) SetSessionMode(_ context.Context, _ acp.SetSessionModeRequest) (acp.SetSessionModeResponse, error) { | ||
| return acp.SetSessionModeResponse{}, nil | ||
| } | ||
|
|
||
| // TestWakeupDoesNotRaceConcurrentPromptWithUserPrompt reproduces the | ||
| // turn-misalignment bug: when a ScheduleWakeup timer fires while a user prompt | ||
| // is still in flight, fireWakeup must NOT issue a second, concurrent | ||
| // conn.Prompt() against the bridge. Two overlapping prompts are what desync the | ||
| // bridge's per-prompt stop_reason from the turn it belongs to, shifting chat | ||
| // turns one prompt behind. | ||
| // | ||
| // The fake agent blocks inside Prompt and records peak concurrency. With the | ||
| // current code the synthetic wakeup prompt overlaps the user prompt | ||
| // (maxInFlight == 2); a correct fix serializes them (maxInFlight == 1). | ||
|
carlosflorencio marked this conversation as resolved.
Outdated
|
||
| func TestWakeupDoesNotRaceConcurrentPromptWithUserPrompt(t *testing.T) { | ||
| a := newTestAdapter() | ||
|
|
||
| // Two in-memory pipes wire the adapter (client side) to the fake agent. | ||
| // clientToAgent: adapter writes requests -> agent reads. | ||
| // agentToClient: agent writes replies -> adapter reads. | ||
| c2aR, c2aW := io.Pipe() | ||
| a2cR, a2cW := io.Pipe() | ||
|
|
||
| if err := a.Connect(c2aW, a2cR); err != nil { | ||
| t.Fatalf("Connect: %v", err) | ||
| } | ||
|
|
||
| fa := &concurrencyFakeAgent{ | ||
| entered: make(chan struct{}, 8), | ||
| release: make(chan struct{}), | ||
| } | ||
| _ = acp.NewAgentSideConnection(fa, a2cW, c2aR) | ||
|
|
||
| ctx := context.Background() | ||
| if err := a.Initialize(ctx); err != nil { | ||
| t.Fatalf("Initialize: %v", err) | ||
| } | ||
| sid, err := a.NewSession(ctx, nil) | ||
| if err != nil { | ||
| t.Fatalf("NewSession: %v", err) | ||
| } | ||
|
|
||
| var userWG sync.WaitGroup | ||
| userWG.Add(1) | ||
| go func() { | ||
| defer userWG.Done() | ||
| _ = a.Prompt(ctx, "user message", nil) | ||
| }() | ||
|
|
||
| // Wait until the user prompt is parked inside the agent's Prompt handler. | ||
| select { | ||
| case <-fa.entered: | ||
| case <-time.After(5 * time.Second): | ||
| t.Fatal("user prompt never reached the agent") | ||
| } | ||
|
|
||
| // Fire the wakeup while the user prompt is still in flight. | ||
| a.fireWakeup(sid, "synthetic wakeup prompt") | ||
|
|
||
| // Did a second prompt overlap the in-flight user prompt? | ||
| secondOverlapped := false | ||
| select { | ||
| case <-fa.entered: | ||
| secondOverlapped = true | ||
| case <-time.After(2 * time.Second): | ||
|
carlosflorencio marked this conversation as resolved.
Outdated
|
||
| } | ||
|
|
||
| close(fa.release) | ||
| userWG.Wait() | ||
|
|
||
| t.Cleanup(func() { | ||
| _ = a.Close() | ||
| _ = c2aW.Close() | ||
| _ = a2cW.Close() | ||
| }) | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
|
|
||
| if secondOverlapped || fa.maxInFlight.Load() > 1 { | ||
| t.Fatalf("wakeup issued a concurrent conn.Prompt() while a user prompt was in flight (maxInFlight=%d); prompts must be serialized so the bridge's stop_reason stays aligned with its turn", fa.maxInFlight.Load()) | ||
| } | ||
| } | ||
|
|
||
| // TestWakeupDroppedWhenSessionChangesWhileQueued covers the case where a wakeup | ||
| // prompt queues behind an in-flight user prompt and the adapter's active session | ||
| // changes (NewSession/LoadSession/reset) before the wakeup gets the gate. The | ||
| // queued wakeup must target the session it was scheduled for; if that session is | ||
| // no longer current it must be dropped, not injected into the new session. | ||
| func TestWakeupDroppedWhenSessionChangesWhileQueued(t *testing.T) { | ||
| a := newTestAdapter() | ||
|
|
||
| c2aR, c2aW := io.Pipe() | ||
| a2cR, a2cW := io.Pipe() | ||
| if err := a.Connect(c2aW, a2cR); err != nil { | ||
| t.Fatalf("Connect: %v", err) | ||
| } | ||
| fa := &concurrencyFakeAgent{ | ||
| entered: make(chan struct{}, 8), | ||
| release: make(chan struct{}), | ||
| } | ||
| _ = acp.NewAgentSideConnection(fa, a2cW, c2aR) | ||
|
|
||
| ctx := context.Background() | ||
|
carlosflorencio marked this conversation as resolved.
Outdated
|
||
| if err := a.Initialize(ctx); err != nil { | ||
| t.Fatalf("Initialize: %v", err) | ||
| } | ||
| origSession, err := a.NewSession(ctx, nil) | ||
| if err != nil { | ||
| t.Fatalf("NewSession: %v", err) | ||
| } | ||
|
|
||
| var userWG sync.WaitGroup | ||
| userWG.Add(1) | ||
| go func() { | ||
| defer userWG.Done() | ||
| _ = a.Prompt(ctx, "user message", nil) | ||
| }() | ||
| select { | ||
| case <-fa.entered: | ||
| case <-time.After(5 * time.Second): | ||
| t.Fatal("user prompt never reached the agent") | ||
| } | ||
|
|
||
| // Wakeup fires for the original session and queues behind the gate. | ||
| a.fireWakeup(origSession, "scheduled wakeup for original session") | ||
|
|
||
| // The active session changes while the wakeup waits (e.g. reset/resume). | ||
| a.mu.Lock() | ||
| a.sessionID = "different-session-after-reset" | ||
| a.mu.Unlock() | ||
|
|
||
| // Release the in-flight user prompt so the queued wakeup can run. | ||
| close(fa.release) | ||
| userWG.Wait() | ||
|
|
||
| select { | ||
| case <-fa.entered: | ||
|
carlosflorencio marked this conversation as resolved.
|
||
| t.Fatal("queued wakeup was sent after the session changed; it must be dropped to avoid injecting into an unrelated session") | ||
| case <-time.After(2 * time.Second): | ||
| } | ||
|
|
||
| t.Cleanup(func() { | ||
| _ = a.Close() | ||
| _ = c2aW.Close() | ||
| _ = a2cW.Close() | ||
| }) | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.