| 1 | package agent |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "sync/atomic" |
| 6 | "time" |
| 7 | ) |
| 8 | |
| 9 | // runStragglers counts parallel tool goroutines that outlived their batch's |
| 10 | // grace period. The batch already reported their result as unknown, but they |
| 11 | // can still be inside the agent when the next turn resets per-turn state. |
| 12 | type runStragglers struct{ live atomic.Int64 } |
| 13 | |
| 14 | func (s *runStragglers) enter() { s.live.Add(1) } |
| 15 | func (s *runStragglers) leave() { s.live.Add(-1) } |
| 16 | |
| 17 | // drain waits up to limit for abandoned goroutines to leave the agent, so the |
| 18 | // next turn never zeroes per-turn state under a live reader. A goroutine that |
| 19 | // ignores its cancelled context past the limit is left to the batch's unknown |
| 20 | // outcome, exactly as before. |
| 21 | func (s *runStragglers) drain(ctx context.Context, limit time.Duration) { |
| 22 | if s.live.Load() == 0 { |
| 23 | return |
| 24 | } |
| 25 | deadline := time.Now().Add(limit) |
| 26 | for s.live.Load() > 0 && time.Now().Before(deadline) && ctx.Err() == nil { |
| 27 | time.Sleep(10 * time.Millisecond) |
| 28 | } |
| 29 | } |
| 30 |