Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): isolate runtime poll & heartbeat schedules per runtime (#2116)
Bohan Jiangb08594f2f63a
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 99c6b6682f..68bd10209e 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -6,6 +6,7 @@ import ("errors""fmt""log/slog"+ "math/rand""os""path/filepath""strconv"@@ -54,7 +55,7 @@ type Daemon struct {workspaces map[string]*workspaceStateruntimeIndex map[string]Runtime // runtimeID -> Runtime for provider lookupsreloading sync.Mutex // prevents concurrent workspace syncs- runtimeSetCh chan struct{} // notifies the WS wakeup loop to reconnect with a new runtime set+ runtimeSet *runtimeSetWatcher // multi-subscriber pub/sub for runtime-set changesversionsMu sync.RWMutex // guards agentVersionsagentVersions map[string]string // provider -> detected CLI version (set during registration)@@ -92,7 +93,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {logger: logger,workspaces: make(map[string]*workspaceState),runtimeIndex: make(map[string]Runtime),- runtimeSetCh: make(chan struct{}, 1),+ runtimeSet: newRuntimeSetWatcher(),agentVersions: make(map[string]string),wsHBLastAck: make(map[string]time.Time),activeEnvRoots: make(map[string]int),@@ -116,18 +117,48 @@ func (d *Daemon) agentVersion(provider string) string {}func (d *Daemon) notifyRuntimeSetChanged() {- select {- case d.runtimeSetCh <- struct{}{}:- default:+ d.runtimeSet.notify()+}++// runtimeSetWatcher is a tiny pub/sub for runtime-set changes. It exists+// because more than one supervisor (taskWakeupLoop, heartbeatLoop, pollLoop)+// needs to react to runtime-set changes; a single buffered channel would+// race so only the first listener would learn about each change.+//+// Each subscriber gets a 1-slot channel; missed nudges coalesce into a+// single signal — the subscriber is expected to re-derive the current+// runtime set via allRuntimeIDs() rather than relying on edge counts.+type runtimeSetWatcher struct {+ mu sync.Mutex+ subscribers map[chan struct{}]struct{}+}++func newRuntimeSetWatcher() *runtimeSetWatcher {+ return &runtimeSetWatcher{subscribers: make(map[chan struct{}]struct{})}+}++// Subscribe returns a channel that receives a non-blocking nudge whenever+// the runtime set changes, and an unsubscribe func the caller must invoke+// when done.+func (w *runtimeSetWatcher) Subscribe() (<-chan struct{}, func()) {+ ch := make(chan struct{}, 1)+ w.mu.Lock()+ w.subscribers[ch] = struct{}{}+ w.mu.Unlock()+ return ch, func() {+ w.mu.Lock()+ delete(w.subscribers, ch)+ w.mu.Unlock()}}-func (d *Daemon) drainRuntimeSetChanged() {- for {+func (w *runtimeSetWatcher) notify() {+ w.mu.Lock()+ defer w.mu.Unlock()+ for ch := range w.subscribers {select {- case <-d.runtimeSetCh:+ case ch <- struct{}{}:default:- return}}}@@ -222,7 +253,6 @@ func (d *Daemon) Run(ctx context.Context) error {go d.workspaceSyncLoop(ctx)taskWakeups := make(chan struct{}, 1)- d.drainRuntimeSetChanged()go d.taskWakeupLoop(ctx, taskWakeups)go d.heartbeatLoop(ctx)go d.gcLoop(ctx)@@ -667,36 +697,106 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context) error {return nil}+// heartbeatLoop supervises per-runtime HTTP heartbeat goroutines. Each runtime+// gets an independent ticker so a slow heartbeat for one runtime cannot block+// heartbeats for any other runtime — this matters when a single daemon serves+// multiple workspaces, because the previous shared loop would serialize an+// up-to-30s HTTP timeout across every runtime in the set.func (d *Daemon) heartbeatLoop(ctx context.Context) {- ticker := time.NewTicker(d.cfg.HeartbeatInterval)- defer ticker.Stop()+ runtimeSetCh, unsub := d.runtimeSet.Subscribe()+ defer unsub()++ cancels := make(map[string]context.CancelFunc)+ defer func() {+ for _, cancel := range cancels {+ cancel()+ }+ }()++ sync := func() {+ want := make(map[string]struct{})+ for _, rid := range d.allRuntimeIDs() {+ want[rid] = struct{}{}+ }+ for rid, cancel := range cancels {+ if _, ok := want[rid]; !ok {+ cancel()+ delete(cancels, rid)+ }+ }+ for rid := range want {+ if _, ok := cancels[rid]; ok {+ continue+ }+ rctx, rcancel := context.WithCancel(ctx)+ cancels[rid] = rcancel+ go d.runRuntimeHeartbeat(rctx, rid)+ }+ }++ sync()+ for {+ select {+ case <-ctx.Done():+ return+ case <-runtimeSetCh:+ sync()+ }+ }+}++// runRuntimeHeartbeat owns the HTTP heartbeat schedule for a single runtime.+// The first tick fires after a small jittered delay (up to one full interval)+// to avoid a thundering herd when the daemon registers many runtimes at once.+func (d *Daemon) runRuntimeHeartbeat(ctx context.Context, rid string) {+ interval := d.cfg.HeartbeatInterval+ if interval <= 0 {+ interval = 15 * time.Second+ }+ // Jittered initial delay; cap at the interval so the first beat still+ // happens within one period.+ if jitter := time.Duration(rand.Int63n(int64(interval))); jitter > 0 {+ select {+ case <-ctx.Done():+ return+ case <-time.After(jitter):+ }+ }+ d.runHeartbeatTick(ctx, rid)++ ticker := time.NewTicker(interval)+ defer ticker.Stop()for {select {case <-ctx.Done():returncase <-ticker.C:- for _, rid := range d.allRuntimeIDs() {- // Skip HTTP heartbeat for runtimes that successfully acked- // a recent WebSocket heartbeat. The WS path keeps last_seen_at- // fresh and delivers actions, so the HTTP write would be a- // duplicate DB update. If the WS heartbeat goes silent the- // freshness window expires and HTTP resumes automatically on- // the next tick — that is the fallback the WS path relies on.- if d.wsHeartbeatRecentlyAcked(rid) {- continue- }- resp, err := d.client.SendHeartbeat(ctx, rid)- if err != nil {- d.logger.Warn("heartbeat failed", "runtime_id", rid, "error", err)- continue- }- d.handleHeartbeatActions(ctx, rid, resp)- }+ d.runHeartbeatTick(ctx, rid)}}}+func (d *Daemon) runHeartbeatTick(ctx context.Context, rid string) {+ // Skip HTTP heartbeat for runtimes that successfully acked a recent+ // WebSocket heartbeat. The WS path keeps last_seen_at fresh and delivers+ // actions, so the HTTP write would be a duplicate DB update. If the WS+ // heartbeat goes silent the freshness window expires and HTTP resumes+ // automatically on the next tick — that is the fallback the WS path+ // relies on.+ if d.wsHeartbeatRecentlyAcked(rid) {+ return+ }+ resp, err := d.client.SendHeartbeat(ctx, rid)+ if err != nil {+ if ctx.Err() == nil {+ d.logger.Warn("heartbeat failed", "runtime_id", rid, "error", err)+ }+ return+ }+ d.handleHeartbeatActions(ctx, rid, resp)+}+// handleHeartbeatActions dispatches the pending-action set returned by either// transport (HTTP POST /api/daemon/heartbeat or WS daemon:heartbeat_ack).// Each action is dispatched in its own goroutine so a slow handler cannot@@ -1060,93 +1160,176 @@ func (d *Daemon) triggerRestart() {}}+// pollLoop supervises one runtimePoller goroutine per registered runtime,+// fans wake-up signals out to all of them, and waits for in-flight tasks to+// drain on shutdown. Per-runtime workers replace the previous round-robin+// 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 {sem := newTaskSlotSemaphore(d.cfg.MaxConcurrentTasks)- var wg sync.WaitGroup+ var taskWG sync.WaitGroup // tracks in-flight handleTask goroutines+ var pollerWG sync.WaitGroup // tracks runRuntimePoller goroutines++ runtimeSetCh, unsub := d.runtimeSet.Subscribe()+ defer unsub()++ type pollerHandle struct {+ cancel context.CancelFunc+ wakeup chan struct{}+ }+ pollers := make(map[string]*pollerHandle)++ syncPollers := func() {+ want := make(map[string]struct{})+ for _, rid := range d.allRuntimeIDs() {+ want[rid] = struct{}{}+ }+ for rid, h := range pollers {+ if _, ok := want[rid]; !ok {+ h.cancel()+ delete(pollers, rid)+ }+ }+ for rid := range want {+ if _, ok := pollers[rid]; ok {+ continue+ }+ pctx, pcancel := context.WithCancel(ctx)+ wakeup := make(chan struct{}, 1)+ pollers[rid] = &pollerHandle{cancel: pcancel, wakeup: wakeup}+ pollerWG.Add(1)+ go func(rid string, pctx context.Context, wakeup <-chan struct{}) {+ defer pollerWG.Done()+ d.runRuntimePoller(pctx, ctx, rid, sem, wakeup, &taskWG)+ }(rid, pctx, wakeup)+ }+ }++ syncPollers()- pollOffset := 0- pollCount := 0for {select {case <-ctx.Done():d.logger.Info("poll loop stopping, waiting for in-flight tasks", "max_wait", "30s")+ for _, h := range pollers {+ h.cancel()+ }+ // Wait for all pollers to fully return before waiting on taskWG.+ // Otherwise a poller that's between ClaimTask and taskWG.Add(1)+ // could race with taskWG.Wait when the counter is zero, which+ // is an undefined sync.WaitGroup misuse.+ pollerWG.Wait()+waitDone := make(chan struct{})- go func() { wg.Wait(); close(waitDone) }()+ go func() { taskWG.Wait(); close(waitDone) }()select {case <-waitDone:case <-time.After(30 * time.Second):d.logger.Warn("timed out waiting for in-flight tasks")}return ctx.Err()- default:+ 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.+ for _, h := range pollers {+ select {+ case h.wakeup <- struct{}{}:+ default:+ }+ }}+ }+}- runtimeIDs := d.allRuntimeIDs()- if len(runtimeIDs) == 0 {- if err := sleepWithContextOrWakeup(ctx, d.cfg.PollInterval, taskWakeups); err != nil {- wg.Wait()- return err- }- continue+// runRuntimePoller is the per-runtime claim+dispatch loop. It owns its own+// poll cadence and wakeup channel so that a slow HTTP claim for this runtime+// cannot delay any other runtime's claims.+//+// The execution slot is acquired BEFORE ClaimTask. The alternative —+// claiming first and then waiting for a slot — would let claimed tasks pile+// up in the server-side `dispatched` state without a corresponding+// StartTask, and the server's sweeper would fail them as `failed/timeout`+// after dispatchTimeoutSeconds=300s (runtime_sweeper.go:25). That is the+// exact user-visible failure this issue is fixing, so we cannot risk+// recreating it under load.+//+// Slot-before-claim does mean a slow claim holds a slot during its HTTP+// roundtrip; the upper bound is `client.Timeout = 30s` (client.go:59), well+// below the 300s dispatch timeout, so other runtimes' tasks stay in+// server-side `queued` state (which has no timeout) rather than entering+// `dispatched` and racing the sweeper.+//+// pollerCtx is cancelled when this runtime is removed from the watched set+// (e.g. workspace de-registered). parentCtx is the daemon's root ctx and is+// passed to handleTask so an in-flight task is not killed just because the+// runtime set changed mid-flight — the task continues to run until the+// daemon itself shuts down (or the server cancels it).+func (d *Daemon) runRuntimePoller(+ pollerCtx, parentCtx context.Context,+ rid string,+ sem chan int,+ wakeup <-chan struct{},+ taskWG *sync.WaitGroup,+) {+ for {+ if pollerCtx.Err() != nil {+ return}- claimed := false- n := len(runtimeIDs)- for i := 0; i < n; i++ {- // Check if we have capacity before claiming.- var slot int- select {- case slot = <-sem:- // Acquired a slot.- default:- // All slots occupied, stop trying to claim.- d.logger.Debug("poll: at capacity", "running", d.cfg.MaxConcurrentTasks)- goto sleep+ // 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():+ return+ default:+ d.logger.Debug("poll: at capacity", "runtime_id", rid, "running", d.cfg.MaxConcurrentTasks)+ if err := sleepWithContextOrWakeup(pollerCtx, d.cfg.PollInterval, wakeup); err != nil {+ return}+ continue+ }- rid := runtimeIDs[(pollOffset+i)%n]- task, err := d.client.ClaimTask(ctx, rid)- if err != nil {- sem <- slot // Release the slot.+ task, err := d.client.ClaimTask(pollerCtx, rid)+ if err != nil {+ sem <- slot+ if pollerCtx.Err() == nil {d.logger.Warn("claim task failed", "runtime_id", rid, "error", err)- continue}- if task != nil {- taskTarget := task.IssueID- if taskTarget == "" && task.ChatSessionID != "" {- taskTarget = "chat:" + shortID(task.ChatSessionID)- }- d.logger.Info("task received", "task", shortID(task.ID), "target", taskTarget)- wg.Add(1)- d.activeTasks.Add(1)- go func(t Task, slot int) {- defer wg.Done()- defer d.activeTasks.Add(-1)- defer func() { sem <- slot }()- d.handleTask(ctx, t, slot)- }(*task, slot)- claimed = true- pollOffset = (pollOffset + i + 1) % n- break+ if err := sleepWithContextOrWakeup(pollerCtx, d.cfg.PollInterval, wakeup); err != nil {+ return}- // No task for this runtime, release the slot and try next.- sem <- slot+ continue}- sleep:- if !claimed {- pollCount++- if pollCount%20 == 1 {- d.logger.Debug("poll: no tasks", "runtimes", runtimeIDs, "cycle", pollCount)- }- pollOffset = (pollOffset + 1) % n- if err := sleepWithContextOrWakeup(ctx, d.cfg.PollInterval, taskWakeups); err != nil {- wg.Wait()- return err+ if task == nil {+ sem <- slot+ if err := sleepWithContextOrWakeup(pollerCtx, d.cfg.PollInterval, wakeup); err != nil {+ return}- } else {- pollCount = 0+ continue+ }++ taskTarget := task.IssueID+ if taskTarget == "" && task.ChatSessionID != "" {+ taskTarget = "chat:" + shortID(task.ChatSessionID)}+ d.logger.Info("task received", "task", shortID(task.ID), "target", taskTarget)+ taskWG.Add(1)+ d.activeTasks.Add(1)+ go func(t Task, slot int) {+ defer taskWG.Done()+ defer d.activeTasks.Add(-1)+ defer func() { sem <- slot }()+ d.handleTask(parentCtx, t, slot)+ }(*task, slot)+ // Loop immediately: more tasks may already be queued for this runtime.}}diff --git a/server/internal/daemon/runtime_isolation_test.go b/server/internal/daemon/runtime_isolation_test.gonew file mode 100644index 0000000000..d580160345--- /dev/null+++ b/server/internal/daemon/runtime_isolation_test.go@@ -0,0 +1,336 @@+package daemon++import (+ "context"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"+)++// TestRuntimeSetWatcherFanOut pins the multi-subscriber contract: every+// subscribed channel must receive a nudge on each notify, and unsubscribed+// channels must not.+func TestRuntimeSetWatcherFanOut(t *testing.T) {+ t.Parallel()++ w := newRuntimeSetWatcher()+ chA, unsubA := w.Subscribe()+ chB, unsubB := w.Subscribe()+ defer unsubA()+ defer unsubB()++ w.notify()+ for _, ch := range []<-chan struct{}{chA, chB} {+ select {+ case <-ch:+ case <-time.After(time.Second):+ t.Fatal("expected each subscriber to receive a nudge")+ }+ }++ // Coalescing: a second notify before the subscriber drains must not+ // block, and the subscriber should still see exactly one pending nudge.+ w.notify()+ w.notify()+ select {+ case <-chA:+ default:+ t.Fatal("expected coalesced nudge to be pending")+ }+ select {+ case <-chA:+ t.Fatal("expected only one coalesced nudge to be queued")+ default:+ }++ // Unsubscribed channels must not get nudges. Drain any in-flight nudge+ // on chB first so we observe only post-unsubscribe behaviour.+ select {+ case <-chB:+ default:+ }+ unsubB()+ w.notify()+ select {+ case <-chB:+ t.Fatal("unsubscribed channel must not receive a nudge")+ case <-time.After(50 * time.Millisecond):+ }+}++// TestRunRuntimePollerIsolatesSlowRuntime is the regression test for+// MUL-1744's main symptom: a slow ClaimTask on one runtime must not delay+// claims on any other runtime. The pre-refactor pollLoop's serial round-+// robin made every runtime wait behind the slow one's HTTP roundtrip.+//+// MaxConcurrentTasks=4 leaves headroom so each runtime gets its own slot.+// The poller does acquire a slot before claiming (see runRuntimePoller for+// why), so this test deliberately uses a capacity that fits both runtimes+// concurrently — that's the case where slot-before-claim still gives full+// isolation.+func TestRunRuntimePollerIsolatesSlowRuntime(t *testing.T) {+ t.Parallel()++ var fastClaims atomic.Int64+ slowEntered := make(chan struct{}, 1)+ releaseSlow := make(chan struct{})++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ path := r.URL.Path+ switch {+ case strings.HasSuffix(path, "/runtimes/runtime-slow/tasks/claim"):+ select {+ case slowEntered <- struct{}{}:+ default:+ }+ select {+ case <-releaseSlow:+ case <-r.Context().Done():+ }+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"task":null}`))+ case strings.HasSuffix(path, "/runtimes/runtime-fast/tasks/claim"):+ fastClaims.Add(1)+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"task":null}`))+ default:+ http.Error(w, "unexpected path: "+path, http.StatusNotFound)+ }+ }))+ defer srv.Close()+ defer close(releaseSlow)++ d := New(Config{+ ServerBaseURL: srv.URL,+ HeartbeatInterval: time.Hour, // disable WS-suppression effects+ PollInterval: 50 * time.Millisecond,+ MaxConcurrentTasks: 4,+ }, slog.New(slog.NewTextHandler(noopWriter{}, nil)))++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ sem := newTaskSlotSemaphore(d.cfg.MaxConcurrentTasks)+ var taskWG sync.WaitGroup++ slowCtx, slowCancel := context.WithCancel(ctx)+ defer slowCancel()+ go d.runRuntimePoller(slowCtx, ctx, "runtime-slow", sem, make(chan struct{}, 1), &taskWG)++ fastCtx, fastCancel := context.WithCancel(ctx)+ defer fastCancel()+ go d.runRuntimePoller(fastCtx, ctx, "runtime-fast", sem, make(chan struct{}, 1), &taskWG)++ // Wait for the slow handler to actually enter (so we know its claim is+ // in flight) before checking fast-runtime progress.+ select {+ case <-slowEntered:+ case <-time.After(2 * time.Second):+ t.Fatal("slow runtime claim never entered server handler")+ }++ // Within a short window, the fast runtime should issue several claims.+ // Pre-isolation, it would be stuck behind the still-blocked slow claim.+ deadline := time.After(2 * time.Second)+ for fastClaims.Load() < 3 {+ select {+ case <-deadline:+ t.Fatalf("fast runtime made only %d claims while slow runtime blocked; expected ≥3", fastClaims.Load())+ case <-time.After(20 * time.Millisecond):+ }+ }+}++// TestRunRuntimePollerSkipsClaimWhenAtCapacity pins the slot-before-claim+// invariant: when no execution slots are available, the poller must NOT+// call ClaimTask. Pre-claiming and then waiting for a slot would let the+// task pile up in server-side `dispatched` state and race the 5-minute+// `dispatchTimeoutSeconds` sweeper, recreating the exact failure mode this+// issue is fixing.+func TestRunRuntimePollerSkipsClaimWhenAtCapacity(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: 20 * time.Millisecond,+ MaxConcurrentTasks: 1,+ }, slog.New(slog.NewTextHandler(noopWriter{}, nil)))++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ // Drain the only slot to simulate a long-running handleTask occupying+ // capacity. The poller must observe an empty sem and skip ClaimTask.+ sem := newTaskSlotSemaphore(d.cfg.MaxConcurrentTasks)+ <-sem // hold it: never returned during this test++ var taskWG sync.WaitGroup+ go d.runRuntimePoller(ctx, ctx, "runtime-busy", sem, make(chan struct{}, 1), &taskWG)++ // Give the poller several PollInterval ticks to race against the empty+ // sem. With slot-before-claim it must report zero claim attempts; the+ // older "claim first" path would have hammered ClaimTask each tick.+ time.Sleep(200 * time.Millisecond)++ if got := claimAttempts.Load(); got != 0 {+ t.Fatalf("poller called ClaimTask %d times while at capacity; want 0 — pre-claiming risks server-side dispatch_timeout", got)+ }+}++// 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+// taskWG.Add(1). The supervisor uses a separate pollerWG that this test+// implicitly exercises by running shutdown concurrently with a task being+// dispatched.+func TestPollLoopShutdownWaitsForPollersBeforeTaskWG(t *testing.T) {+ t.Parallel()++ taskID := "00000000-0000-0000-0000-000000000001"+ releaseClaim := make(chan struct{})++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ path := r.URL.Path+ w.Header().Set("Content-Type", "application/json")+ switch {+ case strings.HasSuffix(path, "/tasks/claim"):+ // Block until the test releases. When released, return a real task+ // so the poller proceeds into the slot/dispatch path — exactly the+ // window where taskWG.Add(1) races with shutdown's taskWG.Wait.+ select {+ case <-releaseClaim:+ case <-r.Context().Done():+ w.Write([]byte(`{"task":null}`))+ return+ }+ w.Write([]byte(`{"task":{"id":"` + taskID + `","runtime_id":"runtime-1","issue_id":"issue-1","agent":{"name":"test"}}}`))+ case strings.HasSuffix(path, "/start"):+ w.Write([]byte(`{}`))+ case strings.HasSuffix(path, "/fail"):+ w.Write([]byte(`{}`))+ case strings.HasSuffix(path, "/complete"):+ w.Write([]byte(`{}`))+ case strings.HasSuffix(path, "/progress"):+ w.Write([]byte(`{}`))+ default:+ w.Write([]byte(`{}`))+ }+ }))+ defer srv.Close()++ d := New(Config{+ ServerBaseURL: srv.URL,+ HeartbeatInterval: time.Hour,+ PollInterval: 50 * time.Millisecond,+ MaxConcurrentTasks: 1,+ }, slog.New(slog.NewTextHandler(noopWriter{}, nil)))+ d.workspaces["ws-1"] = &workspaceState{+ workspaceID: "ws-1",+ runtimeIDs: []string{"runtime-1"},+ }++ ctx, cancel := context.WithCancel(context.Background())+ pollDone := make(chan error, 1)+ go func() {+ pollDone <- d.pollLoop(ctx, nil)+ }()++ // Let the poller enter ClaimTask, then trigger shutdown right as the+ // claim is about to return a task. The race is the window between+ // ClaimTask returning and taskWG.Add(1) executing.+ time.Sleep(100 * time.Millisecond)+ close(releaseClaim)+ cancel()++ select {+ case <-pollDone:+ case <-time.After(5 * time.Second):+ t.Fatal("pollLoop did not return within shutdown deadline")+ }+}++// TestRunRuntimeHeartbeatIsolatesSlowRuntime is the heartbeat-side mirror of+// the poll-isolation test: a slow SendHeartbeat for one runtime must not+// block other runtimes' heartbeats.+func TestRunRuntimeHeartbeatIsolatesSlowRuntime(t *testing.T) {+ t.Parallel()++ var fastBeats atomic.Int64+ slowEntered := make(chan struct{}, 1)+ releaseSlow := make(chan struct{})++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body := make([]byte, 1024)+ n, _ := r.Body.Read(body)+ payload := string(body[:n])+ switch {+ case strings.Contains(payload, `"runtime-slow"`):+ select {+ case slowEntered <- struct{}{}:+ default:+ }+ select {+ case <-releaseSlow:+ case <-r.Context().Done():+ }+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{}`))+ case strings.Contains(payload, `"runtime-fast"`):+ fastBeats.Add(1)+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{}`))+ default:+ http.Error(w, "unexpected payload", http.StatusBadRequest)+ }+ }))+ defer srv.Close()+ defer close(releaseSlow)++ d := New(Config{+ ServerBaseURL: srv.URL,+ HeartbeatInterval: 50 * time.Millisecond,+ }, slog.New(slog.NewTextHandler(noopWriter{}, nil)))++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ go d.runRuntimeHeartbeat(ctx, "runtime-slow")+ go d.runRuntimeHeartbeat(ctx, "runtime-fast")++ select {+ case <-slowEntered:+ case <-time.After(2 * time.Second):+ t.Fatal("slow heartbeat never entered server handler")+ }++ deadline := time.After(2 * time.Second)+ for fastBeats.Load() < 3 {+ select {+ case <-deadline:+ t.Fatalf("fast runtime sent only %d heartbeats while slow runtime blocked; expected ≥3", fastBeats.Load())+ case <-time.After(20 * time.Millisecond):+ }+ }+}++// noopWriter discards log output so the test runner doesn't get noisy.+type noopWriter struct{}++func (noopWriter) Write(p []byte) (int, error) { return len(p), nil }diff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.goindex efb51161c6..aa6813d29b 100644--- a/server/internal/daemon/wakeup.go+++ b/server/internal/daemon/wakeup.go@@ -20,17 +20,19 @@ var errRuntimeSetChanged = errors.New("runtime set changed")func (d *Daemon) taskWakeupLoop(ctx context.Context, taskWakeups chan<- struct{}) {backoff := time.Second+ runtimeSetCh, unsub := d.runtimeSet.Subscribe()+ defer unsub()for {runtimeIDs := d.allRuntimeIDs()if len(runtimeIDs) == 0 {- if err := sleepWithContextOrRuntimeChange(ctx, 5*time.Second, d.runtimeSetCh); err != nil {+ if err := sleepWithContextOrRuntimeChange(ctx, 5*time.Second, runtimeSetCh); err != nil {return}continue}- err := d.runTaskWakeupConnection(ctx, runtimeIDs, taskWakeups)+ err := d.runTaskWakeupConnection(ctx, runtimeIDs, taskWakeups, runtimeSetCh)if ctx.Err() != nil {return}@@ -42,7 +44,7 @@ func (d *Daemon) taskWakeupLoop(ctx context.Context, taskWakeups chan<- struct{}d.logger.Debug("task wakeup websocket unavailable; polling fallback remains active", "error", err, "retry_in", backoff)}- if err := sleepWithContextOrRuntimeChange(ctx, jitterDuration(backoff), d.runtimeSetCh); err != nil {+ if err := sleepWithContextOrRuntimeChange(ctx, jitterDuration(backoff), runtimeSetCh); err != nil {return}if backoff < 30*time.Second {@@ -66,7 +68,7 @@ func jitterDuration(d time.Duration) time.Duration {return d + delta}-func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []string, taskWakeups chan<- struct{}) error {+func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []string, taskWakeups chan<- struct{}, runtimeSetCh <-chan struct{}) error {wsURL, err := taskWakeupURL(d.cfg.ServerBaseURL, runtimeIDs)if err != nil {return err@@ -101,8 +103,16 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strin// Serialize all writes through a single channel: the gorilla/websocket// Conn does not allow concurrent WriteMessage calls, and the heartbeat- // sender now coexists with future server-initiated writes.- writes := make(chan []byte, 8)+ // sender now coexists with future server-initiated writes. The buffer+ // is sized to fit a full per-runtime heartbeat batch plus headroom; a+ // fixed 8-slot queue would silently drop heartbeats once a daemon+ // watched more than ~8 runtimes (typical when one machine connects to+ // several workspaces), even when the network was healthy.+ writeBufSize := 16+ if 2*len(runtimeIDs) > writeBufSize {+ writeBufSize = 2 * len(runtimeIDs)+ }+ writes := make(chan []byte, writeBufSize)writerDone := make(chan struct{})go d.runWSWriter(conn, writes, writerDone)@@ -138,7 +148,7 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strinselect {case <-ctx.Done():return ctx.Err()- case <-d.runtimeSetCh:+ case <-runtimeSetCh:return errRuntimeSetChangedcase err := <-errCh:return err