Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
Optimize daemon runtime wakeups (#3859)
Wes5e7587ad07e3
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 8a78c27d7a..12629c8b3b 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -5,6 +5,7 @@ import ("encoding/json""errors""fmt"+ "hash/fnv""log/slog""math/rand""os"@@ -27,6 +28,11 @@ import (// server refresh.var ErrRepoNotConfigured = errors.New("repo is not configured for this workspace")+const (+ taskSlotWaitTimeout = 2 * time.Second+ taskSlotCapacityBackoff = 5 * time.Second+)+// taskRunner executes a single agent task and returns the result.// Extracted as an interface so tests can inject a fake without spawning real// agent processes, while keeping test scaffolding out of the production struct.@@ -647,7 +653,7 @@ func (d *Daemon) Run(ctx context.Context) error {// Start workspace sync loop to discover newly created workspaces.go d.workspaceSyncLoop(ctx)- taskWakeups := make(chan struct{}, 1)+ taskWakeups := make(chan taskWakeup, 256)go d.taskWakeupLoop(ctx, taskWakeups)go d.heartbeatLoop(ctx)go d.gcLoop(ctx)@@ -1858,7 +1864,7 @@ func (d *Daemon) triggerRestart() {// loop so that a slow ClaimTask call (HTTP 30s timeout) for one runtime no// longer delays claims on every other runtime — that was the cross-workspace// stall mode reported in MUL-1744.-func (d *Daemon) pollLoop(ctx context.Context, taskWakeups <-chan struct{}) error {+func (d *Daemon) pollLoop(ctx context.Context, taskWakeups <-chan taskWakeup) error {sem := newTaskSlotSemaphore(d.cfg.MaxConcurrentTasks)var taskWG sync.WaitGroup // tracks in-flight handleTask goroutinesvar pollerWG sync.WaitGroup // tracks runRuntimePoller goroutines@@ -1923,10 +1929,23 @@ func (d *Daemon) pollLoop(ctx context.Context, taskWakeups <-chan struct{}) erroreturn ctx.Err()case <-runtimeSetCh:syncPollers()- case <-taskWakeups:- // Fan out to every runtime poller. Any of them might have a queued- // task; the per-poller wakeup channel coalesces (cap 1) so a burst- // of wake-ups doesn't pile up.+ case wakeup := <-taskWakeups:+ if wakeup.runtimeID != "" {+ if h, ok := pollers[wakeup.runtimeID]; ok {+ d.logger.Debug("task wakeup: signaling runtime poller", "runtime_id", wakeup.runtimeID)+ select {+ case h.wakeup <- struct{}{}:+ default:+ }+ } else {+ d.logger.Debug("task wakeup: runtime poller not found", "runtime_id", wakeup.runtimeID, "pollers", len(pollers))+ }+ continue+ }++ // A wakeup without a runtime_id is a catch-up signal (for example,+ // immediately after the websocket connects). Fan it out so queued+ // work that existed before the connection is still discovered.d.logger.Debug("task wakeup: fanning out to pollers", "pollers", len(pollers))for _, h := range pollers {select {@@ -1968,6 +1987,13 @@ func (d *Daemon) runRuntimePoller(wakeup <-chan struct{},taskWG *sync.WaitGroup,) {+ if offset := runtimePollOffset(rid, d.cfg.PollInterval); offset > 0 {+ d.logger.Debug("poll: initial offset", "runtime_id", rid, "offset", offset)+ if err := sleepWithContextOrWakeup(pollerCtx, offset, wakeup); err != nil {+ return+ }+ }+for {if pollerCtx.Err() != nil {return@@ -1976,14 +2002,16 @@ func (d *Daemon) runRuntimePoller(// Acquire an execution slot before claiming. If at capacity, sleep// without claiming so we don't push a task into `dispatched` and// then race the 5-min server-side dispatch timeout while waiting.- var slot int- select {- case slot = <-sem:- case <-pollerCtx.Done():+ slot, acquired, woke, err := waitForTaskSlot(pollerCtx, sem, wakeup, taskSlotWaitTimeout)+ if err != nil {return- default:+ }+ if !acquired {d.logger.Debug("poll: at capacity", "runtime_id", rid, "running", d.cfg.MaxConcurrentTasks)- if err := sleepWithContextOrWakeup(pollerCtx, d.cfg.PollInterval, wakeup); err != nil {+ if woke {+ continue+ }+ if err := sleepWithContextOrWakeup(pollerCtx, capacityBackoff(d.cfg.PollInterval), wakeup); err != nil {return}continue@@ -2050,6 +2078,49 @@ func (d *Daemon) runRuntimePoller(}}+func runtimePollOffset(runtimeID string, interval time.Duration) time.Duration {+ if interval <= 0 || runtimeID == "" {+ return 0+ }+ h := fnv.New64a()+ _, _ = h.Write([]byte(runtimeID))+ return time.Duration(h.Sum64() % uint64(interval))+}++func capacityBackoff(pollInterval time.Duration) time.Duration {+ if pollInterval <= 0 || pollInterval > taskSlotCapacityBackoff {+ return taskSlotCapacityBackoff+ }+ return pollInterval+}++func waitForTaskSlot(ctx context.Context, sem chan int, wakeup <-chan struct{}, wait time.Duration) (slot int, acquired, woke bool, err error) {+ select {+ case slot = <-sem:+ return slot, true, false, nil+ case <-ctx.Done():+ return 0, false, false, ctx.Err()+ default:+ }++ if wait <= 0 {+ return 0, false, false, nil+ }++ timer := time.NewTimer(wait)+ defer timer.Stop()+ select {+ case slot = <-sem:+ return slot, true, false, nil+ case <-wakeup:+ return 0, false, true, nil+ case <-ctx.Done():+ return 0, false, false, ctx.Err()+ case <-timer.C:+ return 0, false, false, nil+ }+}+// newTaskSlotSemaphore returns a buffered channel pre-populated with stable// slot indices [0, n). Receive to acquire a slot, send the same slot back to// release. Used by pollLoop to expose MULTICA_TASK_SLOT to spawned tasks.diff --git a/server/internal/daemon/runtime_isolation_test.go b/server/internal/daemon/runtime_isolation_test.goindex d580160345..32705ce244 100644--- a/server/internal/daemon/runtime_isolation_test.go+++ b/server/internal/daemon/runtime_isolation_test.go@@ -194,6 +194,55 @@ func TestRunRuntimePollerSkipsClaimWhenAtCapacity(t *testing.T) {}}+func TestRunRuntimePollerClaimsWhenSlotBecomesAvailable(t *testing.T) {+ t.Parallel()++ var claimAttempts atomic.Int64++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if strings.Contains(r.URL.Path, "/tasks/claim") {+ claimAttempts.Add(1)+ }+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"task":null}`))+ }))+ defer srv.Close()++ d := New(Config{+ ServerBaseURL: srv.URL,+ HeartbeatInterval: time.Hour,+ PollInterval: time.Hour,+ MaxConcurrentTasks: 1,+ }, slog.New(slog.NewTextHandler(noopWriter{}, nil)))++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ sem := newTaskSlotSemaphore(d.cfg.MaxConcurrentTasks)+ slot := <-sem++ var taskWG sync.WaitGroup+ wakeup := make(chan struct{}, 1)+ go d.runRuntimePoller(ctx, ctx, "runtime-waiting", sem, wakeup, &taskWG)+ wakeup <- struct{}{}++ time.Sleep(100 * time.Millisecond)+ if got := claimAttempts.Load(); got != 0 {+ t.Fatalf("poller claimed before a slot was available; got %d claims", got)+ }++ sem <- slot++ deadline := time.After(2 * time.Second)+ for claimAttempts.Load() < 1 {+ select {+ case <-deadline:+ t.Fatal("poller did not claim after a slot became available")+ case <-time.After(10 * time.Millisecond):+ }+ }+}+// TestPollLoopShutdownWaitsForPollersBeforeTaskWG is a race-detector// regression for the WaitGroup misuse GPT-Boy flagged: pollLoop must not// call taskWG.Wait while a poller goroutine could still execute@@ -266,6 +315,84 @@ func TestPollLoopShutdownWaitsForPollersBeforeTaskWG(t *testing.T) {}}+func TestPollLoopTargetsRuntimeWakeup(t *testing.T) {+ t.Parallel()++ var fastClaims atomic.Int64+ var slowClaims atomic.Int64++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ path := r.URL.Path+ switch {+ case strings.HasSuffix(path, "/runtimes/runtime-fast/tasks/claim"):+ fastClaims.Add(1)+ case strings.HasSuffix(path, "/runtimes/runtime-slow/tasks/claim"):+ slowClaims.Add(1)+ default:+ http.Error(w, "unexpected path: "+path, http.StatusNotFound)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"task":null}`))+ }))+ defer srv.Close()++ d := New(Config{+ ServerBaseURL: srv.URL,+ HeartbeatInterval: time.Hour,+ PollInterval: time.Hour,+ MaxConcurrentTasks: 4,+ }, slog.New(slog.NewTextHandler(noopWriter{}, nil)))+ d.workspaces["ws-1"] = &workspaceState{+ workspaceID: "ws-1",+ runtimeIDs: []string{"runtime-fast", "runtime-slow"},+ }++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ taskWakeups := make(chan taskWakeup, 1)+ pollDone := make(chan error, 1)+ go func() {+ pollDone <- d.pollLoop(ctx, taskWakeups)+ }()++ taskWakeups <- taskWakeup{}++ deadline := time.After(2 * time.Second)+ for fastClaims.Load() < 1 || slowClaims.Load() < 1 {+ select {+ case <-deadline:+ t.Fatalf("initial poll did not claim both runtimes; fast=%d slow=%d", fastClaims.Load(), slowClaims.Load())+ case <-time.After(10 * time.Millisecond):+ }+ }++ fastClaims.Store(0)+ slowClaims.Store(0)+ taskWakeups <- taskWakeup{runtimeID: "runtime-fast"}++ deadline = time.After(2 * time.Second)+ for fastClaims.Load() < 1 {+ select {+ case <-deadline:+ t.Fatal("targeted wakeup did not wake runtime-fast")+ case <-time.After(10 * time.Millisecond):+ }+ }++ time.Sleep(100 * time.Millisecond)+ if got := slowClaims.Load(); got != 0 {+ t.Fatalf("targeted wakeup woke runtime-slow %d times; want 0", got)+ }++ cancel()+ select {+ case <-pollDone:+ case <-time.After(5 * time.Second):+ t.Fatal("pollLoop did not stop")+ }+}+// TestRunRuntimeHeartbeatIsolatesSlowRuntime is the heartbeat-side mirror of// the poll-isolation test: a slow SendHeartbeat for one runtime must not// block other runtimes' heartbeats.diff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.goindex a5d8b075b2..21dbbd9707 100644--- a/server/internal/daemon/wakeup.go+++ b/server/internal/daemon/wakeup.go@@ -18,7 +18,11 @@ import (var errRuntimeSetChanged = errors.New("runtime set changed")-func (d *Daemon) taskWakeupLoop(ctx context.Context, taskWakeups chan<- struct{}) {+type taskWakeup struct {+ runtimeID string+}++func (d *Daemon) taskWakeupLoop(ctx context.Context, taskWakeups chan<- taskWakeup) {backoff := time.SecondruntimeSetCh, unsub := d.runtimeSet.Subscribe()defer unsub()@@ -68,7 +72,7 @@ func jitterDuration(d time.Duration) time.Duration {return d + delta}-func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []string, taskWakeups chan<- struct{}, runtimeSetCh <-chan struct{}) error {+func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []string, taskWakeups chan<- taskWakeup, runtimeSetCh <-chan struct{}) error {wsURL, err := taskWakeupURL(d.cfg.ServerBaseURL, runtimeIDs)if err != nil {return err@@ -99,7 +103,7 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strindefer d.clearWSHeartbeatAcks()d.logger.Info("task wakeup websocket connected", "runtimes", len(runtimeIDs))- signalTaskWakeup(taskWakeups)+ signalTaskWakeup(taskWakeups, "")// Serialize all writes through a single channel: the gorilla/websocket// Conn does not allow concurrent WriteMessage calls, and the heartbeat@@ -255,7 +259,7 @@ func (d *Daemon) handleWSHeartbeatAck(ctx context.Context, ack *HeartbeatResponsd.handleHeartbeatActions(ctx, ack.RuntimeID, ack)}-func (d *Daemon) readTaskWakeupMessages(conn *websocket.Conn, taskWakeups chan<- struct{}) error {+func (d *Daemon) readTaskWakeupMessages(conn *websocket.Conn, taskWakeups chan<- taskWakeup) error {conn.SetReadLimit(64 * 1024)for {_, raw, err := conn.ReadMessage()@@ -279,7 +283,7 @@ func (d *Daemon) readTaskWakeupMessages(conn *websocket.Conn, taskWakeups chan<-if payload.RuntimeID != "" {d.logger.Debug("task wakeup received", "runtime_id", payload.RuntimeID, "task_id", payload.TaskID)}- signalTaskWakeup(taskWakeups)+ signalTaskWakeup(taskWakeups, payload.RuntimeID)case protocol.EventDaemonHeartbeatAck:var ack HeartbeatResponseif err := json.Unmarshal(msg.Payload, &ack); err != nil {@@ -291,9 +295,9 @@ func (d *Daemon) readTaskWakeupMessages(conn *websocket.Conn, taskWakeups chan<-}}-func signalTaskWakeup(taskWakeups chan<- struct{}) {+func signalTaskWakeup(taskWakeups chan<- taskWakeup, runtimeID string) {select {- case taskWakeups <- struct{}{}:+ case taskWakeups <- taskWakeup{runtimeID: runtimeID}:default:}}