Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
Machine-level batch task claim endpoint (MUL-4257) (#5193)
Multica Evec3dd9ec84546
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 1c1a138546..10795cce9c 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -601,6 +601,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Wire WS heartbeat after stores are finalized so the WS path uses the// same (possibly Redis-backed) stores as the HTTP path.daemonHub.SetHeartbeatHandler(h.HandleDaemonWSHeartbeat)+ // WS-first claim (MUL-4257): route daemon:rpc_request frames (e.g.+ // tasks.claim) through the same handlers as the HTTP endpoints.+ daemonHub.SetRPCHandler(h.DaemonRPCHandler)health := newServerHealth(pool)r := chi.NewRouter()@@ -730,6 +733,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/workspaces/{workspaceId}/runtime-profiles", h.DaemonListRuntimeProfiles)r.Post("/runtimes/{runtimeId}/tasks/claim", h.ClaimTaskByRuntime)+ // Canonical machine-level batch claim (MUL-4257). `/claim` is a+ // transitional alias; the daemon coordinator targets the canonical+ // path.+ r.Post("/tasks/claim", h.ClaimTasksByRuntime)+ r.Post("/claim", h.ClaimTasksByRuntime)r.Post("/runtimes/{runtimeId}/tasks/{taskId}/prepare-lease", h.ExtendTaskPrepareLease)r.Post("/runtimes/{runtimeId}/tasks/{taskId}/skill-bundles/resolve", h.ResolveTaskSkillBundles)r.Get("/runtimes/{runtimeId}/tasks/pending", h.ListPendingTasksByRuntime)diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 2336859849..d71d351acf 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -166,10 +166,20 @@ func (c *Client) setIdentityHeaders(req *http.Request) {if c.os != "" {req.Header.Set("X-Client-OS", c.os)}- req.Header.Set("X-Client-Capabilities", strings.Join([]string{+ req.Header.Set("X-Client-Capabilities", daemonClientCapabilities())+}++// daemonClientCapabilities is the X-Client-Capabilities value the daemon+// advertises on BOTH the HTTP control-plane requests and the WS handshake, so a+// claim built over WS gets the same capability gating (skill refs,+// coalesced-comments) as the HTTP path. rpc-v1 advertises WS request/response+// support (MUL-4257).+func daemonClientCapabilities() string {+ return strings.Join([]string{protocol.DaemonCapabilitySkillBundlesV1,protocol.DaemonCapabilityCoalescedCommentsV1,- }, ","))+ protocol.DaemonCapabilityRPCV1,+ }, ",")}// SetToken sets the auth token for authenticated requests.@@ -192,6 +202,86 @@ func (c *Client) ClaimTask(ctx context.Context, runtimeID string) (*Task, error)return resp.Task, nil}+// batchClaimRequestTimeout is the short, request-scoped deadline for the+// machine-level batch claim (MUL-4257). Unlike the per-runtime claim — which+// gets the full 30s control-plane timeout because a stall there only blocks+// that one runtime's goroutine — the batch call covers every runtime the+// daemon hosts in a single request, so a slow claim would delay ALL of them+// (the head-of-line coupling the per-runtime pollers were split to avoid,+// MUL-1744). Bounding the batch to a few seconds caps that worst-case+// starvation; a claim that commits server-side after the client gives up is+// recovered by ReclaimStaleDispatchedTasksForRuntimes on the next poll. Kept+// comfortably above p99 claim latency so recovery stays the exception.+const batchClaimRequestTimeout = 5 * time.Second++// ClaimTasks is the machine-level (MUL-4257) batch counterpart of ClaimTask:+// it asks the server, in a single request, to claim up to maxTasks tasks across+// every runtime the daemon hosts. daemonID scopes the request to this machine —+// the server rejects any runtime_id whose runtime.daemon_id doesn't match, so a+// stale/crossed runtime set can't claim another machine's tasks. Each returned+// Task carries its own RuntimeID so the daemon routes it to the matching+// runtime locally. The request runs under a short, request-scoped deadline+// (batchClaimRequestTimeout) rather than the shared 30s control-plane timeout so+// one slow claim cannot stall the whole batch; the deadline propagates to the+// server and cancels the in-flight query there too.+func (c *Client) ClaimTasks(ctx context.Context, daemonID string, runtimeIDs []string, maxTasks int) ([]*Task, error) {+ reqCtx, cancel := context.WithTimeout(ctx, batchClaimRequestTimeout)+ defer cancel()+ var resp struct {+ Tasks []*Task `json:"tasks"`+ }+ if err := c.postJSON(reqCtx, "/api/daemon/tasks/claim", map[string]any{+ "daemon_id": daemonID,+ "runtime_ids": runtimeIDs,+ "max_tasks": maxTasks,+ }, &resp); err != nil {+ return nil, err+ }+ return resp.Tasks, nil+}++// isBatchClaimUnsupported reports whether err is a 404 from the batch claim+// endpoint — i.e. the server predates the /api/daemon/tasks/claim route and the+// daemon must fall back to the legacy per-runtime claim (MUL-4257). The batch+// handler itself never returns 404, so a 404 here means the route is+// unregistered on an un-upgraded server.+func isBatchClaimUnsupported(err error) bool {+ var reqErr *requestError+ if !errors.As(err, &reqErr) {+ return false+ }+ return reqErr.StatusCode == http.StatusNotFound+}++// claimTasksLegacy is the pre-batch compatibility fallback (MUL-4257): claim per+// runtime via the legacy POST /api/daemon/runtimes/{id}/tasks/claim so a new+// daemon still works against a server that has no batch route. Returns up to+// maxTasks tasks. A per-runtime error is only propagated when nothing has been+// claimed yet; otherwise the partial result is returned and the next poll+// retries the rest.+func (c *Client) claimTasksLegacy(ctx context.Context, runtimeIDs []string, maxTasks int) ([]*Task, error) {+ if maxTasks <= 0 {+ return nil, nil+ }+ out := make([]*Task, 0, maxTasks)+ for _, rid := range runtimeIDs {+ if len(out) >= maxTasks {+ break+ }+ task, err := c.ClaimTask(ctx, rid)+ if err != nil {+ if len(out) == 0 {+ return nil, err+ }+ return out, nil+ }+ if task != nil {+ out = append(out, task)+ }+ }+ return out, nil+}+// ResolveSkillBundle downloads a single skill bundle. It uses bundleClient (no// fixed timeout) so the deadline is governed entirely by ctx, which the daemon// scales to the bundle's size, and retries transient transport blips withindiff --git a/server/internal/daemon/client_batch_claim_test.go b/server/internal/daemon/client_batch_claim_test.gonew file mode 100644index 0000000000..a76cdc852d--- /dev/null+++ b/server/internal/daemon/client_batch_claim_test.go@@ -0,0 +1,83 @@+package daemon++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "testing"+)++// TestClient_ClaimTasks_PostsRuntimeSetAndParsesTasks verifies the machine-level+// batch claim (MUL-4257): the client POSTs to /api/daemon/tasks/claim with the full+// runtime_id set + max_tasks, and parses the {"tasks":[...]} envelope, keeping+// each task's runtime_id so the daemon can route it locally.+func TestClient_ClaimTasks_PostsRuntimeSetAndParsesTasks(t *testing.T) {+ var gotPath string+ var gotBody struct {+ DaemonID string `json:"daemon_id"`+ RuntimeIDs []string `json:"runtime_ids"`+ MaxTasks int `json:"max_tasks"`+ }++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotPath = r.URL.Path+ body, _ := io.ReadAll(r.Body)+ _ = json.Unmarshal(body, &gotBody)+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"tasks":[+ {"id":"t1","runtime_id":"rt-a","agent":{"name":"a"}},+ {"id":"t2","runtime_id":"rt-b","agent":{"name":"b"}}+ ]}`))+ }))+ defer srv.Close()++ c := NewClient(srv.URL)+ c.SetToken("tok")++ tasks, err := c.ClaimTasks(context.Background(), "daemon-x", []string{"rt-a", "rt-b", "rt-c"}, 3)+ if err != nil {+ t.Fatalf("ClaimTasks: %v", err)+ }++ if gotPath != "/api/daemon/tasks/claim" {+ t.Errorf("path = %q, want /api/daemon/tasks/claim", gotPath)+ }+ if gotBody.DaemonID != "daemon-x" {+ t.Errorf("posted daemon_id = %q, want daemon-x", gotBody.DaemonID)+ }+ if len(gotBody.RuntimeIDs) != 3 || gotBody.RuntimeIDs[0] != "rt-a" || gotBody.MaxTasks != 3 {+ t.Errorf("posted body = %+v, want runtime_ids=[rt-a rt-b rt-c] max_tasks=3", gotBody)+ }+ if len(tasks) != 2 {+ t.Fatalf("got %d tasks, want 2", len(tasks))+ }+ if tasks[0].ID != "t1" || tasks[0].RuntimeID != "rt-a" {+ t.Errorf("task[0] = %+v, want id=t1 runtime_id=rt-a", tasks[0])+ }+ if tasks[1].ID != "t2" || tasks[1].RuntimeID != "rt-b" {+ t.Errorf("task[1] = %+v, want id=t2 runtime_id=rt-b", tasks[1])+ }+}++// TestClient_ClaimTasks_EmptyResult confirms an empty batch (idle daemon) is+// returned as a nil/empty slice, not an error.+func TestClient_ClaimTasks_EmptyResult(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"tasks":[]}`))+ }))+ defer srv.Close()++ c := NewClient(srv.URL)+ c.SetToken("tok")++ tasks, err := c.ClaimTasks(context.Background(), "daemon-x", []string{"rt-a"}, 1)+ if err != nil {+ t.Fatalf("ClaimTasks: %v", err)+ }+ if len(tasks) != 0 {+ t.Fatalf("got %d tasks, want 0", len(tasks))+ }+}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 2f9cf077cb..4813c3b6ca 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -181,6 +181,19 @@ type Daemon struct {// reconcile.go and runTaskWakeupConnection.reconcile *reconcileBroadcaster+ // wsRPC carries generic request/response RPCs (e.g. tasks.claim, MUL-4257)+ // over the task-wakeup WS connection. It is attached to the live+ // connection in runTaskWakeupConnection and detached on disconnect; when+ // detached, callers fall back to HTTP.+ wsRPC *wsRPCClient++ // batchClaimUnsupported is set once a batch claim gets a 404 from the+ // server (no /api/daemon/tasks/claim route — an un-upgraded server), so+ // subsequent polls skip WS+batch and use the legacy per-runtime claim+ // directly. Reset when the WS (re)connects, so a server upgrade that+ // bounces the connection re-probes the batch route (MUL-4257).+ batchClaimUnsupported atomic.Bool+// runtimeGoneMu guards runtimeGoneInflight, reregisterNextAttempt, and// reregisterLastCompletedAt. The state lets heartbeat / poller / WS-ack// handlers converge on a single recovery path when they each detect that a@@ -211,7 +224,7 @@ type Daemon struct {// race where a new task slipping in during the release-metadata fetch// would be cancelled by triggerRestart's root-ctx cancel.claimMu sync.Mutex- pauseClaims bool // when true, runRuntimePoller skips ClaimTask+ pauseClaims bool // when true, the batch poller skips claimingclaimsInFlight int // pollers that have decided to claim but haven't yet handed the task off to handleTaskactiveEnvRootsMu sync.Mutex@@ -271,6 +284,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {reregisterLastCompletedAt: make(map[string]time.Time),cancelPollInterval: 5 * time.Second,reconcile: newReconcileBroadcaster(),+ wsRPC: newWSRPCClient(wsRPCResponseGrace),}d.runner = taskRunnerFunc(d.runTask)d.runUpdateFn = d.runUpdate@@ -2470,67 +2484,49 @@ 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.+// pollLoop runs the machine-level batch claim poller (MUL-4257): a single+// goroutine claims across ALL of the daemon's runtimes per cycle via+// ClaimTasksWSFirst (WS-first, HTTP fallback), replacing the previous+// one-HTTP-poller-per-runtime model. Wake-up signals — a WS task_available /+// catch-up nudge or a runtime-set change — all collapse to one nudge because a+// batch claim already covers every runtime. On shutdown it stops the poller,+// then drains in-flight tasks.+//+// This trades the per-runtime isolation the old model gave (MUL-1744) for a+// single request; the head-of-line risk is bounded by ClaimTasksWSFirst's short+// per-request timeout (WS) / the client's timeout (HTTP fallback), and the+// server-side batch claim is index-backed + short.func (d *Daemon) pollLoop(ctx context.Context, taskWakeups <-chan taskWakeup) error {sem := newTaskSlotSemaphore(d.cfg.MaxConcurrentTasks)- var taskWG sync.WaitGroup // tracks in-flight handleTask goroutines- var pollerWG sync.WaitGroup // tracks runRuntimePoller goroutines+ var taskWG sync.WaitGroup // tracks in-flight handleTask goroutinesruntimeSetCh, 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)+ wakeup := make(chan struct{}, 1)+ nudge := func() {+ select {+ case wakeup <- struct{}{}:+ default:}}- syncPollers()+ pollerCtx, pollerCancel := context.WithCancel(ctx)+ pollerDone := make(chan struct{})+ go func() {+ defer close(pollerDone)+ d.runBatchPoller(pollerCtx, ctx, sem, wakeup, &taskWG)+ }()for {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()-+ pollerCancel()+ // Wait for the poller to fully return before waiting on taskWG so a+ // poller between ClaimTasksWSFirst and taskWG.Add(1) cannot race+ // taskWG.Wait at a zero counter.+ <-pollerDonewaitDone := make(chan struct{})go func() { taskWG.Wait(); close(waitDone) }()select {@@ -2540,69 +2536,31 @@ func (d *Daemon) pollLoop(ctx context.Context, taskWakeups <-chan taskWakeup) er}return ctx.Err()case <-runtimeSetCh:- syncPollers()- 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 {- case h.wakeup <- struct{}{}:- default:- }- }+ // The batch poller re-derives allRuntimeIDs() each cycle; nudge it to+ // pick up a registered/removed runtime promptly.+ nudge()+ case <-taskWakeups:+ // Targeted-runtime and catch-up wakeups both trigger one batch claim+ // across the whole runtime set.+ nudge()}}}-// 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.+// runBatchPoller is the single machine-level claim+dispatch loop. Each cycle it+// acquires whatever execution slots are free (slot-before-claim, so a claimed+// task never sits server-side `dispatched` without local capacity to run it and+// race the dispatch-timeout sweeper), asks the server for up to that many tasks+// across all of the daemon's runtimes in one call, and dispatches each returned+// task — routed to its runtime by handleTask — into a slot.//-// 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,-) {- 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+// pollerCtx is cancelled on shutdown. parentCtx is the daemon root ctx passed to+// handleTask so an in-flight task is not killed just because the poll loop is+// stopping mid-flight.+func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan int, wakeup <-chan struct{}, taskWG *sync.WaitGroup) {+ releaseSlots := func(slots []int) {+ for _, sl := range slots {+ sem <- sl}}@@ -2611,15 +2569,21 @@ func (d *Daemon) runRuntimePoller(return}- // 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.+ runtimeIDs := d.allRuntimeIDs()+ if len(runtimeIDs) == 0 {+ if err := sleepWithContextOrWakeup(pollerCtx, d.cfg.PollInterval, wakeup); err != nil {+ return+ }+ continue+ }++ // Acquire at least one slot (blocking briefly), then grab any other free+ // slots so a single batch claim can fill them all.slot, acquired, woke, err := waitForTaskSlot(pollerCtx, sem, wakeup, taskSlotWaitTimeout)if err != nil {return}if !acquired {- d.logger.Debug("poll: at capacity", "runtime_id", rid, "running", d.cfg.MaxConcurrentTasks)if woke {continue}@@ -2628,34 +2592,24 @@ func (d *Daemon) runRuntimePoller(}continue}+ slots := append([]int{slot}, drainAvailableSlots(sem, d.cfg.MaxConcurrentTasks-1)...)- // Refuse new claims while an auto-update is preparing to roll the- // process. The barrier is paired with a re-check of claimsInFlight +- // activeTasks inside tryAutoUpdate, so once we get past tryEnterClaim- // the auto-update path is guaranteed to defer until this poller has- // handed the task off (or given up).+ // Auto-update barrier: refuse to claim while an update prepares to roll+ // the process (paired with the re-check in tryAutoUpdate).if !d.tryEnterClaim() {- sem <- slot+ releaseSlots(slots)if err := sleepWithContextOrWakeup(pollerCtx, d.cfg.PollInterval, wakeup); err != nil {return}continue}- task, err := d.client.ClaimTask(pollerCtx, rid)+ tasks, err := d.ClaimTasksWSFirst(pollerCtx, d.cfg.DaemonID, runtimeIDs, len(slots))if err != nil {d.exitClaim()- sem <- slot+ releaseSlots(slots)if pollerCtx.Err() == nil {- if isRuntimeNotFoundError(err) {- // Server says this runtime is gone — recover and exit- // the poller; the runtime-set watcher will tear this- // goroutine down via pollerCtx once the workspace is- // re-registered with a new runtime ID.- go d.handleRuntimeGone(rid)- return- }- d.logger.Warn("claim task failed", "runtime_id", rid, "error", err)+ d.logger.Warn("batch claim failed", "error", err)}if err := sleepWithContextOrWakeup(pollerCtx, d.cfg.PollInterval, wakeup); err != nil {return@@ -2663,40 +2617,63 @@ func (d *Daemon) runRuntimePoller(continue}- if task == nil {- d.exitClaim()- sem <- slot- if err := sleepWithContextOrWakeup(pollerCtx, d.cfg.PollInterval, wakeup); err != nil {- return+ // Dispatch each claimed task into a slot. activeTasks is incremented for+ // every dispatched task BEFORE exitClaim so the auto-update barrier never+ // sees a zero-claims / zero-active window between claim and dispatch.+ dispatched := 0+ for i := range tasks {+ if i >= len(slots) || tasks[i] == nil {+ break}+ t := *tasks[i]+ slot := slots[i]+ taskTarget := t.IssueID+ if taskTarget == "" && t.ChatSessionID != "" {+ taskTarget = "chat:" + shortID(t.ChatSessionID)+ }+ d.logger.Info("task received", "task", shortID(t.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)+ }(t, slot)+ dispatched+++ }+ d.exitClaim()+ if dispatched < len(slots) {+ releaseSlots(slots[dispatched:])+ }++ // If we filled every slot, more work may be queued — loop immediately.+ // Otherwise wait for the next wakeup / poll interval.+ if dispatched > 0 && dispatched == len(slots) {continue}-- taskTarget := task.IssueID- if taskTarget == "" && task.ChatSessionID != "" {- taskTarget = "chat:" + shortID(task.ChatSessionID)+ if err := sleepWithContextOrWakeup(pollerCtx, d.cfg.PollInterval, wakeup); err != nil {+ return}- 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.exitClaim()- 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.}}-func runtimePollOffset(runtimeID string, interval time.Duration) time.Duration {- if interval <= 0 || runtimeID == "" {- return 0+// drainAvailableSlots non-blockingly pulls up to max additional slots from the+// semaphore, returning immediately when none are free.+func drainAvailableSlots(sem chan int, max int) []int {+ if max <= 0 {+ return nil}- h := fnv.New64a()- _, _ = h.Write([]byte(runtimeID))- return time.Duration(h.Sum64() % uint64(interval))+ var slots []int+ for len(slots) < max {+ select {+ case s := <-sem:+ slots = append(slots, s)+ default:+ return slots+ }+ }+ return slots}func capacityBackoff(pollInterval time.Duration) time.Duration {diff --git a/server/internal/daemon/daemon_legacy_fallback_test.go b/server/internal/daemon/daemon_legacy_fallback_test.gonew file mode 100644index 0000000000..2ce98324cf--- /dev/null+++ b/server/internal/daemon/daemon_legacy_fallback_test.go@@ -0,0 +1,133 @@+package daemon++import (+ "context"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"+)++// TestClaimTasksWSFirst_LegacyFallbackWhenBatchRouteMissing pins the MUL-4257+// backward-compat fix: against a server that has no /api/daemon/tasks/claim+// route (returns 404), the daemon falls back to the legacy per-runtime+// POST /api/daemon/runtimes/{id}/tasks/claim loop, and remembers it so later+// polls skip the batch attempt.+func TestClaimTasksWSFirst_LegacyFallbackWhenBatchRouteMissing(t *testing.T) {+ var batchCalls, legacyCalls atomic.Int64+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ path := r.URL.Path+ switch {+ case strings.HasSuffix(path, "/api/daemon/tasks/claim"):+ batchCalls.Add(1)+ http.Error(w, "404 page not found", http.StatusNotFound)+ case strings.HasSuffix(path, "/runtimes/rt1/tasks/claim"):+ legacyCalls.Add(1)+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"task":{"id":"t1","runtime_id":"rt1","agent":{"name":"a"}}}`))+ case strings.HasSuffix(path, "/runtimes/rt2/tasks/claim"):+ legacyCalls.Add(1)+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"task":{"id":"t2","runtime_id":"rt2","agent":{"name":"b"}}}`))+ default:+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{}`))+ }+ }))+ defer srv.Close()++ d := New(Config{ServerBaseURL: srv.URL, MaxConcurrentTasks: 4}, slog.New(slog.NewTextHandler(noopWriter{}, nil)))++ tasks, err := d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1", "rt2"}, 5)+ if err != nil {+ t.Fatalf("ClaimTasksWSFirst: %v", err)+ }+ if len(tasks) != 2 {+ t.Fatalf("legacy fallback claimed %d tasks, want 2", len(tasks))+ }+ seen := map[string]bool{}+ for _, task := range tasks {+ seen[task.RuntimeID] = true+ }+ if !seen["rt1"] || !seen["rt2"] {+ t.Fatalf("expected tasks for rt1 and rt2, got %v", seen)+ }+ if batchCalls.Load() != 1 {+ t.Fatalf("batch route called %d times, want exactly 1 (the initial probe)", batchCalls.Load())+ }+ if !d.batchClaimUnsupported.Load() {+ t.Fatal("expected batchClaimUnsupported to be set after a 404")+ }++ // Second poll must skip the batch route entirely and go straight to legacy.+ if _, err := d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1", "rt2"}, 5); err != nil {+ t.Fatalf("second ClaimTasksWSFirst: %v", err)+ }+ if batchCalls.Load() != 1 {+ t.Fatalf("batch route retried after being marked unsupported; calls=%d", batchCalls.Load())+ }+}++// TestClaimTasksWSFirst_NoDoubleClaimOnDetach pins the Sol-Boy review fix: if+// the WS connection detaches while a tasks.claim RPC is in flight (its frame+// already sent), ClaimTasksWSFirst must NOT fall back to an HTTP claim for the+// same free slots — the WS claim may have committed server-side, and a second+// HTTP claim would double-claim. It returns no tasks; reclaim / the next poll+// recovers.+func TestClaimTasksWSFirst_NoDoubleClaimOnDetach(t *testing.T) {+ var httpClaims atomic.Int64+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if strings.Contains(r.URL.Path, "/claim") {+ httpClaims.Add(1)+ }+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"tasks":[{"id":"http-t","runtime_id":"rt1","agent":{"name":"a"}}]}`))+ }))+ defer srv.Close()++ d := New(Config{ServerBaseURL: srv.URL, MaxConcurrentTasks: 4}, slog.New(slog.NewTextHandler(noopWriter{}, nil)))+ // Sender enqueues the frame and hands back its cancelable handle; we then+ // mark it written to simulate the writer having put it on the wire, so the+ // disconnect leaves a genuinely uncertain outcome (the server may commit).+ var mu sync.Mutex+ var item *wsOutbound+ d.wsRPC.attach(func(frame []byte) (*wsOutbound, error) {+ mu.Lock()+ defer mu.Unlock()+ item = &wsOutbound{data: frame}+ return item, nil+ })++ done := make(chan struct{})+ var tasks []*Task+ var err error+ go func() {+ tasks, err = d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2)+ close(done)+ }()++ time.Sleep(50 * time.Millisecond) // let Call send the frame and block on the response+ mu.Lock()+ item.beginWrite() // frame is now on the wire — cannot be un-sent+ mu.Unlock()+ d.wsRPC.attach(nil) // detach mid-flight (reconnect / teardown)++ select {+ case <-done:+ case <-time.After(3 * time.Second):+ t.Fatal("ClaimTasksWSFirst did not return after detach")+ }+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if len(tasks) != 0 {+ t.Fatalf("expected no tasks on uncertain WS outcome, got %d", len(tasks))+ }+ if httpClaims.Load() != 0 {+ t.Fatalf("HTTP fallback claimed %d times after an uncertain WS claim; must be 0 to avoid double-claim", httpClaims.Load())+ }+}diff --git a/server/internal/daemon/runtime_isolation_test.go b/server/internal/daemon/runtime_isolation_test.goindex 32705ce244..cca8222d67 100644--- a/server/internal/daemon/runtime_isolation_test.go+++ b/server/internal/daemon/runtime_isolation_test.go@@ -63,27 +63,22 @@ func TestRuntimeSetWatcherFanOut(t *testing.T) {}}-// 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) {+// 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 fastClaims atomic.Int64+ var fastBeats atomic.Int64slowEntered := make(chan struct{}, 1)releaseSlow := make(chan struct{})srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- path := r.URL.Path+ body := make([]byte, 1024)+ n, _ := r.Body.Read(body)+ payload := string(body[:n])switch {- case strings.HasSuffix(path, "/runtimes/runtime-slow/tasks/claim"):+ case strings.Contains(payload, `"runtime-slow"`):select {case slowEntered <- struct{}{}:default:@@ -93,76 +88,72 @@ func TestRunRuntimePollerIsolatesSlowRuntime(t *testing.T) {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.Write([]byte(`{}`))+ case strings.Contains(payload, `"runtime-fast"`):+ fastBeats.Add(1)w.Header().Set("Content-Type", "application/json")- w.Write([]byte(`{"task":null}`))+ w.Write([]byte(`{}`))default:- http.Error(w, "unexpected path: "+path, http.StatusNotFound)+ http.Error(w, "unexpected payload", http.StatusBadRequest)}}))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,+ ServerBaseURL: srv.URL,+ HeartbeatInterval: 50 * time.Millisecond,}, 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)+ go d.runRuntimeHeartbeat(ctx, "runtime-slow")+ go d.runRuntimeHeartbeat(ctx, "runtime-fast")- // 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")+ t.Fatal("slow heartbeat 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 {+ for fastBeats.Load() < 3 {select {case <-deadline:- t.Fatalf("fast runtime made only %d claims while slow runtime blocked; expected ≥3", fastClaims.Load())+ t.Fatalf("fast runtime sent only %d heartbeats while slow runtime blocked; expected ≥3", fastBeats.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()+// noopWriter discards log output so the test runner doesn't get noisy.+type noopWriter struct{}- var claimAttempts atomic.Int64+func (noopWriter) Write(p []byte) (int, error) { return len(p), nil }+// TestRunBatchPollerClaimsAcrossRuntimes pins the machine-level cutover+// (MUL-4257): a single batch poller issues one claim across ALL of the daemon's+// runtimes (HTTP fallback here, since no WS is attached) and dispatches each+// returned task to its runtime.+func TestRunBatchPollerClaimsAcrossRuntimes(t *testing.T) {+ t.Parallel()++ var claimCalls atomic.Int64srv := 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}`))+ if strings.HasSuffix(r.URL.Path, "/api/daemon/tasks/claim") {+ if claimCalls.Add(1) == 1 {+ w.Write([]byte(`{"tasks":[+ {"id":"t1","runtime_id":"rt-1","issue_id":"i1","agent":{"name":"a"}},+ {"id":"t2","runtime_id":"rt-2","issue_id":"i2","agent":{"name":"b"}}+ ]}`))+ return+ }+ w.Write([]byte(`{"tasks":[]}`))+ return+ }+ w.Write([]byte(`{}`))}))defer srv.Close()@@ -170,294 +161,125 @@ func TestRunRuntimePollerSkipsClaimWhenAtCapacity(t *testing.T) {ServerBaseURL: srv.URL,HeartbeatInterval: time.Hour,PollInterval: 20 * time.Millisecond,- MaxConcurrentTasks: 1,+ MaxConcurrentTasks: 4,}, slog.New(slog.NewTextHandler(noopWriter{}, nil)))+ d.workspaces["ws-1"] = &workspaceState{workspaceID: "ws-1", runtimeIDs: []string{"rt-1", "rt-2"}}+ d.cancelPollInterval = time.Hour // no server-side cancellation polling in this test++ var mu sync.Mutex+ dispatched := map[string]int{}+ d.runner = taskRunnerFunc(func(ctx context.Context, task Task, provider string, slot int, log *slog.Logger) (TaskResult, error) {+ mu.Lock()+ dispatched[task.RuntimeID]+++ mu.Unlock()+ return TaskResult{Status: "completed"}, 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)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ go d.runBatchPoller(ctx, ctx, sem, make(chan struct{}, 1), &taskWG)++ deadline := time.After(3 * time.Second)+ for {+ mu.Lock()+ got1, got2 := dispatched["rt-1"], dispatched["rt-2"]+ mu.Unlock()+ if got1 >= 1 && got2 >= 1 {+ break+ }+ select {+ case <-deadline:+ t.Fatalf("batch poller did not dispatch both runtimes; got rt-1=%d rt-2=%d", got1, got2)+ case <-time.After(10 * time.Millisecond):+ }}+ cancel()+ taskWG.Wait()}-func TestRunRuntimePollerClaimsWhenSlotBecomesAvailable(t *testing.T) {+// TestRunBatchPollerSkipsClaimWhenAtCapacity pins slot-before-claim for the+// batch poller: with no free execution slots it must NOT claim, so tasks never+// pile up server-side `dispatched` and race the dispatch-timeout sweeper.+func TestRunBatchPollerSkipsClaimWhenAtCapacity(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") {+ if strings.Contains(r.URL.Path, "/claim") {claimAttempts.Add(1)}w.Header().Set("Content-Type", "application/json")- w.Write([]byte(`{"task":null}`))+ w.Write([]byte(`{"tasks":[]}`))}))defer srv.Close()d := New(Config{ServerBaseURL: srv.URL,HeartbeatInterval: time.Hour,- PollInterval: time.Hour,+ PollInterval: 20 * time.Millisecond,MaxConcurrentTasks: 1,}, slog.New(slog.NewTextHandler(noopWriter{}, nil)))-- ctx, cancel := context.WithCancel(context.Background())- defer cancel()+ d.workspaces["ws-1"] = &workspaceState{workspaceID: "ws-1", runtimeIDs: []string{"rt-1"}}sem := newTaskSlotSemaphore(d.cfg.MaxConcurrentTasks)- slot := <-sem+ <-sem // hold the only slot for the whole testvar taskWG sync.WaitGroup- wakeup := make(chan struct{}, 1)- go d.runRuntimePoller(ctx, ctx, "runtime-waiting", sem, wakeup, &taskWG)- wakeup <- struct{}{}+ ctx, cancel := context.WithCancel(context.Background())+ go d.runBatchPoller(ctx, ctx, sem, make(chan struct{}, 1), &taskWG)- time.Sleep(100 * time.Millisecond)+ time.Sleep(200 * 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):- }+ t.Fatalf("batch poller claimed %d times while at capacity; want 0", got)}+ cancel()}-// 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) {+// TestPollLoopBatchShutdown pins that pollLoop stops its single batch poller and+// returns promptly on ctx cancel even with a task in flight.+func TestPollLoopBatchShutdown(t *testing.T) {t.Parallel()- taskID := "00000000-0000-0000-0000-000000000001"- releaseClaim := make(chan struct{})-+ releaseRun := make(chan struct{})srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- path := r.URL.Pathw.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(`{}`))+ if strings.HasSuffix(r.URL.Path, "/api/daemon/tasks/claim") {+ w.Write([]byte(`{"tasks":[{"id":"t1","runtime_id":"rt-1","issue_id":"i1","agent":{"name":"a"}}]}`))+ return}+ w.Write([]byte(`{}`))}))defer srv.Close()+ defer close(releaseRun)d := New(Config{ServerBaseURL: srv.URL,HeartbeatInterval: time.Hour,- PollInterval: 50 * time.Millisecond,+ PollInterval: 20 * 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")- }-}--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+ d.workspaces["ws-1"] = &workspaceState{workspaceID: "ws-1", runtimeIDs: []string{"rt-1"}}+ d.cancelPollInterval = time.Hour+ d.runner = taskRunnerFunc(func(ctx context.Context, task Task, provider string, slot int, log *slog.Logger) (TaskResult, error) {+ // Block until the test releases or the run ctx is cancelled by shutdown.+ select {+ case <-releaseRun:+ case <-ctx.Done():}- 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"},- }+ return TaskResult{Status: "completed"}, nil+ })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)- }+ go func() { pollDone <- d.pollLoop(ctx, nil) }()+ time.Sleep(150 * time.Millisecond) // let it claim + enter the in-flight runcancel()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.-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):- }+ t.Fatal("pollLoop did not return within shutdown deadline")}}--// 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 3c6ba8e43c..b7219290e2 100644--- a/server/internal/daemon/wakeup.go+++ b/server/internal/daemon/wakeup.go@@ -10,6 +10,7 @@ import ("net/url""sort""strings"+ "sync""time""github.com/gorilla/websocket"@@ -109,6 +110,9 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strinif d.client.os != "" {headers.Set("X-Client-OS", d.client.os)}+ // Advertise the same capabilities as the HTTP path so a claim built over+ // this WS connection gets identical capability gating (MUL-4257).+ headers.Set("X-Client-Capabilities", daemonClientCapabilities())dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second}conn, _, err := dialer.DialContext(ctx, wsURL, headers)@@ -147,10 +151,34 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strinif 2*len(runtimeIDs) > writeBufSize {writeBufSize = 2 * len(runtimeIDs)}- writes := make(chan []byte, writeBufSize)+ writes := make(chan *wsOutbound, writeBufSize)writerDone := make(chan struct{})go d.runWSWriter(conn, writes, writerDone)+ // Attach the generic WS RPC sender (MUL-4257) to this connection's write+ // channel. Guarded so a Call racing teardown never sends on the closed+ // `writes` channel: teardown flips sendClosed under sendMu before+ // close(writes), and the sender holds sendMu across its non-blocking send.+ var sendMu sync.Mutex+ sendClosed := false+ d.wsRPC.attach(func(frame []byte) (*wsOutbound, error) {+ sendMu.Lock()+ defer sendMu.Unlock()+ if sendClosed {+ return nil, errWSRPCUnavailable+ }+ item := &wsOutbound{data: frame}+ select {+ case writes <- item:+ return item, nil+ default:+ return nil, errWSRPCWriteBufferFull+ }+ })+ // A (re)connect may be a freshly-upgraded server: re-probe the batch claim+ // route rather than staying on the legacy fallback forever (MUL-4257).+ d.batchClaimUnsupported.Store(false)+heartbeatCtx, cancelHeartbeat := context.WithCancel(ctx)hbDone := make(chan struct{})go func() {@@ -174,6 +202,22 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strin// LIFO defer order would close writes before the sender stops, so the// teardown is folded into a single deferred function instead.defer func() {+ // Close the socket FIRST, before failing pending RPCs. Otherwise a+ // queued tasks.claim frame would still be flushed to the (on a normal+ // runtimeSetCh reconnect) still-alive socket AFTER attach(nil) has made+ // the RPC fall over to HTTP — the server would then commit that WS+ // claim on top of the HTTP fallback, double-claiming the same free+ // slots (MUL-4257, Sol-Boy review). With the conn closed here,+ // runWSWriter's next write errors and it DISCARDS the queue instead of+ // delivering it.+ conn.Close()+ // Detach RPC (fails pending → HTTP fallback, now safe since the queued+ // frame will be dropped), and flip the send-closed flag under sendMu so+ // any in-flight guarded send finishes before we close writes.+ d.wsRPC.attach(nil)+ sendMu.Lock()+ sendClosed = true+ sendMu.Unlock()cancelHeartbeat()<-hbDoneclose(writes)@@ -193,11 +237,17 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strin// runWSWriter funnels writes from the heartbeat sender (and any future// daemon-initiated message) into a single goroutine. gorilla/websocket// requires that all WriteMessage calls happen from the same goroutine.-func (d *Daemon) runWSWriter(conn *websocket.Conn, writes <-chan []byte, done chan<- struct{}) {+func (d *Daemon) runWSWriter(conn *websocket.Conn, writes <-chan *wsOutbound, done chan<- struct{}) {defer close(done)- for frame := range writes {+ for item := range writes {+ // Skip frames whose RPC caller already gave up: delivering them after a+ // fallback would double-claim (MUL-4257). beginWrite also marks the+ // frame sent so a racing cancel() can no longer reclaim it.+ if !item.beginWrite() {+ continue+ }conn.SetWriteDeadline(time.Now().Add(10 * time.Second))- if err := conn.WriteMessage(websocket.TextMessage, frame); err != nil {+ if err := conn.WriteMessage(websocket.TextMessage, item.data); err != nil {d.logger.Debug("task wakeup websocket write failed", "error", err)conn.Close()// Drain remaining frames so the producers don't block forever@@ -215,7 +265,7 @@ func (d *Daemon) runWSWriter(conn *websocket.Conn, writes <-chan []byte, done ch// to the writer; if the queue is full the heartbeat is dropped (the// freshness window is short enough that one missed beat just means HTTP will// pick it up next tick).-func (d *Daemon) runWSHeartbeatSender(ctx context.Context, runtimeIDs []string, writes chan<- []byte) {+func (d *Daemon) runWSHeartbeatSender(ctx context.Context, runtimeIDs []string, writes chan<- *wsOutbound) {d.sendWSHeartbeats(ctx, runtimeIDs, writes)interval := d.cfg.HeartbeatIntervalif interval <= 0 {@@ -233,7 +283,7 @@ func (d *Daemon) runWSHeartbeatSender(ctx context.Context, runtimeIDs []string,}}-func (d *Daemon) sendWSHeartbeats(ctx context.Context, runtimeIDs []string, writes chan<- []byte) {+func (d *Daemon) sendWSHeartbeats(ctx context.Context, runtimeIDs []string, writes chan<- *wsOutbound) {for _, rid := range runtimeIDs {if ctx.Err() != nil {return@@ -247,7 +297,7 @@ func (d *Daemon) sendWSHeartbeats(ctx context.Context, runtimeIDs []string, writcontinue}select {- case writes <- frame:+ case writes <- &wsOutbound{data: frame}:case <-ctx.Done():returndefault:@@ -336,6 +386,13 @@ func (d *Daemon) readTaskWakeupMessages(conn *websocket.Conn, taskWakeups chan<-continue}d.handleWSHeartbeatAck(context.Background(), &ack)+ case protocol.EventDaemonRPCResponse:+ var resp protocol.RPCResponsePayload+ if err := json.Unmarshal(msg.Payload, &resp); err != nil {+ d.logger.Debug("ws rpc response invalid payload", "error", err)+ continue+ }+ d.wsRPC.deliver(resp)}}}diff --git a/server/internal/daemon/wsrpc.go b/server/internal/daemon/wsrpc.gonew file mode 100644index 0000000000..afed826ed1--- /dev/null+++ b/server/internal/daemon/wsrpc.go@@ -0,0 +1,306 @@+package daemon++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "sync"+ "time"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// errWSRPCUnavailable is returned by wsRPCClient.Call when there is no live WS+// connection to carry the request. Callers treat it as the signal to fall back+// to HTTP.+var errWSRPCUnavailable = errors.New("ws rpc: no active connection")++// errWSRPCUncertain is returned when a request's frame WAS sent but the+// connection dropped before a definitive response. The outcome is unknown (the+// server may have committed), so the caller must NOT fall back to another+// transport for the same work — that risks a double claim (MUL-4257).+var errWSRPCUncertain = errors.New("ws rpc: sent but outcome unknown (connection lost)")++// wsRPCResponseGrace is how much longer the daemon waits for an RPC response+// beyond the server-side execution budget it requested, so a claim that+// committed just before the server deadline still reports back before the+// daemon gives up (MUL-4257).+const wsRPCResponseGrace = 2 * time.Second++// errWSRPCWriteBufferFull is returned when the connection's write buffer is+// saturated; the caller falls back to HTTP rather than blocking the socket.+var errWSRPCWriteBufferFull = errors.New("ws rpc: write buffer full")++// wsRPCClient is the daemon-side half of the generic WS request/response+// transport (MUL-4257). It correlates responses to requests by request_id over+// the shared, multiplexed WS control connection so multiple RPCs can be in+// flight concurrently. Sending is delegated to an injected sendFrame func+// (which pushes onto the active connection's write channel); when no connection+// is attached, Call fails fast with errWSRPCUnavailable and the caller uses+// HTTP.+// wsOutbound is a frame queued for the WS writer. It is cancelable so an RPC+// caller that gives up (timeout/detach) before the frame has hit the socket can+// prevent it from being delivered later — otherwise a backpressured writer+// could deliver a stale tasks.claim after the daemon already HTTP-fell-back,+// double-claiming (MUL-4257, Sol-Boy review). sent/cancel race under mu so the+// decision is atomic: whoever wins determines whether the frame is delivered.+type wsOutbound struct {+ data []byte+ mu sync.Mutex+ sent bool+ canceled bool+}++// beginWrite is called by the writer immediately before WriteMessage. It+// returns false when the frame was already cancelled (skip it); otherwise it+// marks the frame sent so a concurrent cancel() can no longer un-send it.+func (o *wsOutbound) beginWrite() bool {+ o.mu.Lock()+ defer o.mu.Unlock()+ if o.canceled {+ return false+ }+ o.sent = true+ return true+}++// cancel is called by an RPC caller giving up. Returns true if the frame was+// still pending (now cancelled — the writer will skip it, so it is guaranteed+// NOT delivered); false if the writer already began sending it.+func (o *wsOutbound) cancel() bool {+ o.mu.Lock()+ defer o.mu.Unlock()+ if o.sent {+ return false+ }+ o.canceled = true+ return true+}++type wsRPCClient struct {+ mu sync.Mutex+ pending map[string]chan protocol.RPCResponsePayload+ sendFrame func([]byte) (*wsOutbound, error)+ // grace is added to a call's server-side timeout budget to get how long the+ // daemon waits for the response, so a claim that committed just before the+ // server deadline still reports back before the daemon gives up (MUL-4257).+ grace time.Duration+}++func newWSRPCClient(grace time.Duration) *wsRPCClient {+ return &wsRPCClient{+ pending: make(map[string]chan protocol.RPCResponsePayload),+ grace: grace,+ }+}++// attach binds a live connection's frame writer. Passing nil detaches (on+// disconnect), after which Call fails fast until the next attach. Any pending+// requests are failed so their callers fall back to HTTP immediately.+func (c *wsRPCClient) attach(sendFrame func([]byte) (*wsOutbound, error)) {+ c.mu.Lock()+ c.sendFrame = sendFrame+ if sendFrame == nil {+ for id, ch := range c.pending {+ close(ch)+ delete(c.pending, id)+ }+ }+ c.mu.Unlock()+}++// connected reports whether a live connection is attached.+func (c *wsRPCClient) connected() bool {+ if c == nil {+ return false+ }+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.sendFrame != nil+}++// Call issues an RPC and blocks until the response, the per-request timeout, or+// ctx cancellation. reqBody is marshaled into the request envelope; on a 2xx+// response respBody (if non-nil) is unmarshaled from the response body. It+// returns the response status (0 when the call never reached the server) so the+// caller can distinguish transport failure (→ HTTP fallback) from a server-side+// error.+func (c *wsRPCClient) Call(ctx context.Context, method string, serverTimeout time.Duration, reqBody, respBody any) (int, error) {+ if c == nil {+ return 0, errWSRPCUnavailable+ }+ var rawReq json.RawMessage+ if reqBody != nil {+ b, err := json.Marshal(reqBody)+ if err != nil {+ return 0, fmt.Errorf("ws rpc: marshal request: %w", err)+ }+ rawReq = b+ }+ id := uuid.NewString()+ frame, err := json.Marshal(protocol.Message{+ Type: protocol.EventDaemonRPCRequest,+ Payload: marshalRaw(protocol.RPCRequestPayload{+ RequestID: id,+ Method: method,+ Body: rawReq,+ TimeoutMs: serverTimeout.Milliseconds(),+ }),+ })+ if err != nil {+ return 0, fmt.Errorf("ws rpc: marshal frame: %w", err)+ }++ ch := make(chan protocol.RPCResponsePayload, 1)+ c.mu.Lock()+ if c.sendFrame == nil {+ c.mu.Unlock()+ return 0, errWSRPCUnavailable+ }+ send := c.sendFrame+ c.pending[id] = ch+ c.mu.Unlock()++ defer func() {+ c.mu.Lock()+ delete(c.pending, id)+ c.mu.Unlock()+ }()++ item, err := send(frame)+ if err != nil {+ return 0, fmt.Errorf("ws rpc: send: %w", err)+ }++ // giveUp resolves an abandoned request. If the frame is still queued we+ // cancel it so the writer never delivers it — a definitively-not-sent+ // outcome that is safe to HTTP-fall-back. If the writer already began+ // sending it, it may reach the server, so the outcome is uncertain and the+ // caller must NOT fall back (that would double-claim, MUL-4257).+ giveUp := func() error {+ if item.cancel() {+ return errWSRPCUnavailable+ }+ return errWSRPCUncertain+ }++ // Wait the server-side budget PLUS a grace margin: a claim that committed+ // just before the server deadline must still report back before the daemon+ // gives up and falls back to HTTP, or we would double-claim (MUL-4257).+ timeout := serverTimeout + c.grace+ if timeout <= 0 {+ timeout = 5 * time.Second+ }+ timer := time.NewTimer(timeout)+ defer timer.Stop()++ select {+ case resp, ok := <-ch:+ if !ok {+ // The connection detached. Whether the server saw this request+ // depends on whether the frame had already left the writer, so let+ // giveUp() decide (not-sent → safe fallback; sent → uncertain).+ return 0, giveUp()+ }+ if resp.Status >= 200 && resp.Status < 300 {+ if respBody != nil && len(resp.Body) > 0 {+ if err := json.Unmarshal(resp.Body, respBody); err != nil {+ return resp.Status, fmt.Errorf("ws rpc: decode response: %w", err)+ }+ }+ return resp.Status, nil+ }+ msg := resp.Error+ if msg == "" {+ msg = fmt.Sprintf("ws rpc status %d", resp.Status)+ }+ return resp.Status, errors.New(msg)+ case <-timer.C:+ // The budget elapsed. If the frame is still queued behind a+ // backpressured writer, cancel it so it is never delivered after we+ // fall back (giveUp → not-sent). If it already left the writer, the+ // outcome is uncertain and we must not fall back.+ if err := giveUp(); errors.Is(err, errWSRPCUncertain) {+ return 0, err+ }+ return 0, fmt.Errorf("ws rpc: timeout after %s: %w", timeout, errWSRPCUnavailable)+ case <-ctx.Done():+ item.cancel()+ return 0, ctx.Err()+ }+}++// deliver routes an inbound rpc_response frame to the waiting Call. The send+// happens under the mutex so it is serialized with attach(nil)'s close+delete:+// a channel present in pending is guaranteed not yet closed, so this never+// sends on a closed channel. Unknown request ids (already timed out / detached)+// are dropped.+func (c *wsRPCClient) deliver(resp protocol.RPCResponsePayload) {+ if c == nil {+ return+ }+ c.mu.Lock()+ defer c.mu.Unlock()+ ch, ok := c.pending[resp.RequestID]+ if !ok {+ return+ }+ select {+ case ch <- resp:+ default:+ }+}++// ClaimTasksWSFirst is the WS-first claim policy (MUL-4257): it issues the+// tasks.claim RPC over the WS control connection when one is attached, and+// falls back to the HTTP claim endpoint on any transport failure (no+// connection, write-buffer full, timeout) or server error. The request/response+// bodies are identical to the HTTP endpoint so both transports are+// interchangeable. Wired into the claim poller as part of the poller cutover.+func (d *Daemon) ClaimTasksWSFirst(ctx context.Context, daemonID string, runtimeIDs []string, maxTasks int) ([]*Task, error) {+ // Un-upgraded server without the batch route: a prior poll already learned+ // this (via a 404), so go straight to the legacy per-runtime claim and skip+ // the WS + batch attempts each cycle.+ if d.batchClaimUnsupported.Load() {+ return d.client.claimTasksLegacy(ctx, runtimeIDs, maxTasks)+ }+ if d.wsRPC.connected() {+ var resp struct {+ Tasks []*Task `json:"tasks"`+ }+ // batchClaimRequestTimeout is the server-side execution budget; the+ // daemon waits that plus the client's grace margin for the response.+ _, err := d.wsRPC.Call(ctx, "tasks.claim", batchClaimRequestTimeout, map[string]any{+ "daemon_id": daemonID,+ "runtime_ids": runtimeIDs,+ "max_tasks": maxTasks,+ }, &resp)+ if err == nil {+ return resp.Tasks, nil+ }+ if errors.Is(err, errWSRPCUncertain) {+ // The WS claim may have committed server-side; claiming the same+ // free slots again over HTTP would double-claim. Skip this cycle —+ // an orphaned server-side claim is recovered by stale reclaim and+ // the next poll picks up anything still queued.+ d.logger.Debug("ws claim outcome uncertain after disconnect; skipping fallback this cycle")+ return nil, nil+ }+ d.logger.Debug("ws claim failed; falling back to http", "error", err)+ }+ tasks, err := d.client.ClaimTasks(ctx, daemonID, runtimeIDs, maxTasks)+ if err == nil {+ return tasks, nil+ }+ // Server has no batch route (404): freeze the old API contract by falling+ // back to the legacy per-runtime claim loop, and remember it so we don't+ // re-probe every cycle.+ if isBatchClaimUnsupported(err) {+ d.batchClaimUnsupported.Store(true)+ d.logger.Info("batch claim route unsupported by server; using legacy per-runtime claim")+ return d.client.claimTasksLegacy(ctx, runtimeIDs, maxTasks)+ }+ return nil, err+}diff --git a/server/internal/daemon/wsrpc_test.go b/server/internal/daemon/wsrpc_test.gonew file mode 100644index 0000000000..8edf6a365f--- /dev/null+++ b/server/internal/daemon/wsrpc_test.go@@ -0,0 +1,246 @@+package daemon++import (+ "context"+ "encoding/json"+ "errors"+ "sync"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/pkg/protocol"+)++// TestWSRPCClient_CallRoundTrip: a request is framed and sent, and a matching+// response (by request_id) is decoded into respBody.+func TestWSRPCClient_CallRoundTrip(t *testing.T) {+ c := newWSRPCClient(time.Second)++ // Fake transport: capture the frame, and reply asynchronously with a 200.+ c.attach(func(frame []byte) (*wsOutbound, error) {+ var msg protocol.Message+ if err := json.Unmarshal(frame, &msg); err != nil {+ return nil, err+ }+ var req protocol.RPCRequestPayload+ if err := json.Unmarshal(msg.Payload, &req); err != nil {+ return nil, err+ }+ if req.Method != "tasks.claim" {+ t.Errorf("method = %q, want tasks.claim", req.Method)+ }+ go c.deliver(protocol.RPCResponsePayload{+ RequestID: req.RequestID,+ Status: 200,+ Body: json.RawMessage(`{"tasks":[{"id":"t1"}]}`),+ })+ return &wsOutbound{data: frame}, nil+ })++ var resp struct {+ Tasks []struct {+ ID string `json:"id"`+ } `json:"tasks"`+ }+ status, err := c.Call(context.Background(), "tasks.claim", 0, map[string]any{"max_tasks": 3}, &resp)+ if err != nil || status != 200 {+ t.Fatalf("Call: status=%d err=%v", status, err)+ }+ if len(resp.Tasks) != 1 || resp.Tasks[0].ID != "t1" {+ t.Fatalf("resp = %+v, want one task t1", resp)+ }+}++// TestWSRPCClient_Unavailable: with no connection attached, Call fails fast so+// the caller falls back to HTTP.+func TestWSRPCClient_Unavailable(t *testing.T) {+ c := newWSRPCClient(time.Second)+ if _, err := c.Call(context.Background(), "tasks.claim", 0, nil, nil); !errors.Is(err, errWSRPCUnavailable) {+ t.Fatalf("err = %v, want errWSRPCUnavailable", err)+ }+}++// TestWSRPCClient_Timeout: no response arrives within the per-request timeout.+func TestWSRPCClient_Timeout(t *testing.T) {+ c := newWSRPCClient(50 * time.Millisecond)+ c.attach(func(frame []byte) (*wsOutbound, error) { return &wsOutbound{data: frame}, nil }) // send succeeds, never replies+ status, err := c.Call(context.Background(), "tasks.claim", 0, nil, nil)+ if err == nil || status != 0 {+ t.Fatalf("status=%d err=%v, want timeout (status 0, err)", status, err)+ }+}++// TestWSRPCClient_ServerError: a non-2xx response surfaces as an error with the+// server-provided message, and a non-zero status so the caller can classify.+func TestWSRPCClient_ServerError(t *testing.T) {+ c := newWSRPCClient(time.Second)+ c.attach(func(frame []byte) (*wsOutbound, error) {+ var msg protocol.Message+ json.Unmarshal(frame, &msg)+ var req protocol.RPCRequestPayload+ json.Unmarshal(msg.Payload, &req)+ go c.deliver(protocol.RPCResponsePayload{RequestID: req.RequestID, Status: 400, Error: "bad daemon_id"})+ return &wsOutbound{data: frame}, nil+ })+ status, err := c.Call(context.Background(), "tasks.claim", 0, nil, nil)+ if status != 400 || err == nil {+ t.Fatalf("status=%d err=%v, want 400 + error", status, err)+ }+}++// TestWSRPCClient_DetachFailsPending: detaching (disconnect) unblocks an+// in-flight Call whose frame was already sent with errWSRPCUncertain — the+// caller must not blindly re-claim over HTTP (MUL-4257).+func TestWSRPCClient_DetachFailsPending(t *testing.T) {+ c := newWSRPCClient(2 * time.Second)+ var mu sync.Mutex+ var item *wsOutbound+ c.attach(func(frame []byte) (*wsOutbound, error) {+ mu.Lock()+ defer mu.Unlock()+ item = &wsOutbound{data: frame}+ return item, nil+ })+ done := make(chan error, 1)+ go func() {+ _, err := c.Call(context.Background(), "tasks.claim", 0, nil, nil)+ done <- err+ }()+ time.Sleep(30 * time.Millisecond)+ // Simulate the writer having put the frame on the wire before the+ // disconnect, so the server may have processed it → outcome is uncertain.+ mu.Lock()+ item.beginWrite()+ mu.Unlock()+ c.attach(nil) // detach+ select {+ case err := <-done:+ if !errors.Is(err, errWSRPCUncertain) {+ t.Fatalf("err = %v, want errWSRPCUncertain", err)+ }+ case <-time.After(time.Second):+ t.Fatal("Call did not return after detach")+ }+}++// TestWSRPCClient_DeliverDetachRaceNoPanic hammers deliver racing with+// attach(nil) (disconnect). Before the fix, deliver could send on a channel+// attach(nil) had just closed → "send on closed channel" panic. Run under+// -race; passing means the two are serialized under the mutex.+func TestWSRPCClient_DeliverDetachRaceNoPanic(t *testing.T) {+ for iter := 0; iter < 300; iter++ {+ c := newWSRPCClient(time.Second)+ c.attach(func(frame []byte) (*wsOutbound, error) { return &wsOutbound{data: frame}, nil })+ id := "req"+ ch := make(chan protocol.RPCResponsePayload, 1)+ c.mu.Lock()+ c.pending[id] = ch+ c.mu.Unlock()++ var wg sync.WaitGroup+ wg.Add(2)+ go func() {+ defer wg.Done()+ c.deliver(protocol.RPCResponsePayload{RequestID: id, Status: 200})+ }()+ go func() {+ defer wg.Done()+ c.attach(nil) // closes + deletes pending under the same mutex+ }()+ wg.Wait()+ }+}++// TestWSOutbound_CancelBeforeWriteDropsFrame: a caller that gives up before the+// writer sends the frame cancels it, and the writer then skips it (never+// delivered) — the core guarantee that a delayed frame cannot double-claim+// after an HTTP fallback (MUL-4257).+func TestWSOutbound_CancelBeforeWriteDropsFrame(t *testing.T) {+ o := &wsOutbound{data: []byte("x")}+ if !o.cancel() {+ t.Fatal("cancel of a pending frame should succeed")+ }+ if o.beginWrite() {+ t.Fatal("writer must skip a cancelled frame")+ }+}++// TestWSOutbound_WriteBeforeCancelDelivers: once the writer has begun sending a+// frame it can no longer be cancelled, so the caller must treat the outcome as+// uncertain rather than falling back.+func TestWSOutbound_WriteBeforeCancelDelivers(t *testing.T) {+ o := &wsOutbound{data: []byte("x")}+ if !o.beginWrite() {+ t.Fatal("writer should send a pending frame")+ }+ if o.cancel() {+ t.Fatal("cancel must fail once the frame has been sent")+ }+}++// TestWSRPCClient_TimeoutCancelsUnsentFrame reproduces the Sol-Boy backpressure+// blocker: the frame is enqueued but the writer is stalled, so the client times+// out before it is sent. The timeout must cancel the queued frame (so the+// stalled writer later DROPS it) and report a not-sent outcome that is safe to+// HTTP-fall-back — never delivering the stale claim on top of the fallback.+func TestWSRPCClient_TimeoutCancelsUnsentFrame(t *testing.T) {+ c := newWSRPCClient(20 * time.Millisecond)+ var mu sync.Mutex+ var item *wsOutbound+ c.attach(func(frame []byte) (*wsOutbound, error) {+ mu.Lock()+ defer mu.Unlock()+ item = &wsOutbound{data: frame}+ return item, nil // enqueued; no writer ever drains it+ })+ status, err := c.Call(context.Background(), "tasks.claim", 30*time.Millisecond, nil, nil)+ if status != 0 {+ t.Fatalf("status = %d, want 0", status)+ }+ if !errors.Is(err, errWSRPCUnavailable) {+ t.Fatalf("err = %v, want errWSRPCUnavailable (not-sent → safe fallback)", err)+ }+ if errors.Is(err, errWSRPCUncertain) {+ t.Fatal("unsent frame must not be reported uncertain")+ }+ // The stalled writer now wakes up: the frame must have been cancelled so it+ // is dropped, not delivered after the fallback.+ mu.Lock()+ sent := item.beginWrite()+ mu.Unlock()+ if sent {+ t.Fatal("timed-out frame must be dropped by the writer to avoid double-claim")+ }+}++// TestWSRPCClient_TimeoutUncertainWhenAlreadySent: if the writer already put the+// frame on the wire, a subsequent client timeout is uncertain (the server may+// have it) and must NOT fall back.+func TestWSRPCClient_TimeoutUncertainWhenAlreadySent(t *testing.T) {+ c := newWSRPCClient(30 * time.Millisecond)+ var mu sync.Mutex+ var item *wsOutbound+ c.attach(func(frame []byte) (*wsOutbound, error) {+ mu.Lock()+ defer mu.Unlock()+ item = &wsOutbound{data: frame}+ return item, nil+ })+ done := make(chan error, 1)+ go func() {+ _, err := c.Call(context.Background(), "tasks.claim", 40*time.Millisecond, nil, nil)+ done <- err+ }()+ time.Sleep(10 * time.Millisecond)+ mu.Lock()+ item.beginWrite() // writer sends it before the timeout fires+ mu.Unlock()+ select {+ case err := <-done:+ if !errors.Is(err, errWSRPCUncertain) {+ t.Fatalf("err = %v, want errWSRPCUncertain", err)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("Call did not return")+ }+}diff --git a/server/internal/daemonws/hub.go b/server/internal/daemonws/hub.goindex e097070879..aed9ae1567 100644--- a/server/internal/daemonws/hub.go+++ b/server/internal/daemonws/hub.go@@ -30,6 +30,9 @@ type ClientIdentity struct {WorkspaceIDs []stringRuntimeIDs []stringClientVersion string+ // Capabilities is the raw X-Client-Capabilities header captured at connect,+ // so RPC handlers can honor the same capability gating as the HTTP path.+ Capabilities string}// AuthorizedWorkspaceIDs returns the connection's workspace scope in stable@@ -89,9 +92,41 @@ type client struct {identity ClientIdentityruntimes map[string]struct{}+ // ctx is cancelled when the connection tears down, so async RPC handlers+ // stop instead of running against a dead socket. cancel is invoked from+ // readPump's defer.+ ctx context.Context+ cancel context.CancelFunc++ // sendMu guards sendClosed so a late async send (e.g. an RPC response+ // goroutine) can never write to the closed send channel. teardown flips+ // sendClosed under sendMu before closing send.+ sendMu sync.Mutex+ sendClosed bool+dedupMu sync.MutexseenIDs map[string]struct{}seenList []string++ // rpcSem bounds concurrent RPC handlers for this connection.+ rpcSem chan struct{}+}++// trySend delivers frame to the write pump without blocking and without ever+// writing to a closed channel (safe against concurrent teardown). Returns false+// when the buffer is full or the connection is closing.+func (c *client) trySend(frame []byte) bool {+ c.sendMu.Lock()+ defer c.sendMu.Unlock()+ if c.sendClosed {+ return false+ }+ select {+ case c.send <- frame:+ return true+ default:+ return false+ }}const eventDedupCapacity = 128@@ -126,6 +161,18 @@ func (c *client) markSeen(eventID string) bool {// the ack and is logged at debug level.type HeartbeatHandler func(ctx context.Context, identity ClientIdentity, runtimeID string, supportsBatchImport bool) (*protocol.DaemonHeartbeatAckPayload, error)+// RPCHandler processes a generic daemon:rpc_request (MUL-4257). It dispatches+// on method (e.g. "tasks.claim"), scoping work to identity (DaemonID ++// authenticated RuntimeIDs), and returns an HTTP-style status plus a response+// body OR an error. A returned error is surfaced to the daemon as a non-2xx+// RPC response so it can fall back to HTTP. The handler runs in its own+// goroutine, so it must not assume it owns the read pump.+type RPCHandler func(ctx context.Context, identity ClientIdentity, method string, body json.RawMessage) (status int, respBody json.RawMessage, err error)++// maxInFlightRPCPerClient bounds concurrent RPC handlers per connection so a+// single daemon cannot fan out unbounded goroutines / DB work over one socket.+const maxInFlightRPCPerClient = 8+// MessageKindRecorder is the optional metric hook called once per inbound// daemon WebSocket frame. kind is the protocol message type with the// "daemon:" prefix stripped (e.g. "heartbeat") or the literal "unknown" for@@ -147,6 +194,9 @@ type Hub struct {hbMu sync.RWMutexonHeartbeat HeartbeatHandler+ rpcMu sync.RWMutex+ onRPC RPCHandler+kindMu sync.RWMutexkindRecorder MessageKindRecorder}@@ -187,6 +237,24 @@ func (h *Hub) heartbeatHandler() HeartbeatHandler {return h.onHeartbeat}+// SetRPCHandler installs the callback used for daemon:rpc_request frames+// (MUL-4257). Like SetHeartbeatHandler it is wired after handler construction.+// A nil handler disables WS RPC — daemons fall back to the HTTP claim endpoint.+func (h *Hub) SetRPCHandler(fn RPCHandler) {+ if h == nil {+ return+ }+ h.rpcMu.Lock()+ h.onRPC = fn+ h.rpcMu.Unlock()+}++func (h *Hub) rpcHandler() RPCHandler {+ h.rpcMu.RLock()+ defer h.rpcMu.RUnlock()+ return h.onRPC+}+// SetMessageKindRecorder installs an optional callback fired exactly once per// inbound daemon WebSocket frame. Used by the metrics layer to count traffic// by handler kind without hard-coupling the hub to any specific collector.@@ -238,7 +306,9 @@ func (h *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request, identity Csend: make(chan []byte, 16),identity: identity,runtimes: runtimes,+ rpcSem: make(chan struct{}, maxInFlightRPCPerClient),}+ c.ctx, c.cancel = context.WithCancel(context.Background())h.register(c)go c.writePump()@@ -483,7 +553,10 @@ func (h *Hub) unregister(c *client) {}}}+ c.sendMu.Lock()+ c.sendClosed = trueclose(c.send)+ c.sendMu.Unlock()total := len(h.clients)h.mu.Unlock()@@ -501,11 +574,16 @@ func (h *Hub) unregister(c *client) {func (c *client) readPump() {defer func() {+ // Cancel first so async RPC handlers stop before we close the send+ // channel, then unregister (which marks send closed).+ c.cancel()c.hub.unregister(c)c.conn.Close()}()- c.conn.SetReadLimit(4096)+ // Read limit sized for daemon:rpc_request frames carrying a machine's full+ // runtime_id set (MUL-4257), well above the tiny heartbeat/wakeup frames.+ c.conn.SetReadLimit(64 * 1024)c.conn.SetReadDeadline(time.Now().Add(pongWait))c.conn.SetPongHandler(func(string) error {c.conn.SetReadDeadline(time.Now().Add(pongWait))@@ -543,12 +621,90 @@ func (c *client) handleFrame(raw []byte) {switch msg.Type {case protocol.EventDaemonHeartbeat:c.handleHeartbeatFrame(msg.Payload)+ case protocol.EventDaemonRPCRequest:+ c.handleRPCFrame(msg.Payload)default:// Unknown app messages are intentionally ignored for forward// compatibility with future daemon → server message types.}}+// handleRPCFrame processes a generic daemon:rpc_request (MUL-4257): it runs the+// registered RPC handler in its own goroutine (so a DB-bound claim does not+// stall the read pump or the next heartbeat) and writes back a+// daemon:rpc_response echoing the request id. A missing handler or a full+// in-flight slot yields a non-2xx response so the daemon falls back to HTTP.+func (c *client) handleRPCFrame(raw json.RawMessage) {+ var req protocol.RPCRequestPayload+ if err := json.Unmarshal(raw, &req); err != nil {+ slog.Debug("daemon websocket rpc invalid payload", "error", err, "daemon_id", c.identity.DaemonID)+ return+ }+ if req.RequestID == "" {+ slog.Debug("daemon websocket rpc missing request_id", "daemon_id", c.identity.DaemonID)+ return+ }+ handler := c.hub.rpcHandler()+ if handler == nil {+ c.sendRPCResponse(req.RequestID, http.StatusServiceUnavailable, nil, "rpc handler unavailable")+ return+ }+ // Bound concurrent handlers; if saturated, tell the daemon to fall back+ // rather than queueing unbounded work on one socket.+ select {+ case c.rpcSem <- struct{}{}:+ default:+ c.sendRPCResponse(req.RequestID, http.StatusTooManyRequests, nil, "too many in-flight rpc requests")+ return+ }+ go func() {+ defer func() { <-c.rpcSem }()+ // Bound server-side execution by the caller's requested budget (in+ // addition to the connection ctx), so a slow RPC is cancelled — and its+ // work rolled back — rather than committing after the daemon has already+ // timed out and fallen back to HTTP (MUL-4257). The daemon waits a grace+ // period beyond this budget, so a claim that DID commit before the+ // deadline still reports back in time.+ hctx := c.ctx+ if req.TimeoutMs > 0 {+ var cancel context.CancelFunc+ hctx, cancel = context.WithTimeout(c.ctx, time.Duration(req.TimeoutMs)*time.Millisecond)+ defer cancel()+ }+ status, body, err := handler(hctx, c.identity, req.Method, req.Body)+ if err != nil {+ if status < 400 {+ status = http.StatusInternalServerError+ }+ c.sendRPCResponse(req.RequestID, status, nil, err.Error())+ return+ }+ c.sendRPCResponse(req.RequestID, status, body, "")+ }()+}++func (c *client) sendRPCResponse(requestID string, status int, body json.RawMessage, errMsg string) {+ frame, err := json.Marshal(protocol.Message{+ Type: protocol.EventDaemonRPCResponse,+ Payload: mustMarshalRaw(protocol.RPCResponsePayload{+ RequestID: requestID,+ Status: status,+ Body: body,+ Error: errMsg,+ }),+ })+ if err != nil {+ slog.Debug("daemon websocket rpc response marshal failed", "error", err)+ return+ }+ if !c.trySend(frame) {+ // Send buffer full or connection closing — drop the response; the+ // daemon's per-request timeout fires and it falls back to HTTP.+ slog.Debug("daemon websocket rpc response dropped",+ "daemon_id", c.identity.DaemonID, "request_id", requestID)+ }+}+// handleHeartbeatFrame processes an inbound daemon:heartbeat from the daemon,// invokes the hub's handler, and writes back a daemon:heartbeat_ack.func (c *client) handleHeartbeatFrame(raw json.RawMessage) {@@ -603,12 +759,9 @@ func (c *client) handleHeartbeatFrame(raw json.RawMessage) {slog.Debug("daemon websocket heartbeat ack marshal failed", "error", err)return}- select {- case c.send <- frame:- default:- // Send buffer is full — slow client. Don't block the read pump; the- // next writePump tick or notifyFrame eviction will clean up.- slog.Debug("daemon websocket heartbeat ack dropped: send buffer full",+ if !c.trySend(frame) {+ // Send buffer full or connection closing — drop; HTTP heartbeat resumes.+ slog.Debug("daemon websocket heartbeat ack dropped","daemon_id", c.identity.DaemonID,"runtime_id", payload.RuntimeID)}diff --git a/server/internal/daemonws/rpc_dispatch_test.go b/server/internal/daemonws/rpc_dispatch_test.gonew file mode 100644index 0000000000..c077d77d01--- /dev/null+++ b/server/internal/daemonws/rpc_dispatch_test.go@@ -0,0 +1,191 @@+package daemonws++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// dialRPCTestConn spins up a hub-backed WS server and returns a connected+// client conn plus the hub.+func dialRPCTestConn(t *testing.T, hub *Hub, identity ClientIdentity) *websocket.Conn {+ t.Helper()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ hub.HandleWebSocket(w, r, identity)+ }))+ t.Cleanup(server.Close)+ wsURL := "ws" + strings.TrimPrefix(server.URL, "http")+ conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)+ if err != nil {+ t.Fatalf("Dial: %v", err)+ }+ t.Cleanup(func() { conn.Close() })+ return conn+}++func sendRPCRequest(t *testing.T, conn *websocket.Conn, req protocol.RPCRequestPayload) protocol.RPCResponsePayload {+ t.Helper()+ frame, err := json.Marshal(protocol.Message{+ Type: protocol.EventDaemonRPCRequest,+ Payload: mustMarshalRaw(req),+ })+ if err != nil {+ t.Fatalf("marshal request: %v", err)+ }+ if err := conn.WriteMessage(websocket.TextMessage, frame); err != nil {+ t.Fatalf("write: %v", err)+ }+ if err := conn.SetReadDeadline(time.Now().Add(2 * time.Second)); err != nil {+ t.Fatalf("SetReadDeadline: %v", err)+ }+ _, raw, err := conn.ReadMessage()+ if err != nil {+ t.Fatalf("read: %v", err)+ }+ var msg protocol.Message+ if err := json.Unmarshal(raw, &msg); err != nil {+ t.Fatalf("unmarshal msg: %v", err)+ }+ if msg.Type != protocol.EventDaemonRPCResponse {+ t.Fatalf("type = %q, want %q", msg.Type, protocol.EventDaemonRPCResponse)+ }+ var resp protocol.RPCResponsePayload+ if err := json.Unmarshal(msg.Payload, &resp); err != nil {+ t.Fatalf("unmarshal resp: %v", err)+ }+ return resp+}++// TestRPCDispatch_RoundTrip pins the generic WS request/response contract+// (MUL-4257): a daemon:rpc_request is routed to the registered handler with the+// connection's identity, and the daemon:rpc_response echoes the request id and+// carries the handler's body.+func TestRPCDispatch_RoundTrip(t *testing.T) {+ hub := NewHub()+ var gotMethod, gotDaemonID string+ hub.SetRPCHandler(func(ctx context.Context, identity ClientIdentity, method string, body json.RawMessage) (int, json.RawMessage, error) {+ gotMethod = method+ gotDaemonID = identity.DaemonID+ return http.StatusOK, json.RawMessage(`{"ok":true}`), nil+ })+ conn := dialRPCTestConn(t, hub, ClientIdentity{DaemonID: "daemon-1", RuntimeIDs: []string{"rt-1"}})++ resp := sendRPCRequest(t, conn, protocol.RPCRequestPayload{+ RequestID: "req-1",+ Method: "tasks.claim",+ Body: json.RawMessage(`{"max_tasks":3}`),+ })+ if resp.RequestID != "req-1" || resp.Status != http.StatusOK || string(resp.Body) != `{"ok":true}` {+ t.Fatalf("resp = %+v, want req-1/200/{ok:true}", resp)+ }+ if gotMethod != "tasks.claim" || gotDaemonID != "daemon-1" {+ t.Fatalf("handler saw method=%q daemon=%q, want tasks.claim/daemon-1", gotMethod, gotDaemonID)+ }+}++// TestRPCDispatch_HandlerError maps a handler error to a non-2xx response so+// the daemon can fall back to HTTP.+func TestRPCDispatch_HandlerError(t *testing.T) {+ hub := NewHub()+ hub.SetRPCHandler(func(ctx context.Context, identity ClientIdentity, method string, body json.RawMessage) (int, json.RawMessage, error) {+ return 0, nil, context.DeadlineExceeded+ })+ conn := dialRPCTestConn(t, hub, ClientIdentity{DaemonID: "daemon-1", RuntimeIDs: []string{"rt-1"}})+ resp := sendRPCRequest(t, conn, protocol.RPCRequestPayload{RequestID: "req-2", Method: "tasks.claim"})+ if resp.RequestID != "req-2" || resp.Status < 400 || resp.Error == "" {+ t.Fatalf("resp = %+v, want req-2 with 5xx + error", resp)+ }+}++// TestRPCDispatch_NoHandler returns 503 when no RPC handler is registered so+// the daemon falls back to HTTP.+func TestRPCDispatch_NoHandler(t *testing.T) {+ hub := NewHub()+ conn := dialRPCTestConn(t, hub, ClientIdentity{DaemonID: "daemon-1", RuntimeIDs: []string{"rt-1"}})+ resp := sendRPCRequest(t, conn, protocol.RPCRequestPayload{RequestID: "req-3", Method: "tasks.claim"})+ if resp.RequestID != "req-3" || resp.Status != http.StatusServiceUnavailable {+ t.Fatalf("resp = %+v, want req-3 with 503", resp)+ }+}++// TestRPCDispatch_DisconnectDuringHandlerNoPanic pins the server-side fix: an+// RPC handler that finishes AFTER the connection tears down must not send on+// the closed send channel. The handler blocks until the client has+// disconnected, then returns and attempts to write its response. Run under+// -race; passing means the guarded send + connection-ctx teardown are safe.+func TestRPCDispatch_DisconnectDuringHandlerNoPanic(t *testing.T) {+ hub := NewHub()+ release := make(chan struct{})+ entered := make(chan struct{}, 1)+ hub.SetRPCHandler(func(ctx context.Context, identity ClientIdentity, method string, body json.RawMessage) (int, json.RawMessage, error) {+ select {+ case entered <- struct{}{}:+ default:+ }+ <-release // return only after the client disconnects+ return http.StatusOK, json.RawMessage(`{"ok":true}`), nil+ })+ conn := dialRPCTestConn(t, hub, ClientIdentity{DaemonID: "daemon-1", RuntimeIDs: []string{"rt-1"}})++ frame, _ := json.Marshal(protocol.Message{+ Type: protocol.EventDaemonRPCRequest,+ Payload: mustMarshalRaw(protocol.RPCRequestPayload{RequestID: "req-1", Method: "tasks.claim"}),+ })+ if err := conn.WriteMessage(websocket.TextMessage, frame); err != nil {+ t.Fatalf("write: %v", err)+ }+ select {+ case <-entered:+ case <-time.After(2 * time.Second):+ t.Fatal("handler never started")+ }++ conn.Close() // client disconnect → server readPump exits → cancel + close send+ time.Sleep(50 * time.Millisecond)+ close(release) // handler returns and tries to send its response+ time.Sleep(100 * time.Millisecond)+ // No panic == pass.+}++// TestRPCDispatch_ServerTimeoutCancelsHandler pins the MUL-4257 review fix: the+// RPC request's TimeoutMs bounds server-side execution, so a slow handler is+// cancelled (its work rolled back) at the deadline rather than running to+// completion after the daemon has already timed out and fallen back to HTTP.+func TestRPCDispatch_ServerTimeoutCancelsHandler(t *testing.T) {+ hub := NewHub()+ cancelled := make(chan struct{}, 1)+ hub.SetRPCHandler(func(ctx context.Context, identity ClientIdentity, method string, body json.RawMessage) (int, json.RawMessage, error) {+ select {+ case <-ctx.Done():+ select {+ case cancelled <- struct{}{}:+ default:+ }+ return 0, nil, ctx.Err()+ case <-time.After(5 * time.Second):+ return http.StatusOK, json.RawMessage(`{}`), nil+ }+ })+ conn := dialRPCTestConn(t, hub, ClientIdentity{DaemonID: "daemon-1", RuntimeIDs: []string{"rt-1"}})++ resp := sendRPCRequest(t, conn, protocol.RPCRequestPayload{+ RequestID: "req-timeout",+ Method: "tasks.claim",+ TimeoutMs: 100,+ })+ if resp.RequestID != "req-timeout" || resp.Status < 400 || resp.Error == "" {+ t.Fatalf("resp = %+v, want an error response from the cancelled handler", resp)+ }+ select {+ case <-cancelled:+ case <-time.After(2 * time.Second):+ t.Fatal("handler context was not cancelled at the server-side TimeoutMs deadline")+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 293ef10d5f..dc675fc159 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1321,117 +1321,276 @@ func parseRuntimeConnectedAppsForClaim(raw []byte, taskID pgtype.UUID) []runtimereturn apps}-// ClaimTaskByRuntime atomically claims the next queued task for a runtime.-// The response includes the agent's name and skills, fetched fresh from the DB.-func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {- runtimeID := chi.URLParam(r, "runtimeId")+// repairStaleCommentPlanIfNeeded handles the edit/delete race where a claimed+// task's trigger_comment_id was cleared but coalesced_comment_ids survive: such+// a task must never be dispatched as a generic assignment — its user-scoped MCP+// overlay still belongs to the deleted author, and the prompt would read issue+// history exposing that stale user's capabilities. When it applies, the task is+// cancelled and its surviving comments are replayed through normal routing+// (which recomputes originator + connected-app context).+//+// Returns handled=true when the task must NOT be dispatched — either a clean+// repair (failure==nil) or a hard failure (failure!=nil, carrying the+// status/message/outcome the per-runtime endpoint renders). handled=false means+// proceed with a normal claim. Shared by the per-runtime and batch claim+// handlers so the batch path can't silently drop surviving comments (MUL-4257).+func (h *Handler) repairStaleCommentPlanIfNeeded(ctx context.Context, task *db.AgentTaskQueue, runtimeWorkspaceID string) (handled bool, failure *claimBuildFailure) {+ if task.TriggerCommentID.Valid || len(task.CoalescedCommentIds) == 0 {+ return false, nil+ }+ if !task.IssueID.Valid {+ return true, &claimBuildFailure{outcome: "error_stale_comment_plan", status: http.StatusInternalServerError, message: "comment task has no issue"}+ }+ issue, loadErr := h.Queries.GetIssue(ctx, task.IssueID)+ if loadErr != nil {+ return true, &claimBuildFailure{outcome: "error_stale_comment_plan", status: http.StatusInternalServerError, message: "failed to repair stale comment task"}+ }+ if uuidToString(issue.WorkspaceID) != runtimeWorkspaceID {+ if _, cancelErr := h.TaskService.CancelTask(ctx, task.ID); cancelErr != nil {+ slog.Error("task claim: cancel stale cross-workspace task failed",+ "task_id", uuidToString(task.ID), "error", cancelErr)+ }+ return true, &claimBuildFailure{outcome: "error_workspace", status: http.StatusInternalServerError, message: "task workspace isolation check failed"}+ }+ cancelled, cancelErr := h.TaskService.CancelTask(ctx, task.ID)+ if cancelErr != nil {+ return true, &claimBuildFailure{outcome: "error_stale_comment_plan", status: http.StatusInternalServerError, message: "failed to repair stale comment task"}+ }+ h.retriggerCancelledTaskSurvivors(ctx, issue, []db.AgentTaskQueue{*cancelled}, pgtype.UUID{})+ return true, nil+}++// claimBatchMaxTasksCap bounds how many tasks a single machine-level batch+// claim may return, so one request can neither build an unbounded payload nor+// hold the DB for an unbounded number of per-agent claim transactions. The+// daemon never asks for more than its free execution-slot count anyway.+const claimBatchMaxTasksCap = 32++// ClaimTasksByRuntime is the machine-level (MUL-4257) batch claim endpoint. A+// daemon posts every runtime_id it hosts plus its free execution-slot count and+// receives up to max_tasks already-claimed tasks in ONE round trip — each+// carrying its runtime_id so the daemon routes it to the matching runtime+// locally. This collapses the per-runtime idle-poll fan-out (one HTTP request+// plus one promote/reclaim/list cycle per runtime) into a single request backed+// by = ANY merged queries.+//+// Each returned task goes through the same FinalizeTaskClaim as the per-runtime+// endpoint, so the task-scoped token AND the comment-delivery receipt+// (delivered_comment_ids) are persisted atomically; a finalization failure+// requeues that exact claim and omits it from the batch. Unknown/unauthorized+// runtime_ids are skipped silently (a daemon may send a just-deleted runtime;+// it self-heals via the heartbeat path).+func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {start := time.Now()+ var req struct {+ DaemonID string `json:"daemon_id"`+ RuntimeIDs []string `json:"runtime_ids"`+ MaxTasks int `json:"max_tasks"`+ }+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }- var (- outcome = "unauth"- authMs, claimMs, buildMs int64- payloadBytes int- agentSkillCount int- builtinSkillCount int- skillPayloadBytes int- buildStart time.Time- )- defer func() {- // Emit at function exit so error / unauth paths also carry timing.- // build_ms is computed from buildStart only when we entered the- // response-build phase (otherwise stays 0).- if !buildStart.IsZero() {- buildMs = time.Since(buildStart).Milliseconds()- }- logClaimEndpointSlow(runtimeID, outcome, start, authMs, claimMs, buildMs, payloadBytes, agentSkillCount, builtinSkillCount, skillPayloadBytes)- }()+ // Machine-level ownership (MUL-4257 review): the batch claim is scoped to a+ // single daemon. daemon_id is required so the server can reject any+ // runtime_id that belongs to a different machine (guards against a stale /+ // crossed runtime set claiming another daemon's tasks — which would land+ // local_directory / machine-local work on the wrong host). For an mdt_+ // token the body daemon_id must equal the token's daemon_id, so a+ // workspace-scoped token can't spoof a peer.+ if req.DaemonID == "" {+ writeError(w, http.StatusBadRequest, "daemon_id is required")+ return+ }+ if ctxDaemonID := middleware.DaemonIDFromContext(r.Context()); ctxDaemonID != "" && ctxDaemonID != req.DaemonID {+ writeError(w, http.StatusForbidden, "daemon_id does not match token")+ return+ }- // Verify the caller owns this runtime's workspace. The runtime's- // workspace_id is the authoritative value a claimed task must match- // below — a task whose resolved workspace doesn't equal this runtime's- // workspace is rejected even if it was enqueued against this- // runtime_id (defense-in-depth against upstream routing bugs).- runtime, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID)- if !ok {+ // max_tasks semantics (MUL-4257 review): a negative count is malformed; zero+ // is a valid "no free slots" poll that must claim nothing — never coerce to+ // 1, which would dispatch a task the daemon cannot run and strand it until+ // stale reclaim. Positive counts are capped so one request can't build an+ // unbounded payload.+ if req.MaxTasks < 0 {+ writeError(w, http.StatusBadRequest, "max_tasks must not be negative")return}- runtimeWorkspaceID := uuidToString(runtime.WorkspaceID)- supportsCoalescedComments := requestHasDaemonCapability(r, protocol.DaemonCapabilityCoalescedCommentsV1)- authMs = time.Since(start).Milliseconds()+ if req.MaxTasks == 0 {+ writeMeasuredJSON(w, http.StatusOK, map[string]any{"tasks": []AgentTaskResponse{}})+ return+ }+ maxTasks := req.MaxTasks+ if maxTasks > claimBatchMaxTasksCap {+ maxTasks = claimBatchMaxTasksCap+ }- claimStart := time.Now()- task, err := h.TaskService.ClaimTaskForRuntime(r.Context(), parseUUID(runtimeID))- claimMs = time.Since(claimStart).Milliseconds()+ // Parse + de-dup requested ids with the NON-panicking parser (MUL-4257+ // review): the handler-local parseUUID panics on malformed input, which+ // would turn a single bad id into a 500. Invalid ids are skipped, matching+ // this endpoint's "unknown id skipped" semantics. Key by the canonical uuid+ // string so the post-claim lookup by task.RuntimeID always matches.+ idByKey := make(map[string]pgtype.UUID, len(req.RuntimeIDs))+ for _, rid := range req.RuntimeIDs {+ ruid, err := util.ParseUUID(rid)+ if err != nil {+ continue+ }+ idByKey[util.UUIDToString(ruid)] = ruid+ }+ if len(idByKey) == 0 {+ writeMeasuredJSON(w, http.StatusOK, map[string]any{"tasks": []AgentTaskResponse{}})+ return+ }+ ids := make([]pgtype.UUID, 0, len(idByKey))+ for _, id := range idByKey {+ ids = append(ids, id)+ }++ // Resolve all requested runtimes in one query (instead of a point lookup+ // per runtime), then authorize each; skip (don't fail) unknown/unauthorized+ // ids so a single stale runtime can't sink the whole batch.+ runtimes, err := h.Queries.GetAgentRuntimes(r.Context(), ids)if err != nil {- outcome = "error_claim"- writeError(w, http.StatusInternalServerError, "failed to claim task: "+err.Error())+ writeError(w, http.StatusInternalServerError, "failed to load runtimes")+ return+ }+ runtimeByID := make(map[string]db.AgentRuntime, len(runtimes))+ authorized := make([]pgtype.UUID, 0, len(runtimes))+ for _, rt := range runtimes {+ if !h.verifyDaemonWorkspaceAccess(r, uuidToString(rt.WorkspaceID)) {+ continue+ }+ // Group-ownership check (mirrors the WS path, daemon_ws.go): a runtime+ // bound to a different daemon must not be claimed by this one. Runtimes+ // with a NULL daemon_id (e.g. cloud runtimes) are not machine-pinned, so+ // they stay claimable — same tolerance as the WS handler.+ if rt.DaemonID.Valid && rt.DaemonID.String != req.DaemonID {+ continue+ }+ runtimeByID[uuidToString(rt.ID)] = rt+ authorized = append(authorized, rt.ID)+ }+ if len(authorized) == 0 {+ writeMeasuredJSON(w, http.StatusOK, map[string]any{"tasks": []AgentTaskResponse{}})return}- if task == nil {- slog.Debug("no task to claim", "runtime_id", runtimeID)- payloadBytes, _ = writeMeasuredJSON(w, http.StatusOK, map[string]any{"task": nil})- outcome = "no_task"+ claimed, err := h.TaskService.ClaimTasksForRuntimes(r.Context(), authorized, maxTasks)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to claim tasks: "+err.Error())return}- if !task.TriggerCommentID.Valid && len(task.CoalescedCommentIds) > 0 {- // A legacy edit/delete race can leave a plan whose trigger FK was- // cleared while its user-scoped MCP overlay still belongs to the deleted- // author. Never dispatch it as a generic assignment: that prompt reads- // issue history and would still expose the stale user's capabilities.- // Cancel the stale row and replay every survivor through normal routing,- // which recomputes originator and connected-app context.- if !task.IssueID.Valid {- outcome = "error_stale_comment_plan"- writeError(w, http.StatusInternalServerError, "comment task has no issue")- return++ out := make([]AgentTaskResponse, 0, len(claimed))+ for i := range claimed {+ task := claimed[i]+ rt, ok := runtimeByID[uuidToString(task.RuntimeID)]+ if !ok {+ // Service guards claims to the authorized set; a miss here would be+ // a stray cross-daemon claim. Leave it for the owning daemon's+ // reclaim path rather than shipping it to the wrong machine.+ continue}- issue, loadErr := h.Queries.GetIssue(r.Context(), task.IssueID)- if loadErr != nil {- outcome = "error_stale_comment_plan"- writeError(w, http.StatusInternalServerError, "failed to repair stale comment task")- return+ rtWorkspaceID := uuidToString(rt.WorkspaceID)+ // Stale comment-plan repair must run for the batch path too: otherwise a+ // task whose trigger was deleted (only coalesced survive) would be+ // finalized+dispatched with no comment input, silently dropping the+ // surviving user comment. On repair (or hard failure) the task is+ // cancelled / left for reclaim and omitted from the batch.+ if handled, _ := h.repairStaleCommentPlanIfNeeded(r.Context(), &task, rtWorkspaceID); handled {+ continue}- if uuidToString(issue.WorkspaceID) != runtimeWorkspaceID {- outcome = "error_workspace"- if _, cancelErr := h.TaskService.CancelTask(r.Context(), task.ID); cancelErr != nil {- slog.Error("task claim: cancel stale cross-workspace task failed",- "task_id", uuidToString(task.ID), "error", cancelErr)+ resp, deliveredCommentIDs, _, _, failure := h.buildClaimedTaskResponse(r, &task, rt, uuidToString(task.RuntimeID), rtWorkspaceID)+ if failure != nil {+ // Builder rejected this task (workspace isolation / chat-input);+ // it has already cancelled the task where the failure requires it.+ // Skip it — non-cancelling failures leave the task dispatched for+ // the reclaim path.+ continue+ }+ if !rt.OwnerID.Valid {+ slog.Error("batch claim: runtime owner missing; cancelling task to avoid unscoped agent credentials",+ "task_id", uuidToString(task.ID), "runtime_id", uuidToString(task.RuntimeID))+ if _, cerr := h.TaskService.CancelTask(r.Context(), task.ID); cerr != nil {+ slog.Error("batch claim: cancel after missing runtime owner failed",+ "task_id", uuidToString(task.ID), "error", cerr)}- writeError(w, http.StatusInternalServerError, "task workspace isolation check failed")- return+ continue}- cancelled, cancelErr := h.TaskService.CancelTask(r.Context(), task.ID)- if cancelErr != nil {- outcome = "error_stale_comment_plan"- writeError(w, http.StatusInternalServerError, "failed to repair stale comment task")- return+ tokenStr, terr := auth.GenerateAgentTaskToken()+ if terr != nil {+ slog.Error("batch claim: generate task token failed; requeueing claim",+ "task_id", uuidToString(task.ID), "error", terr)+ if _, rerr := h.TaskService.RequeueTaskAfterClaimFailure(r.Context(), task); rerr != nil {+ slog.Error("batch claim: requeue after token-gen failure failed",+ "task_id", uuidToString(task.ID), "error", rerr)+ }+ continue}- h.retriggerCancelledTaskSurvivors(r.Context(), issue, []db.AgentTaskQueue{*cancelled}, pgtype.UUID{})- outcome = "repaired_stale_comment_plan"- payloadBytes, _ = writeMeasuredJSON(w, http.StatusOK, map[string]any{"task": nil})- return+ // Route through the SAME finalization as the per-runtime endpoint so the+ // token and the comment-delivery receipt (delivered_comment_ids for+ // comment/coalesced-comment tasks) are persisted atomically; on failure+ // the exact claim is requeued and omitted from this batch.+ commentBackedTask := task.TriggerCommentID.Valid || len(task.CoalescedCommentIds) > 0+ receipt, ferr := h.TaskService.FinalizeTaskClaim(r.Context(), task, db.CreateTaskTokenParams{+ TokenHash: auth.HashToken(tokenStr),+ TaskID: task.ID,+ AgentID: task.AgentID,+ WorkspaceID: parseUUID(resp.WorkspaceID),+ UserID: rt.OwnerID,+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},+ }, deliveredCommentIDs, commentBackedTask)+ if ferr != nil {+ slog.Error("batch claim: finalize task claim failed; requeueing claim",+ "task_id", uuidToString(task.ID), "error", ferr)+ if _, rerr := h.TaskService.RequeueTaskAfterClaimFailure(r.Context(), task); rerr != nil {+ slog.Error("batch claim: requeue after finalize failure failed",+ "task_id", uuidToString(task.ID), "error", rerr)+ }+ continue+ }+ resp.AuthToken = tokenStr+ resp.DeliveredCommentIDs = uuidStringsOrEmpty(receipt)+ out = append(out, resp)}- outcome = "claimed"- buildStart = time.Now()+ if len(out) > 0 {+ slog.Info("tasks claimed by runtime batch",+ "runtimes", len(authorized), "requested_max", maxTasks, "claimed", len(out),+ "total_ms", time.Since(start).Milliseconds())+ }+ writeMeasuredJSON(w, http.StatusOK, map[string]any{"tasks": out})+}++// claimBuildFailure captures a pre-response failure from+// buildClaimedTaskResponse (workspace isolation, chat-input load/empty, ...) so+// the per-runtime handler can render the exact status/message/outcome and the+// batch handler can skip the task. Any task cancellation is already performed+// inside the builder before it returns one.+type claimBuildFailure struct {+ outcome string+ status int+ message string+}+// buildClaimedTaskResponse assembles the full daemon claim payload for a+// single already-claimed task and computes the exact comment ids embedded in+// it (deliveredCommentIDs). Shared by the per-runtime handler+// (ClaimTaskByRuntime) and the machine-level batch handler+// (ClaimTasksByRuntime, MUL-4257) so both build byte-identical payloads and+// feed the same delivery receipt into FinalizeTaskClaim. A non-nil failure+// means the task must not be dispatched; the builder has already cancelled it+// where the failure semantics require it.+func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQueue, runtime db.AgentRuntime, runtimeID, runtimeWorkspaceID string) (resp AgentTaskResponse, deliveredCommentIDs []pgtype.UUID, agentSkillCount, builtinSkillCount int, failure *claimBuildFailure) {// Build response with fresh agent data (name + skills + custom_env + custom_args).- resp := taskToResponse(*task, runtimeWorkspaceID)+ resp = taskToResponse(*task, runtimeWorkspaceID)+ supportsCoalescedComments := requestHasDaemonCapability(r, protocol.DaemonCapabilityCoalescedCommentsV1)// Empty-but-non-nil so pgx persists '{}' rather than NULL for tasks without// comment input. Comment tasks replace this with the ids actually embedded// in the capability-aware response built below.- deliveredCommentIDs := []pgtype.UUID{}- commentBackedTask := task.TriggerCommentID.Valid || len(task.CoalescedCommentIds) > 0- requeueFailedClaim := func(reason string) {- if _, err := h.TaskService.RequeueTaskAfterClaimFailure(r.Context(), *task); err != nil {- slog.Error("task claim: failed to requeue after finalization error",- "task_id", uuidToString(task.ID),- "reason", reason,- "error", err,- )- }- }+ deliveredCommentIDs = []pgtype.UUID{}composioMCPEnabled := h.composioMCPAppsEnabled(r.Context())if composioMCPEnabled {resp.ConnectedApps = parseRuntimeConnectedAppsForClaim(task.RuntimeConnectedApps, task.ID)@@ -1924,13 +2083,15 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {// and reject the claim with 5xx, rather than cancelling a valid direct// task on a transient DB error (MUL-4351 review).if inputLoadErr != nil {- outcome = "error_chat_input_load"slog.Error("chat claim: load chat input messages failed; preserving task for redelivery","task_id", uuidToString(task.ID),"chat_session_id", uuidToString(cs.ID),"error", inputLoadErr)- writeError(w, http.StatusInternalServerError, "failed to load chat input")- return+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{+ outcome: "error_chat_input_load",+ status: http.StatusInternalServerError,+ message: "failed to load chat input",+ }}parts := make([]string, 0, len(unanswered))@@ -1960,7 +2121,6 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {// corrupt state — cancel the just-dispatched task and reject the claim// rather than run the agent with nothing to answer (MUL-4351).if task.ChatInputTaskID.Valid && !resp.ChatIntro && strings.TrimSpace(resp.ChatMessage) == "" {- outcome = "error_empty_chat_input"slog.Error("chat claim: task-owned direct task has no user input; cancelling","task_id", uuidToString(task.ID),"chat_session_id", uuidToString(cs.ID),@@ -1970,8 +2130,11 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {slog.Error("chat claim: cancel after empty input failed","task_id", uuidToString(task.ID), "error", cerr)}- writeError(w, http.StatusInternalServerError, "chat task has no user input")- return+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{+ outcome: "error_empty_chat_input",+ status: http.StatusInternalServerError,+ message: "chat task has no user input",+ }}if strings.TrimSpace(resp.ThreadName) == "" && resp.ChatMessage != "" {@@ -2154,7 +2317,6 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {// fail AND cancel the just-dispatched task so the queue / agent status// don't sit stuck until the stale-task sweeper fires minutes later.if resp.WorkspaceID == "" || resp.WorkspaceID != runtimeWorkspaceID {- outcome = "error_workspace"slog.Error("task claim: workspace isolation check failed, cancelling task","task_id", uuidToString(task.ID),"runtime_id", runtimeID,@@ -2169,8 +2331,11 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {slog.Error("task claim: cancel after workspace check failed","task_id", uuidToString(task.ID), "error", cerr)}- writeError(w, http.StatusInternalServerError, "task workspace isolation check failed")- return+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{+ outcome: "error_workspace",+ status: http.StatusInternalServerError,+ message: "task workspace isolation check failed",+ }}// Workspace-level Context (workspace.context DB column) — the per-workspace@@ -2191,6 +2356,94 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {)}+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, nil+}++// ClaimTaskByRuntime atomically claims the next queued task for a runtime.+// The response includes the agent's name and skills, fetched fresh from the DB.+func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {+ runtimeID := chi.URLParam(r, "runtimeId")+ start := time.Now()++ var (+ outcome = "unauth"+ authMs, claimMs, buildMs int64+ payloadBytes int+ agentSkillCount int+ builtinSkillCount int+ skillPayloadBytes int+ buildStart time.Time+ )+ defer func() {+ // Emit at function exit so error / unauth paths also carry timing.+ // build_ms is computed from buildStart only when we entered the+ // response-build phase (otherwise stays 0).+ if !buildStart.IsZero() {+ buildMs = time.Since(buildStart).Milliseconds()+ }+ logClaimEndpointSlow(runtimeID, outcome, start, authMs, claimMs, buildMs, payloadBytes, agentSkillCount, builtinSkillCount, skillPayloadBytes)+ }()++ // Verify the caller owns this runtime's workspace. The runtime's+ // workspace_id is the authoritative value a claimed task must match+ // below — a task whose resolved workspace doesn't equal this runtime's+ // workspace is rejected even if it was enqueued against this+ // runtime_id (defense-in-depth against upstream routing bugs).+ runtime, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID)+ if !ok {+ return+ }+ runtimeWorkspaceID := uuidToString(runtime.WorkspaceID)+ authMs = time.Since(start).Milliseconds()++ claimStart := time.Now()+ task, err := h.TaskService.ClaimTaskForRuntime(r.Context(), parseUUID(runtimeID))+ claimMs = time.Since(claimStart).Milliseconds()+ if err != nil {+ outcome = "error_claim"+ writeError(w, http.StatusInternalServerError, "failed to claim task: "+err.Error())+ return+ }++ if task == nil {+ slog.Debug("no task to claim", "runtime_id", runtimeID)+ payloadBytes, _ = writeMeasuredJSON(w, http.StatusOK, map[string]any{"task": nil})+ outcome = "no_task"+ return+ }+ if !task.TriggerCommentID.Valid && len(task.CoalescedCommentIds) > 0 {+ handled, failure := h.repairStaleCommentPlanIfNeeded(r.Context(), task, runtimeWorkspaceID)+ if handled {+ if failure != nil {+ outcome = failure.outcome+ writeError(w, failure.status, failure.message)+ return+ }+ outcome = "repaired_stale_comment_plan"+ payloadBytes, _ = writeMeasuredJSON(w, http.StatusOK, map[string]any{"task": nil})+ return+ }+ }++ outcome = "claimed"+ buildStart = time.Now()++ resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, failure := h.buildClaimedTaskResponse(r, task, runtime, runtimeID, runtimeWorkspaceID)+ if failure != nil {+ outcome = failure.outcome+ writeError(w, failure.status, failure.message)+ return+ }+ commentBackedTask := task.TriggerCommentID.Valid || len(task.CoalescedCommentIds) > 0+ requeueFailedClaim := func(reason string) {+ if _, err := h.TaskService.RequeueTaskAfterClaimFailure(r.Context(), *task); err != nil {+ slog.Error("task claim: failed to requeue after finalization error",+ "task_id", uuidToString(task.ID),+ "reason", reason,+ "error", err,+ )+ }+ }// Mint a task-scoped `mat_` token bound to (agent, task, workspace,// owner). The daemon will inject this as MULTICA_TOKEN into the agent// process instead of its own credential, so any API call the agentdiff --git a/server/internal/handler/daemon_batch_claim_finalize_test.go b/server/internal/handler/daemon_batch_claim_finalize_test.gonew file mode 100644index 0000000000..7068e3df13--- /dev/null+++ b/server/internal/handler/daemon_batch_claim_finalize_test.go@@ -0,0 +1,349 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++type batchClaimReceiptResponse struct {+ Tasks []struct {+ ID string `json:"id"`+ RuntimeID string `json:"runtime_id"`+ AuthToken string `json:"auth_token"`+ DeliveredCommentIDs []string `json:"delivered_comment_ids"`+ } `json:"tasks"`+}++// TestClaimTasksByRuntime_MaxTasksZeroClaimsNothing pins the MUL-4257 review+// fix: max_tasks=0 is a valid "no free slots" poll that must claim nothing —+// it must NOT be coerced to 1 (which would dispatch a task the daemon can't run+// and strand it until stale reclaim).+func TestClaimTasksByRuntime_MaxTasksZeroClaimsNothing(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ rt := createClaimReclaimRuntime(t, ctx, "Batch max0 rt")+ a, i := createClaimReclaimAgentAndIssue(t, ctx, rt, "Batch max0 agent")+ taskID := seedQueuedIssueTask(t, ctx, a, rt, i)++ w := postBatchClaim(t, testWorkspaceID, []string{rt}, 0)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp batchClaimReceiptResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(resp.Tasks) != 0 {+ t.Fatalf("max_tasks=0 claimed %d tasks, want 0", len(resp.Tasks))+ }+ var status string+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {+ t.Fatalf("read status: %v", err)+ }+ if status != "queued" {+ t.Fatalf("task status = %s, want still queued", status)+ }+}++// TestClaimTasksByRuntime_MaxTasksNegativeIsBadRequest pins that a negative+// max_tasks is rejected rather than silently coerced.+func TestClaimTasksByRuntime_MaxTasksNegativeIsBadRequest(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ rt := createClaimReclaimRuntime(t, context.Background(), "Batch neg rt")+ w := postBatchClaim(t, testWorkspaceID, []string{rt}, -1)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for negative max_tasks, got %d: %s", w.Code, w.Body.String())+ }+}++// TestClaimTasksByRuntime_SkipsInvalidRuntimeID pins the MUL-4257 review fix:+// a malformed runtime_id must be skipped (non-panicking parse), not turned into+// a 500 — and a valid runtime in the same request is still claimed.+func TestClaimTasksByRuntime_SkipsInvalidRuntimeID(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ rt := createClaimReclaimRuntime(t, ctx, "Batch badid rt")+ a, i := createClaimReclaimAgentAndIssue(t, ctx, rt, "Batch badid agent")+ seedQueuedIssueTask(t, ctx, a, rt, i)++ w := postBatchClaim(t, testWorkspaceID, []string{"not-a-uuid", rt}, 5)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200 (invalid id skipped, not 500), got %d: %s", w.Code, w.Body.String())+ }+ var resp batchClaimReceiptResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(resp.Tasks) != 1 || resp.Tasks[0].RuntimeID != rt {+ t.Fatalf("expected the valid runtime's task to be claimed despite the invalid id, got %+v", resp.Tasks)+ }+}++// seedCommentBackedQueuedTask inserts a queued task triggered by a real comment+// on its issue, returning (taskID, commentID).+func seedCommentBackedQueuedTask(t *testing.T, ctx context.Context, agentID, runtimeID, issueID string) (string, string) {+ t.Helper()+ var commentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)+ VALUES ($1, $2, 'member', $3, 'please handle this')+ RETURNING id+ `, testWorkspaceID, issueID, testUserID).Scan(&commentID); err != nil {+ t.Fatalf("seed comment: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, commentID) })++ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority)+ VALUES ($1, $2, $3, $4, 'queued', 0)+ RETURNING id+ `, agentID, runtimeID, issueID, commentID).Scan(&taskID); err != nil {+ t.Fatalf("seed comment-backed task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ return taskID, commentID+}++func assertCommentDelivered(t *testing.T, ctx context.Context, taskID, commentID string) {+ t.Helper()+ var member bool+ if err := testPool.QueryRow(ctx, `+ SELECT $1 = ANY(delivered_comment_ids) FROM agent_task_queue WHERE id = $2+ `, commentID, taskID).Scan(&member); err != nil {+ t.Fatalf("read delivered_comment_ids: %v", err)+ }+ if !member {+ t.Fatalf("trigger comment %s not persisted in task %s delivered_comment_ids", commentID, taskID)+ }+}++// TestClaimTasksByRuntime_PersistsCommentDeliveryReceipt pins the MUL-4257+// must-fix: the batch path routes through FinalizeTaskClaim, so a comment-backed+// task claimed via batch persists the delivered_comment_ids receipt AND returns+// it in the response.+func TestClaimTasksByRuntime_PersistsCommentDeliveryReceipt(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ rt := createClaimReclaimRuntime(t, ctx, "Batch receipt rt")+ a, i := createClaimReclaimAgentAndIssue(t, ctx, rt, "Batch receipt agent")+ taskID, commentID := seedCommentBackedQueuedTask(t, ctx, a, rt, i)++ w := postBatchClaim(t, testWorkspaceID, []string{rt}, 5)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp batchClaimReceiptResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(resp.Tasks) != 1 {+ t.Fatalf("claimed %d tasks, want 1: %s", len(resp.Tasks), w.Body.String())+ }+ found := false+ for _, id := range resp.Tasks[0].DeliveredCommentIDs {+ if id == commentID {+ found = true+ }+ }+ if !found {+ t.Fatalf("response delivered_comment_ids %v missing trigger comment %s", resp.Tasks[0].DeliveredCommentIDs, commentID)+ }+ assertCommentDelivered(t, ctx, taskID, commentID)+}++// TestClaimTasksByRuntime_StaleReclaimRecordsDeliveryReceipt pins that a+// comment-backed task recovered via the batch reclaim path (dispatched, never+// started, past the recovery window) is re-finalized so its delivery receipt is+// recorded on the replacement claim.+func TestClaimTasksByRuntime_StaleReclaimRecordsDeliveryReceipt(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ rt := createClaimReclaimRuntime(t, ctx, "Batch stale-receipt rt")+ a, i := createClaimReclaimAgentAndIssue(t, ctx, rt, "Batch stale-receipt agent")++ var commentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)+ VALUES ($1, $2, 'member', $3, 'stale reclaim comment')+ RETURNING id+ `, testWorkspaceID, i, testUserID).Scan(&commentID); err != nil {+ t.Fatalf("seed comment: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, commentID) })++ // Stale dispatched, comment-backed, never started, past the 90s window.+ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority, dispatched_at, started_at)+ VALUES ($1, $2, $3, $4, 'dispatched', 0, now() - interval '120 seconds', NULL)+ RETURNING id+ `, a, rt, i, commentID).Scan(&taskID); err != nil {+ t.Fatalf("seed stale dispatched comment task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })++ w := postBatchClaim(t, testWorkspaceID, []string{rt}, 5)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp batchClaimReceiptResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(resp.Tasks) != 1 || resp.Tasks[0].ID != taskID {+ t.Fatalf("expected the stale task %s reclaimed, got %+v", taskID, resp.Tasks)+ }+ assertCommentDelivered(t, ctx, taskID, commentID)+}++// TestClaimTasksByRuntime_SkipsRuntimeOwnedByAnotherDaemon pins the MUL-4257+// review must-fix: a daemon must not batch-claim a task routed to a runtime+// bound to a DIFFERENT daemon, even in the same workspace. The runtime is+// skipped and its task stays queued for the owning machine.+func TestClaimTasksByRuntime_SkipsRuntimeOwnedByAnotherDaemon(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ // Runtime bound to a different daemon in the same (handler-test) workspace.+ var rt string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_runtime (workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, visibility, owner_id)+ VALUES ($1, 'other-daemon-machine', 'Other daemon RT', 'cloud', 'handler_test_runtime', 'online', 'x', '{}'::jsonb, now(), 'private', $2)+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&rt); err != nil {+ t.Fatalf("create other-daemon runtime: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, rt) })++ a, i := createClaimReclaimAgentAndIssue(t, ctx, rt, "Other daemon agent")+ taskID := seedQueuedIssueTask(t, ctx, a, rt, i)++ // postBatchClaim sends daemon_id = batchClaimTestDaemonID ("batch-claim-review"),+ // which differs from the runtime's "other-daemon-machine".+ w := postBatchClaim(t, testWorkspaceID, []string{rt}, 5)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp batchClaimReceiptResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(resp.Tasks) != 0 {+ t.Fatalf("daemon-A claimed %d tasks from a runtime owned by daemon-B, want 0", len(resp.Tasks))+ }+ var status string+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {+ t.Fatalf("read status: %v", err)+ }+ if status != "queued" {+ t.Fatalf("task status = %s, want still queued for the owning daemon", status)+ }+}++// TestClaimTasksByRuntime_RequiresDaemonID pins that the batch claim rejects a+// request with no daemon_id rather than falling back to workspace-only scoping.+func TestClaimTasksByRuntime_RequiresDaemonID(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/tasks/claim",+ map[string]any{"runtime_ids": []string{}, "max_tasks": 5},+ testWorkspaceID, batchClaimTestDaemonID)+ testHandler.ClaimTasksByRuntime(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 when daemon_id is missing, got %d: %s", w.Code, w.Body.String())+ }+}++// TestClaimTasksByRuntime_RepairsStaleCommentPlan pins the MUL-4257 review+// must-fix: when a claimed task's trigger comment was deleted (only coalesced+// survivors remain), the batch path must NOT finalize+dispatch it (which would+// silently drop the surviving comment). Instead it cancels the stale task,+// omits it from the batch, and replays the surviving comment as a fresh plan.+func TestClaimTasksByRuntime_RepairsStaleCommentPlan(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ rt := createClaimReclaimRuntime(t, ctx, "Stale plan rt")+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, rt, "Stale plan agent")+ // Assign the issue to the agent so the surviving comment re-routes to it.+ if _, err := testPool.Exec(ctx, `UPDATE issue SET assignee_type='agent', assignee_id=$1 WHERE id=$2`, agentID, issueID); err != nil {+ t.Fatalf("assign issue: %v", err)+ }++ // A surviving member comment on the issue.+ var survivorID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)+ VALUES ($1, $2, 'member', $3, 'please still handle this')+ RETURNING id+ `, testWorkspaceID, issueID, testUserID).Scan(&survivorID); err != nil {+ t.Fatalf("seed survivor comment: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, survivorID) })++ // Stale plan: trigger_comment_id NULL, only coalesced survivor remains.+ var staleID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, coalesced_comment_ids)+ VALUES ($1, $2, $3, 'queued', 0, ARRAY[$4]::uuid[])+ RETURNING id+ `, agentID, rt, issueID, survivorID).Scan(&staleID); err != nil {+ t.Fatalf("seed stale task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, staleID) })+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })++ w := postBatchClaim(t, testWorkspaceID, []string{rt}, 5)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp batchClaimReceiptResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ // (1) The stale task must not be returned.+ for _, task := range resp.Tasks {+ if task.ID == staleID {+ t.Fatalf("stale-plan task %s was dispatched by the batch path; want it repaired/omitted", staleID)+ }+ }+ // (2) The stale task must be cancelled.+ var status string+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, staleID).Scan(&status); err != nil {+ t.Fatalf("read stale status: %v", err)+ }+ if status != "cancelled" {+ t.Fatalf("stale task status = %s, want cancelled", status)+ }+ // (3) The surviving comment was rebuilt into a fresh plan (a new task with+ // the survivor as its trigger).+ var rebuilt int+ if err := testPool.QueryRow(ctx, `+ SELECT count(*) FROM agent_task_queue+ WHERE issue_id = $1 AND trigger_comment_id = $2 AND id <> $3+ `, issueID, survivorID, staleID).Scan(&rebuilt); err != nil {+ t.Fatalf("count rebuilt: %v", err)+ }+ if rebuilt < 1 {+ t.Fatalf("expected the surviving comment rebuilt into a new trigger task, found %d", rebuilt)+ }+}diff --git a/server/internal/handler/daemon_batch_claim_test.go b/server/internal/handler/daemon_batch_claim_test.gonew file mode 100644index 0000000000..80f0aae5f5--- /dev/null+++ b/server/internal/handler/daemon_batch_claim_test.go@@ -0,0 +1,194 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++// batchClaimResponse mirrors the {"tasks":[...]} envelope ClaimTasksByRuntime+// returns, with the few fields these tests assert on.+type batchClaimResponse struct {+ Tasks []struct {+ ID string `json:"id"`+ RuntimeID string `json:"runtime_id"`+ AuthToken string `json:"auth_token"`+ } `json:"tasks"`+}++func seedQueuedIssueTask(t *testing.T, ctx context.Context, agentID, runtimeID, issueID string) string {+ t.Helper()+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)+ VALUES ($1, $2, $3, 'queued', 0)+ RETURNING id+ `, agentID, runtimeID, issueID).Scan(&id); err != nil {+ t.Fatalf("seed queued task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, id) })+ return id+}++func postBatchClaim(t *testing.T, workspaceID string, runtimeIDs []string, maxTasks int) *httptest.ResponseRecorder {+ t.Helper()+ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/tasks/claim",+ map[string]any{"daemon_id": batchClaimTestDaemonID, "runtime_ids": runtimeIDs, "max_tasks": maxTasks},+ workspaceID, batchClaimTestDaemonID)+ testHandler.ClaimTasksByRuntime(w, req)+ return w+}++// batchClaimTestDaemonID is the daemon id used by both the mdt_ token context+// and the request body in batch-claim handler tests, so the daemon_id+// consistency check passes on the happy path.+const batchClaimTestDaemonID = "batch-claim-review"++// TestClaimTasksByRuntime_RoutesAcrossRuntimesAndMintsTokens covers the happy+// path: one call claims across two runtimes on the same machine, returns one+// task per runtime (per-agent dedup), and mints a task-scoped token for each.+func TestClaimTasksByRuntime_RoutesAcrossRuntimesAndMintsTokens(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ rt1 := createClaimReclaimRuntime(t, ctx, "Batch claim rt1")+ rt2 := createClaimReclaimRuntime(t, ctx, "Batch claim rt2")+ a1, i1 := createClaimReclaimAgentAndIssue(t, ctx, rt1, "Batch claim a1")+ a2, i2 := createClaimReclaimAgentAndIssue(t, ctx, rt2, "Batch claim a2")+ seedQueuedIssueTask(t, ctx, a1, rt1, i1)+ seedQueuedIssueTask(t, ctx, a2, rt2, i2)++ w := postBatchClaim(t, testWorkspaceID, []string{rt1, rt2}, 5)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp batchClaimResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(resp.Tasks) != 2 {+ t.Fatalf("claimed %d tasks, want 2: %s", len(resp.Tasks), w.Body.String())+ }+ seen := map[string]int{}+ for _, task := range resp.Tasks {+ seen[task.RuntimeID]+++ if !strings.HasPrefix(task.AuthToken, "mat_") {+ t.Fatalf("task %s missing mat_ task token, got %q", task.ID, task.AuthToken)+ }+ }+ if seen[rt1] != 1 || seen[rt2] != 1 {+ t.Fatalf("runtime distribution = %v, want one task each for rt1/rt2", seen)+ }+}++// TestClaimTasksByRuntime_SkipsCrossWorkspaceRuntime is the security-critical+// case: a daemon token scoped to workspace A must not claim a task routed to a+// runtime in workspace B, even when B's runtime_id is included in the request.+func TestClaimTasksByRuntime_SkipsCrossWorkspaceRuntime(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ // A foreign workspace with its own runtime + agent + queued task.+ var foreignUser, foreignWS string+ if err := testPool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Foreign User', '[email protected]') RETURNING id`).Scan(&foreignUser); err != nil {+ t.Fatalf("foreign user: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM "user" WHERE id = $1`, foreignUser) })+ if err := testPool.QueryRow(ctx, `INSERT INTO workspace (name, slug, description, issue_prefix) VALUES ('Foreign WS','batch-foreign-ws','x','FGN') RETURNING id`).Scan(&foreignWS); err != nil {+ t.Fatalf("foreign workspace: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, foreignWS) })+ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1,$2,'owner')`, foreignWS, foreignUser); err != nil {+ t.Fatalf("foreign member: %v", err)+ }+ var foreignRT, foreignAgent, foreignIssue string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_runtime (workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, visibility, owner_id)+ VALUES ($1, NULL, 'Foreign RT', 'cloud', 'handler_test_runtime', 'online', 'x', '{}'::jsonb, now(), 'private', $2)+ RETURNING id`, foreignWS, foreignUser).Scan(&foreignRT); err != nil {+ t.Fatalf("foreign runtime: %v", err)+ }+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent (workspace_id, name, description, runtime_mode, runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id)+ VALUES ($1, 'Foreign Agent', '', 'cloud', '{}'::jsonb, $2, 'private', 1, $3)+ RETURNING id`, foreignWS, foreignRT, foreignUser).Scan(&foreignAgent); err != nil {+ t.Fatalf("foreign agent: %v", err)+ }+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)+ VALUES ($1, 'foreign issue', 'in_progress', 'none', $2, 'member', 1, 0)+ RETURNING id`, foreignWS, foreignUser).Scan(&foreignIssue); err != nil {+ t.Fatalf("foreign issue: %v", err)+ }+ foreignTask := seedQueuedIssueTask(t, ctx, foreignAgent, foreignRT, foreignIssue)++ // Daemon token scoped to the (unrelated) handler-test workspace.+ w := postBatchClaim(t, testWorkspaceID, []string{foreignRT}, 5)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp batchClaimResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(resp.Tasks) != 0 {+ t.Fatalf("cross-workspace claim leaked %d tasks, want 0: %s", len(resp.Tasks), w.Body.String())+ }+ var status string+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, foreignTask).Scan(&status); err != nil {+ t.Fatalf("read foreign task status: %v", err)+ }+ if status != "queued" {+ t.Fatalf("foreign task status = %s, want still queued (untouched)", status)+ }+}++// TestClaimTasksByRuntime_CancelsTaskWhenRuntimeOwnerMissing pins the+// unscoped-credential guard: a runtime with no owner cannot mint a task token,+// so the claimed task must be cancelled and omitted from the response rather+// than shipped without a scoped credential.+func TestClaimTasksByRuntime_CancelsTaskWhenRuntimeOwnerMissing(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var rtNull string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_runtime (workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, visibility, owner_id)+ VALUES ($1, NULL, 'Ownerless RT', 'cloud', 'handler_test_runtime', 'online', 'x', '{}'::jsonb, now(), 'private', NULL)+ RETURNING id`, testWorkspaceID).Scan(&rtNull); err != nil {+ t.Fatalf("ownerless runtime: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, rtNull) })++ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, rtNull, "Ownerless agent")+ taskID := seedQueuedIssueTask(t, ctx, agentID, rtNull, issueID)++ w := postBatchClaim(t, testWorkspaceID, []string{rtNull}, 1)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp batchClaimResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(resp.Tasks) != 0 {+ t.Fatalf("claimed %d tasks from owner-less runtime, want 0: %s", len(resp.Tasks), w.Body.String())+ }+ var status string+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {+ t.Fatalf("read task status: %v", err)+ }+ if status != "cancelled" {+ t.Fatalf("task status = %s, want cancelled (owner missing)", status)+ }+}diff --git a/server/internal/handler/daemon_rpc.go b/server/internal/handler/daemon_rpc.gonew file mode 100644index 0000000000..9a88332ba5--- /dev/null+++ b/server/internal/handler/daemon_rpc.go@@ -0,0 +1,90 @@+package handler++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "net/http"++ "github.com/multica-ai/multica/server/internal/daemonws"+ "github.com/multica-ai/multica/server/internal/middleware"+)++// rpcResponseCapture is a minimal in-memory http.ResponseWriter so a WS RPC can+// reuse an existing HTTP handler without a network round trip.+type rpcResponseCapture struct {+ header http.Header+ status int+ body bytes.Buffer+}++func (w *rpcResponseCapture) Header() http.Header {+ if w.header == nil {+ w.header = http.Header{}+ }+ return w.header+}++func (w *rpcResponseCapture) WriteHeader(code int) { w.status = code }++func (w *rpcResponseCapture) Write(b []byte) (int, error) {+ if w.status == 0 {+ w.status = http.StatusOK+ }+ return w.body.Write(b)+}++// DaemonRPCHandler is the daemonws.RPCHandler wired into the WS hub (MUL-4257).+// It dispatches a generic daemon:rpc_request to the matching HTTP handler,+// reusing all of its auth / payload-building / finalization logic by driving it+// with a synthetic in-process request carrying the WS connection's identity.+// The connection is already authenticated and pinned to its daemon + runtime+// set at connect, so the reused handler's per-runtime daemon/workspace checks+// see the same scope as the HTTP path.+func (h *Handler) DaemonRPCHandler(ctx context.Context, identity daemonws.ClientIdentity, method string, body json.RawMessage) (int, json.RawMessage, error) {+ switch method {+ case "tasks.claim":+ return h.rpcClaimTasks(ctx, identity, body)+ default:+ return http.StatusNotFound, nil, fmt.Errorf("unknown rpc method %q", method)+ }+}++func (h *Handler) rpcClaimTasks(ctx context.Context, identity daemonws.ClientIdentity, body json.RawMessage) (int, json.RawMessage, error) {+ if len(body) == 0 {+ body = json.RawMessage("{}")+ }+ reqCtx := ctx+ // A daemon-token connection is workspace-scoped: pin the daemon context so+ // the reused handler's daemon_id + workspace checks behave exactly like the+ // HTTP path. A PAT/cloud connection (no daemon id) authorizes per-workspace+ // via membership from X-User-ID instead, so we must NOT set a single-+ // workspace daemon context there (it would reject the daemon's other+ // workspaces).+ if identity.DaemonID != "" {+ reqCtx = middleware.WithDaemonContext(reqCtx, identity.PrimaryWorkspaceID(), identity.DaemonID)+ }+ req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, "/api/daemon/tasks/claim", bytes.NewReader(body))+ if err != nil {+ return http.StatusInternalServerError, nil, err+ }+ req.Header.Set("Content-Type", "application/json")+ if identity.UserID != "" {+ req.Header.Set("X-User-ID", identity.UserID)+ }+ if identity.Capabilities != "" {+ req.Header.Set("X-Client-Capabilities", identity.Capabilities)+ }+ if identity.ClientVersion != "" {+ req.Header.Set("X-Client-Version", identity.ClientVersion)+ }++ rec := &rpcResponseCapture{}+ h.ClaimTasksByRuntime(rec, req)+ status := rec.status+ if status == 0 {+ status = http.StatusOK+ }+ return status, json.RawMessage(rec.body.Bytes()), nil+}diff --git a/server/internal/handler/daemon_rpc_test.go b/server/internal/handler/daemon_rpc_test.gonew file mode 100644index 0000000000..3d92a37e65--- /dev/null+++ b/server/internal/handler/daemon_rpc_test.go@@ -0,0 +1,74 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "testing"++ "github.com/multica-ai/multica/server/internal/daemonws"+)++// TestDaemonRPCHandler_TasksClaim pins the WS-first claim binding (MUL-4257):+// a tasks.claim RPC, driven with the WS connection's identity, reuses the HTTP+// claim handler and claims a queued task for the daemon's runtime.+func TestDaemonRPCHandler_TasksClaim(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ rt := createClaimReclaimRuntime(t, ctx, "WS claim rt")+ a, i := createClaimReclaimAgentAndIssue(t, ctx, rt, "WS claim agent")+ taskID := seedQueuedIssueTask(t, ctx, a, rt, i)++ identity := daemonws.ClientIdentity{+ DaemonID: "ws-daemon",+ UserID: testUserID,+ WorkspaceID: testWorkspaceID,+ WorkspaceIDs: []string{testWorkspaceID},+ RuntimeIDs: []string{rt},+ }+ body, _ := json.Marshal(map[string]any{+ "daemon_id": "ws-daemon",+ "runtime_ids": []string{rt},+ "max_tasks": 5,+ })++ status, respBody, err := testHandler.DaemonRPCHandler(ctx, identity, "tasks.claim", body)+ if err != nil {+ t.Fatalf("DaemonRPCHandler: %v", err)+ }+ if status != http.StatusOK {+ t.Fatalf("status = %d, want 200: %s", status, string(respBody))+ }+ var resp batchClaimReceiptResponse+ if err := json.Unmarshal(respBody, &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(resp.Tasks) != 1 || resp.Tasks[0].ID != taskID {+ t.Fatalf("claimed %+v, want the queued task %s", resp.Tasks, taskID)+ }+ if resp.Tasks[0].RuntimeID != rt {+ t.Fatalf("claimed runtime = %s, want %s", resp.Tasks[0].RuntimeID, rt)+ }++ var dbStatus string+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&dbStatus); err != nil {+ t.Fatalf("read status: %v", err)+ }+ if dbStatus != "dispatched" {+ t.Fatalf("task status = %s, want dispatched", dbStatus)+ }+}++// TestDaemonRPCHandler_UnknownMethod returns 404 for an unknown method.+func TestDaemonRPCHandler_UnknownMethod(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ status, _, err := testHandler.DaemonRPCHandler(context.Background(),+ daemonws.ClientIdentity{DaemonID: "ws-daemon"}, "does.not.exist", nil)+ if status != http.StatusNotFound || err == nil {+ t.Fatalf("status=%d err=%v, want 404 + error", status, err)+ }+}diff --git a/server/internal/handler/daemon_ws.go b/server/internal/handler/daemon_ws.goindex a3f60ff7a9..11e8c9f23f 100644--- a/server/internal/handler/daemon_ws.go+++ b/server/internal/handler/daemon_ws.go@@ -52,6 +52,7 @@ func (h *Handler) DaemonWebSocket(w http.ResponseWriter, r *http.Request) {WorkspaceIDs: workspaceIDs,RuntimeIDs: runtimeIDs,ClientVersion: r.Header.Get("X-Client-Version"),+ Capabilities: r.Header.Get("X-Client-Capabilities"),})}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex eaed18216c..3208d256c7 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -1675,6 +1675,190 @@ func (s *TaskService) RequeueTaskAfterClaimFailure(ctx context.Context, task db.return &requeued, nil}+// ClaimTasksForRuntimes is the machine-level (MUL-4257) batch counterpart of+// ClaimTaskForRuntime: it claims up to maxTasks tasks across every runtime in+// runtimeIDs in a single call, so a daemon can poll for all of its runtimes+// with one HTTP request and a constant number of DB queries instead of one+// request (and one promote/reclaim/list cycle) per runtime.+//+// It preserves the exact per-runtime semantics, just set-ified:+// 1. promote due deferred tasks across the set (one UPDATE);+// 2. reclaim up to maxTasks stale-dispatched tasks across the set (one UPDATE)+// — done before the empty-cache check because a lost claim response moves+// the task out of `queued`, which the empty-queued cache cannot represent;+// 3. short-circuit runtimes whose empty-claim verdict is cached, sampling the+// invalidation version for the rest BEFORE the candidate SELECT;+// 4. list queued candidates across the non-empty set (one SELECT);+// 5. mark still-empty runtimes so their next idle poll skips Postgres;+// 6. claim per distinct agent via ClaimTask (unchanged — preserves the+// per-(issue, agent) serialization, the agent concurrency cap, and every+// dispatch side effect) until maxTasks is reached.+//+// The returned slice contains both reclaimed and freshly-claimed tasks, each+// already carrying its runtime_id so the daemon routes it to the matching+// runtime locally.+func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pgtype.UUID, maxTasks int) ([]db.AgentTaskQueue, error) {+ if len(runtimeIDs) == 0 || maxTasks <= 0 {+ return nil, nil+ }++ // De-dup runtime IDs defensively so MarkEmpty/version bookkeeping stays+ // unambiguous even if a daemon ever sends a duplicate.+ seen := make(map[string]struct{}, len(runtimeIDs))+ uniqueIDs := make([]pgtype.UUID, 0, len(runtimeIDs))+ runtimeInSet := make(map[string]struct{}, len(runtimeIDs))+ for _, rid := range runtimeIDs {+ key := util.UUIDToString(rid)+ runtimeInSet[key] = struct{}{}+ if _, dup := seen[key]; dup {+ continue+ }+ seen[key] = struct{}{}+ uniqueIDs = append(uniqueIDs, rid)+ }++ claimed := make([]db.AgentTaskQueue, 0, maxTasks)++ // 1. Promote due deferred tasks across the whole set (promote-first, like+ // the singular path). Replay the per-row side effects the singular service+ // method PromoteDueDeferredTasksForRuntime performs — crucially+ // EmptyClaim.Bump (via NotifyTaskEnqueued → notifyTaskAvailable) so a+ // just-promoted deferred task invalidates its runtime's cached empty+ // verdict BEFORE the empty-cache filter in step 3; otherwise a stale+ // MarkEmpty from a prior idle poll would short-circuit the runtime and the+ // promoted task would sit unclaimed until the empty key's TTL. Also emits+ // the deferred→queued UI event and the enqueue analytics sample.+ promoted, err := s.Queries.PromoteDueDeferredTasksForRuntimes(ctx, uniqueIDs)+ if err != nil {+ return nil, fmt.Errorf("promote deferred tasks: %w", err)+ }+ for _, task := range promoted {+ slog.Info("deferred fallback task promoted (batch)",+ "task_id", util.UUIDToString(task.ID),+ "runtime_id", util.UUIDToString(task.RuntimeID),+ "agent_id", util.UUIDToString(task.AgentID),+ )+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)+ s.NotifyTaskEnqueued(ctx, task)+ }++ // 2. Reclaim lost-response dispatched tasks across the set, up to maxTasks.+ reclaimed, err := s.Queries.ReclaimStaleDispatchedTasksForRuntimes(ctx, db.ReclaimStaleDispatchedTasksForRuntimesParams{+ RuntimeIds: uniqueIDs,+ ClaimRecoverySecs: claimResponseRecoveryWindow.Seconds(),+ PrepareLeaseSecs: prepareLeaseDuration.Seconds(),+ MaxTasks: int32(maxTasks),+ })+ if err != nil {+ return nil, fmt.Errorf("reclaim stale dispatched tasks: %w", err)+ }+ for i := range reclaimed {+ claimed = append(claimed, reclaimed[i])+ slog.Info("stale dispatched task reclaimed (batch)",+ "task_id", util.UUIDToString(reclaimed[i].ID),+ "runtime_id", util.UUIDToString(reclaimed[i].RuntimeID),+ "agent_id", util.UUIDToString(reclaimed[i].AgentID),+ )+ }+ if len(claimed) >= maxTasks {+ return claimed[:maxTasks], nil+ }++ // 3. Empty-cache short-circuit + version sampling for the remaining runtimes.+ nonEmpty := make([]pgtype.UUID, 0, len(uniqueIDs))+ versions := make(map[string]int64, len(uniqueIDs))+ for _, rid := range uniqueIDs {+ key := util.UUIDToString(rid)+ if s.EmptyClaim.IsEmpty(ctx, key) {+ continue+ }+ versions[key] = s.EmptyClaim.CurrentVersion(ctx, key)+ nonEmpty = append(nonEmpty, rid)+ }+ if len(nonEmpty) == 0 {+ return claimed, nil+ }++ // 4. One candidate SELECT across the non-empty set.+ candidates, err := s.Queries.ListQueuedClaimCandidatesByRuntimes(ctx, nonEmpty)+ if err != nil {+ // Steps 2/6 commit reclaimed/claimed tasks in their own transactions,+ // so `claimed` may already hold tasks dispatched server-side. Dropping+ // them with a 500 makes the daemon HTTP-fall-back and claim a SECOND+ // batch into the same free slots (the first batch then waits for stale+ // reclaim) — the same double-claim this PR set out to remove+ // (MUL-4257). Prefer partial success: hand back what committed so the+ // handler finalizes and returns it; the errored candidates stay queued+ // for the next poll.+ if len(claimed) > 0 {+ slog.Error("batch claim: candidate query failed after partial success; returning claimed tasks to avoid loss",+ "error", err, "claimed", len(claimed))+ return claimed, nil+ }+ return nil, fmt.Errorf("list queued claim candidates: %w", err)+ }++ // 5. Mark runtimes with zero candidates empty so their next idle poll skips+ // Postgres. Runtimes that had at least one candidate are intentionally not+ // marked (positive results always re-check the DB, matching the singular+ // path).+ withCandidates := make(map[string]struct{}, len(candidates))+ for i := range candidates {+ withCandidates[util.UUIDToString(candidates[i].RuntimeID)] = struct{}{}+ }+ for _, rid := range nonEmpty {+ key := util.UUIDToString(rid)+ if _, ok := withCandidates[key]; !ok {+ s.EmptyClaim.MarkEmpty(ctx, key, versions[key])+ }+ }++ // 6. Claim per distinct agent (unchanged path → same per-(issue, agent)+ // serialization, capacity cap, and dispatch side effects) until maxTasks is+ // reached.+ triedAgents := make(map[string]struct{}, len(candidates))+ for i := range candidates {+ if len(claimed) >= maxTasks {+ break+ }+ agentKey := util.UUIDToString(candidates[i].AgentID)+ if _, tried := triedAgents[agentKey]; tried {+ continue+ }+ triedAgents[agentKey] = struct{}{}++ task, err := s.ClaimTask(ctx, candidates[i].AgentID)+ if err != nil {+ // Each ClaimTask commits in its own transaction, so earlier+ // iterations (and step-2 reclaims) are already dispatched+ // server-side. Returning nil here would drop them and force the+ // daemon to double-claim via HTTP fallback (MUL-4257). Return the+ // partial batch instead; the failed agent's task stays queued.+ if len(claimed) > 0 {+ slog.Error("batch claim: claim task failed after partial success; returning claimed tasks to avoid loss",+ "error", err, "claimed", len(claimed))+ return claimed, nil+ }+ return nil, fmt.Errorf("claim task: %w", err)+ }+ if task == nil {+ continue+ }+ // ClaimAgentTask selects by agent only; guard that the claimed task+ // belongs to a runtime this daemon hosts. An agent with a+ // higher-priority queued task on ANOTHER daemon's runtime could+ // otherwise be dispatched here and dropped — matching the singular+ // path's runtime_id guard. Such a stray dispatch is recovered by the+ // reclaim path on the owning daemon's next poll.+ if _, ok := runtimeInSet[util.UUIDToString(task.RuntimeID)]; !ok {+ continue+ }+ claimed = append(claimed, *task)+ }++ return claimed, nil+}+func (s *TaskService) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) error {tasks, err := s.Queries.PromoteDueDeferredTasksForRuntime(ctx, runtimeID)if err != nil {diff --git a/server/internal/service/task_batch_claim_deferred_test.go b/server/internal/service/task_batch_claim_deferred_test.gonew file mode 100644index 0000000000..b5dbcc3bdd--- /dev/null+++ b/server/internal/service/task_batch_claim_deferred_test.go@@ -0,0 +1,121 @@+package service++import (+ "context"+ "fmt"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// TestClaimTasksForRuntimes_PromotesDeferredAndEmitsQueuedEvent is the+// regression test for the PR #5193 review must-fix: the batch promote step must+// replay the singular service method's per-row side effects — emit the+// deferred→queued (`task:queued`) event AND invalidate the empty-claim verdict+// via NotifyTaskEnqueued — so a just-promoted deferred task is claimable in the+// SAME batch call rather than sitting idle until the empty key's TTL.+//+// The empty-claim cache is nil in tests (no Redis), so this asserts the two+// directly observable halves of the fix: (1) the promoted task is claimed this+// round, and (2) a `task:queued` event is published for it.+func TestClaimTasksForRuntimes_PromotesDeferredAndEmitsQueuedEvent(t *testing.T) {+ ctx := context.Background()+ pool := newTaskClaimRacePool(t)+ bus := events.New()++ var mu sync.Mutex+ queuedTaskIDs := map[string]int{}+ bus.Subscribe(protocol.EventTaskQueued, func(e events.Event) {+ if payload, ok := e.Payload.(map[string]any); ok {+ if id, ok := payload["task_id"].(string); ok {+ mu.Lock()+ queuedTaskIDs[id]+++ mu.Unlock()+ }+ }+ })++ svc := NewTaskService(db.New(pool), pool, nil, bus)+ rt, deferredTaskID := deferredBatchFixture(t, ctx, pool)++ got, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{util.MustParseUUID(rt)}, 5)+ if err != nil {+ t.Fatalf("claim: %v", err)+ }+ if len(got) != 1 || util.UUIDToString(got[0].ID) != deferredTaskID {+ t.Fatalf("expected the promoted deferred task %s to be claimed this round, got %d tasks", deferredTaskID, len(got))+ }++ mu.Lock()+ n := queuedTaskIDs[deferredTaskID]+ mu.Unlock()+ if n != 1 {+ t.Fatalf("expected exactly one task:queued event for the promoted task, got %d", n)+ }+}++// deferredBatchFixture provisions one runtime + agent with a single DEFERRED+// task whose fire_at is already due. Returns the runtime id and the task id.+func deferredBatchFixture(t *testing.T, ctx context.Context, pool *pgxpool.Pool) (runtimeID, taskID string) {+ t.Helper()+ suffix := time.Now().UnixNano()++ var userID string+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1,$2) RETURNING id`,+ "Deferred Batch Test", fmt.Sprintf("deferred-batch-%[email protected]", suffix)).Scan(&userID); err != nil {+ t.Fatalf("create user: %v", err)+ }+ var workspaceID string+ if err := pool.QueryRow(ctx, `INSERT INTO workspace (name, slug, description, issue_prefix) VALUES ($1,$2,$3,$4) RETURNING id`,+ "Deferred Batch Test", fmt.Sprintf("deferred-batch-%d", suffix), "temp deferred batch test", "DBR").Scan(&workspaceID); err != nil {+ t.Fatalf("create workspace: %v", err)+ }+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1,$2,'owner')`, workspaceID, userID); err != nil {+ t.Fatalf("create member: %v", err)+ }+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent_runtime (workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, visibility, owner_id)+ VALUES ($1, 'daemon-deferred', 'Deferred RT', 'cloud', 'deferred_provider', 'online', 'x', '{}'::jsonb, now(), 'private', $2)+ RETURNING id`, workspaceID, userID).Scan(&runtimeID); err != nil {+ t.Fatalf("create runtime: %v", err)+ }+ var agentID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent (workspace_id, name, description, runtime_mode, runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id)+ VALUES ($1, 'Deferred Agent', '', 'cloud', '{}'::jsonb, $2, 'private', 5, $3)+ RETURNING id`, workspaceID, runtimeID, userID).Scan(&agentID); err != nil {+ t.Fatalf("create agent: %v", err)+ }+ var issueID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)+ VALUES ($1, 'deferred issue', 'in_progress', 'none', $2, 'member', 700001, 0)+ RETURNING id`, workspaceID, userID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, issue_id, status, priority, context, runtime_id, fire_at)+ VALUES ($1, $2, 'deferred', 0, '{}'::jsonb, $3, now() - interval '1 minute')+ RETURNING id`, agentID, issueID, runtimeID).Scan(&taskID); err != nil {+ t.Fatalf("create deferred task: %v", err)+ }++ t.Cleanup(func() {+ c := context.Background()+ pool.Exec(c, `DELETE FROM agent_task_queue WHERE agent_id = $1`, agentID)+ pool.Exec(c, `DELETE FROM issue WHERE workspace_id = $1`, workspaceID)+ pool.Exec(c, `DELETE FROM agent WHERE id = $1`, agentID)+ pool.Exec(c, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)+ pool.Exec(c, `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, workspaceID, userID)+ pool.Exec(c, `DELETE FROM workspace WHERE id = $1`, workspaceID)+ pool.Exec(c, `DELETE FROM "user" WHERE id = $1`, userID)+ })+ return runtimeID, taskID+}diff --git a/server/internal/service/task_batch_claim_partial_test.go b/server/internal/service/task_batch_claim_partial_test.gonew file mode 100644index 0000000000..e5d7475c27--- /dev/null+++ b/server/internal/service/task_batch_claim_partial_test.go@@ -0,0 +1,142 @@+package service++import (+ "context"+ "fmt"+ "strings"+ "sync"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// failNthBeginTxStarter fails the Nth Begin so a specific ClaimTask inside the+// batch loop errors AFTER earlier ones have committed.+type failNthBeginTxStarter struct {+ inner TxStarter+ failOn int+ mu sync.Mutex+ count int+}++func (s *failNthBeginTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {+ s.mu.Lock()+ s.count+++ n := s.count+ s.mu.Unlock()+ if n == s.failOn {+ return nil, fmt.Errorf("injected begin failure #%d", n)+ }+ return s.inner.Begin(ctx)+}++// candidateFailDBTX passes every statement through EXCEPT the batch candidate+// SELECT, which it fails — simulating a candidate query error after step-2+// reclaims have already committed.+type candidateFailDBTX struct{ inner db.DBTX }++func (f candidateFailDBTX) Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error) {+ return f.inner.Exec(ctx, sql, args...)+}++func (f candidateFailDBTX) Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error) {+ if strings.Contains(sql, "ListQueuedClaimCandidatesByRuntimes") {+ return nil, fmt.Errorf("injected candidate query failure")+ }+ return f.inner.Query(ctx, sql, args...)+}++func (f candidateFailDBTX) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row {+ return f.inner.QueryRow(ctx, sql, args...)+}++// TestClaimTasksForRuntimes_PartialSuccessOnSecondAgentClaimFailure is the+// MUL-4257 review regression: ClaimTask runs per agent in its own transaction,+// so when a later agent's claim fails the already-committed (dispatched) tasks+// must be RETURNED, not dropped with an error. Dropping them would 500 the+// handler and make the daemon HTTP-fall-back and double-claim the same slots.+func TestClaimTasksForRuntimes_PartialSuccessOnSecondAgentClaimFailure(t *testing.T) {+ ctx := context.Background()+ pool := newTaskClaimRacePool(t)+ tx := &failNthBeginTxStarter{inner: pool, failOn: 2} // 1st agent claims, 2nd errors+ svc := NewTaskService(db.New(pool), tx, nil, events.New())++ rt1, rt2 := batchClaimFixture(t, ctx, pool)+ ids := []pgtype.UUID{util.MustParseUUID(rt1), util.MustParseUUID(rt2)}++ claimed, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)+ if err != nil {+ t.Fatalf("expected partial success (nil error), got %v", err)+ }+ if len(claimed) != 1 {+ t.Fatalf("claimed %d tasks, want 1 (the first agent's committed task, not dropped)", len(claimed))+ }++ // The one returned task must actually be dispatched in the DB (committed),+ // proving we returned a real claim rather than a phantom.+ var status string+ if err := pool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, util.UUIDToString(claimed[0].ID)).Scan(&status); err != nil {+ t.Fatalf("read status: %v", err)+ }+ if status != "dispatched" {+ t.Fatalf("returned task status = %s, want dispatched", status)+ }+}++// TestClaimTasksForRuntimes_PartialSuccessOnCandidateQueryFailureAfterReclaim+// covers the other partial-commit path: step-2 reclaims a stale dispatched task+// (committed), then the step-4 candidate SELECT errors. The reclaimed task must+// be returned, not dropped — same double-claim risk otherwise (MUL-4257).+func TestClaimTasksForRuntimes_PartialSuccessOnCandidateQueryFailureAfterReclaim(t *testing.T) {+ ctx := context.Background()+ pool := newTaskClaimRacePool(t)+ svc := NewTaskService(db.New(candidateFailDBTX{inner: pool}), pool, nil, events.New())++ rt1, rt2 := batchClaimFixture(t, ctx, pool)++ // Seed a stale dispatched task on rt1 (never started, dispatched long ago,+ // no live prepare lease) so step-2 reclaim picks it up.+ var workspaceID, ownerID, agentID string+ if err := pool.QueryRow(ctx, `SELECT workspace_id, owner_id FROM agent_runtime WHERE id = $1`, rt1).Scan(&workspaceID, &ownerID); err != nil {+ t.Fatalf("load runtime: %v", err)+ }+ if err := pool.QueryRow(ctx, `SELECT id FROM agent WHERE runtime_id = $1 LIMIT 1`, rt1).Scan(&agentID); err != nil {+ t.Fatalf("load agent: %v", err)+ }+ var issueID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)+ VALUES ($1, 'stale dispatched', 'in_progress', 'none', $2, 'member', 900123, 99)+ RETURNING id`, workspaceID, ownerID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ var staleTaskID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, context, dispatched_at, started_at, prepare_lease_expires_at)+ VALUES ($1, $2, $3, 'dispatched', 0, '{}'::jsonb, now() - interval '1 hour', NULL, NULL)+ RETURNING id`, agentID, rt1, issueID).Scan(&staleTaskID); err != nil {+ t.Fatalf("create stale dispatched task: %v", err)+ }+ t.Cleanup(func() {+ c := context.Background()+ pool.Exec(c, `DELETE FROM agent_task_queue WHERE id = $1`, staleTaskID)+ pool.Exec(c, `DELETE FROM issue WHERE id = $1`, issueID)+ })++ ids := []pgtype.UUID{util.MustParseUUID(rt1), util.MustParseUUID(rt2)}+ claimed, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)+ if err != nil {+ t.Fatalf("expected partial success (nil error) despite candidate query failure, got %v", err)+ }+ if len(claimed) != 1 {+ t.Fatalf("claimed %d tasks, want 1 (the reclaimed task, not dropped)", len(claimed))+ }+ if util.UUIDToString(claimed[0].ID) != staleTaskID {+ t.Fatalf("returned task = %s, want the reclaimed stale task %s", util.UUIDToString(claimed[0].ID), staleTaskID)+ }+}diff --git a/server/internal/service/task_batch_claim_test.go b/server/internal/service/task_batch_claim_test.gonew file mode 100644index 0000000000..d9e556556c--- /dev/null+++ b/server/internal/service/task_batch_claim_test.go@@ -0,0 +1,181 @@+package service++import (+ "context"+ "fmt"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// batchClaimFixture provisions two runtimes on one machine, each with its own+// agent (max_concurrent_tasks=5): agent1 (on rt1) has two queued tasks on two+// different issues; agent2 (on rt2) has one queued task. Returns the two+// runtime IDs.+func batchClaimFixture(t *testing.T, ctx context.Context, pool *pgxpool.Pool) (rt1, rt2 string) {+ t.Helper()+ suffix := time.Now().UnixNano()++ var userID string+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1,$2) RETURNING id`,+ "Batch Claim Test", fmt.Sprintf("batch-claim-%[email protected]", suffix)).Scan(&userID); err != nil {+ t.Fatalf("create user: %v", err)+ }+ var workspaceID string+ if err := pool.QueryRow(ctx, `INSERT INTO workspace (name, slug, description, issue_prefix) VALUES ($1,$2,$3,$4) RETURNING id`,+ "Batch Claim Test", fmt.Sprintf("batch-claim-%d", suffix), "temp batch claim test workspace", "BCR").Scan(&workspaceID); err != nil {+ t.Fatalf("create workspace: %v", err)+ }+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1,$2,'owner')`, workspaceID, userID); err != nil {+ t.Fatalf("create member: %v", err)+ }++ mkRuntime := func(name, provider string) string {+ var id string+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent_runtime (workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, visibility, owner_id)+ VALUES ($1, 'daemon-batch', $2, 'cloud', $3, 'online', 'test runtime', '{}'::jsonb, now(), 'private', $4)+ RETURNING id`, workspaceID, name, provider, userID).Scan(&id); err != nil {+ t.Fatalf("create runtime %s: %v", name, err)+ }+ return id+ }+ mkAgent := func(name, runtimeID string) string {+ var id string+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent (workspace_id, name, description, runtime_mode, runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id)+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'private', 5, $4)+ RETURNING id`, workspaceID, name, runtimeID, userID).Scan(&id); err != nil {+ t.Fatalf("create agent %s: %v", name, err)+ }+ return id+ }++ rt1 = mkRuntime("Batch RT1", "batch_provider_1")+ rt2 = mkRuntime("Batch RT2", "batch_provider_2")+ agent1 := mkAgent("Batch Agent1", rt1)+ agent2 := mkAgent("Batch Agent2", rt2)++ mkQueuedTask := func(agentID, runtimeID string, n int) {+ var issueID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)+ VALUES ($1, $2, 'in_progress', 'none', $3, 'member', $4, $5)+ RETURNING id`, workspaceID, fmt.Sprintf("batch issue %d", n), userID, 800000+n, n).Scan(&issueID); err != nil {+ t.Fatalf("create issue %d: %v", n, err)+ }+ if _, err := pool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, issue_id, status, priority, context, runtime_id)+ VALUES ($1, $2, 'queued', 0, '{}'::jsonb, $3)`, agentID, issueID, runtimeID); err != nil {+ t.Fatalf("create task %d: %v", n, err)+ }+ // Space out created_at so ordering is deterministic.+ time.Sleep(2 * time.Millisecond)+ }+ mkQueuedTask(agent1, rt1, 1)+ mkQueuedTask(agent1, rt1, 2)+ mkQueuedTask(agent2, rt2, 3)++ t.Cleanup(func() {+ c := context.Background()+ pool.Exec(c, `DELETE FROM agent_task_queue WHERE agent_id IN ($1,$2)`, agent1, agent2)+ pool.Exec(c, `DELETE FROM issue WHERE workspace_id = $1`, workspaceID)+ pool.Exec(c, `DELETE FROM agent WHERE id IN ($1,$2)`, agent1, agent2)+ pool.Exec(c, `DELETE FROM agent_runtime WHERE id IN ($1,$2)`, rt1, rt2)+ pool.Exec(c, `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, workspaceID, userID)+ pool.Exec(c, `DELETE FROM workspace WHERE id = $1`, workspaceID)+ pool.Exec(c, `DELETE FROM "user" WHERE id = $1`, userID)+ })+ return rt1, rt2+}++// TestClaimTasksForRuntimes_MultiRuntimeDrain verifies the machine-level batch+// claim (MUL-4257): a single call claims across all runtimes, one task per+// agent per call (matching the singular path's dedup), routes each task to its+// runtime, respects a subsequent drain, and reports empty once nothing is+// queued.+func TestClaimTasksForRuntimes_MultiRuntimeDrain(t *testing.T) {+ ctx := context.Background()+ pool := newTaskClaimRacePool(t)+ svc := NewTaskService(db.New(pool), pool, nil, events.New())++ rt1, rt2 := batchClaimFixture(t, ctx, pool)+ ids := []pgtype.UUID{util.MustParseUUID(rt1), util.MustParseUUID(rt2)}++ // Call 1: one task per agent (agent1→rt1, agent2→rt2) => 2 tasks, one per runtime.+ got1, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)+ if err != nil {+ t.Fatalf("call1: %v", err)+ }+ if len(got1) != 2 {+ t.Fatalf("call1 claimed %d tasks, want 2", len(got1))+ }+ seen := map[string]int{}+ for _, task := range got1 {+ seen[util.UUIDToString(task.RuntimeID)]+++ }+ if seen[rt1] != 1 || seen[rt2] != 1 {+ t.Fatalf("call1 runtime distribution = %v, want one task each for rt1/rt2", seen)+ }++ // Call 2: agent1 still has a second queued task (different issue, capacity 5);+ // agent2 is drained => exactly 1 task, on rt1.+ got2, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)+ if err != nil {+ t.Fatalf("call2: %v", err)+ }+ if len(got2) != 1 {+ t.Fatalf("call2 claimed %d tasks, want 1", len(got2))+ }+ if util.UUIDToString(got2[0].RuntimeID) != rt1 {+ t.Fatalf("call2 claimed runtime = %s, want rt1", util.UUIDToString(got2[0].RuntimeID))+ }++ // Call 3: everything dispatched => empty.+ got3, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)+ if err != nil {+ t.Fatalf("call3: %v", err)+ }+ if len(got3) != 0 {+ t.Fatalf("call3 claimed %d tasks, want 0", len(got3))+ }+}++// TestClaimTasksForRuntimes_MaxTasksCap verifies max_tasks bounds the number of+// tasks returned in a single batch call.+func TestClaimTasksForRuntimes_MaxTasksCap(t *testing.T) {+ ctx := context.Background()+ pool := newTaskClaimRacePool(t)+ svc := NewTaskService(db.New(pool), pool, nil, events.New())++ rt1, rt2 := batchClaimFixture(t, ctx, pool)+ ids := []pgtype.UUID{util.MustParseUUID(rt1), util.MustParseUUID(rt2)}++ got, err := svc.ClaimTasksForRuntimes(ctx, ids, 1)+ if err != nil {+ t.Fatalf("claim: %v", err)+ }+ if len(got) != 1 {+ t.Fatalf("claimed %d tasks with max_tasks=1, want 1", len(got))+ }+}++// TestClaimTasksForRuntimes_EmptyInputs guards the trivial short-circuits.+func TestClaimTasksForRuntimes_EmptyInputs(t *testing.T) {+ ctx := context.Background()+ pool := newTaskClaimRacePool(t)+ svc := NewTaskService(db.New(pool), pool, nil, events.New())++ if got, err := svc.ClaimTasksForRuntimes(ctx, nil, 5); err != nil || got != nil {+ t.Fatalf("nil runtimes: got=%v err=%v, want nil,nil", got, err)+ }+ rt1, _ := batchClaimFixture(t, ctx, pool)+ if got, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{util.MustParseUUID(rt1)}, 0); err != nil || got != nil {+ t.Fatalf("maxTasks=0: got=%v err=%v, want nil,nil", got, err)+ }+}diff --git a/server/internal/service/task_finalize_failure_test.go b/server/internal/service/task_finalize_failure_test.gonew file mode 100644index 0000000000..03514ddf05--- /dev/null+++ b/server/internal/service/task_finalize_failure_test.go@@ -0,0 +1,141 @@+package service++import (+ "context"+ "errors"+ "fmt"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// TestFinalizeTaskClaimFailureRollsBackTokenThenRequeue is the regression for+// the PR #5193 review ask on the batch path's failure handling: when+// FinalizeTaskClaim fails (here: a delivery receipt referencing an id outside+// the task's comment plan, which the CAS subset-guard rejects), the token write+// is rolled back with it, and RequeueTaskAfterClaimFailure releases the exact+// dispatched claim back to `queued`. These are the two building blocks the+// batch handler composes on a finalization error.+func TestFinalizeTaskClaimFailureRollsBackTokenThenRequeue(t *testing.T) {+ ctx := context.Background()+ pool := newTaskClaimRacePool(t)+ svc := NewTaskService(db.New(pool), pool, nil, events.New())+ queries := db.New(pool)++ taskID, userID, workspaceID := dispatchedCommentTaskFixture(t, ctx, pool)+ task, err := queries.GetAgentTask(ctx, util.MustParseUUID(taskID))+ if err != nil {+ t.Fatalf("load task: %v", err)+ }++ // A delivered id outside the task's plan (no trigger/coalesced match) makes+ // SetTaskDeliveredCommentIDs match zero rows → FinalizeTaskClaim errors.+ bogus := util.MustParseUUID("11111111-1111-1111-1111-111111111111")+ _, ferr := svc.FinalizeTaskClaim(ctx, task, db.CreateTaskTokenParams{+ TokenHash: fmt.Sprintf("finalize-fail-hash-%d", time.Now().UnixNano()),+ TaskID: task.ID,+ AgentID: task.AgentID,+ WorkspaceID: util.MustParseUUID(workspaceID),+ UserID: util.MustParseUUID(userID),+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},+ }, []pgtype.UUID{bogus}, true)+ if ferr == nil {+ t.Fatal("expected FinalizeTaskClaim to fail for an out-of-plan delivery receipt")+ }+ if errors.Is(ferr, context.Canceled) {+ t.Fatalf("unexpected ctx error: %v", ferr)+ }++ // Token write must have rolled back with the receipt (transactional).+ var tokenCount int+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM task_token WHERE task_id = $1`, taskID).Scan(&tokenCount); err != nil {+ t.Fatalf("count tokens: %v", err)+ }+ if tokenCount != 0 {+ t.Fatalf("expected token rolled back, found %d task_token rows", tokenCount)+ }++ // The exact dispatched claim is released back to queued.+ if _, err := svc.RequeueTaskAfterClaimFailure(ctx, task); err != nil {+ t.Fatalf("requeue: %v", err)+ }+ var status string+ if err := pool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {+ t.Fatalf("read status: %v", err)+ }+ if status != "queued" {+ t.Fatalf("task status = %s, want queued after requeue", status)+ }+}++// dispatchedCommentTaskFixture provisions a comment-backed task already in the+// `dispatched` state (never started), returning (taskID, ownerUserID).+func dispatchedCommentTaskFixture(t *testing.T, ctx context.Context, pool *pgxpool.Pool) (taskID, userID, workspaceID string) {+ t.Helper()+ suffix := time.Now().UnixNano()++ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1,$2) RETURNING id`,+ "Finalize Fail Test", fmt.Sprintf("finalize-fail-%[email protected]", suffix)).Scan(&userID); err != nil {+ t.Fatalf("create user: %v", err)+ }+ if err := pool.QueryRow(ctx, `INSERT INTO workspace (name, slug, description, issue_prefix) VALUES ($1,$2,$3,$4) RETURNING id`,+ "Finalize Fail Test", fmt.Sprintf("finalize-fail-%d", suffix), "temp finalize-fail test", "FFR").Scan(&workspaceID); err != nil {+ t.Fatalf("create workspace: %v", err)+ }+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1,$2,'owner')`, workspaceID, userID); err != nil {+ t.Fatalf("create member: %v", err)+ }+ var runtimeID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent_runtime (workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, visibility, owner_id)+ VALUES ($1, 'daemon-ff', 'FF RT', 'cloud', 'ff_provider', 'online', 'x', '{}'::jsonb, now(), 'private', $2)+ RETURNING id`, workspaceID, userID).Scan(&runtimeID); err != nil {+ t.Fatalf("create runtime: %v", err)+ }+ var agentID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent (workspace_id, name, description, runtime_mode, runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id)+ VALUES ($1, 'FF Agent', '', 'cloud', '{}'::jsonb, $2, 'private', 5, $3)+ RETURNING id`, workspaceID, runtimeID, userID).Scan(&agentID); err != nil {+ t.Fatalf("create agent: %v", err)+ }+ var issueID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)+ VALUES ($1, 'ff issue', 'in_progress', 'none', $2, 'member', 600001, 0)+ RETURNING id`, workspaceID, userID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ var commentID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)+ VALUES ($1, $2, 'member', $3, 'ff comment')+ RETURNING id`, workspaceID, issueID, userID).Scan(&commentID); err != nil {+ t.Fatalf("create comment: %v", err)+ }+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority, context, dispatched_at, started_at)+ VALUES ($1, $2, $3, $4, 'dispatched', 0, '{}'::jsonb, now(), NULL)+ RETURNING id`, agentID, runtimeID, issueID, commentID).Scan(&taskID); err != nil {+ t.Fatalf("create dispatched task: %v", err)+ }++ t.Cleanup(func() {+ c := context.Background()+ pool.Exec(c, `DELETE FROM task_token WHERE task_id = $1`, taskID)+ pool.Exec(c, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)+ pool.Exec(c, `DELETE FROM comment WHERE id = $1`, commentID)+ pool.Exec(c, `DELETE FROM issue WHERE id = $1`, issueID)+ pool.Exec(c, `DELETE FROM agent WHERE id = $1`, agentID)+ pool.Exec(c, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)+ pool.Exec(c, `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, workspaceID, userID)+ pool.Exec(c, `DELETE FROM workspace WHERE id = $1`, workspaceID)+ pool.Exec(c, `DELETE FROM "user" WHERE id = $1`, userID)+ })+ return taskID, userID, workspaceID+}diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex a79b0e200c..02b5cf6507 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -3138,6 +3138,81 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtimreturn items, nil}+const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesByRuntimes :many+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id FROM agent_task_queue+WHERE runtime_id = ANY($1::uuid[]) AND status = 'queued'+ORDER BY priority DESC, created_at ASC+`++// Batch variant of ListQueuedClaimCandidatesByRuntime (MUL-4257): returns+// queued claim candidates across every runtime_id in the input set in ONE round+// trip, so a daemon can list candidates for all of its runtimes with a single+// query instead of one per runtime. Ordering matches the singular query+// (priority, then FIFO) so the batch claim loop keeps the same fairness. The+// runtime_id filter is served by the partial index+// idx_agent_task_queue_claim_candidates; the cross-runtime ORDER BY still needs+// a sort step (each runtime's slice is index-ordered, but merging several+// runtimes' rows into one priority/FIFO order is not). The per-machine+// candidate set is small, so this is cheap in practice.+func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runtimeIds []pgtype.UUID) ([]AgentTaskQueue, error) {+ rows, err := q.db.Query(ctx, listQueuedClaimCandidatesByRuntimes, runtimeIds)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AgentTaskQueue{}+ for rows.Next() {+ var i AgentTaskQueue+ if err := rows.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listTasksByIssue = `-- name: ListTasksByIssue :manySELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id FROM agent_task_queueWHERE issue_id = $1@@ -3532,6 +3607,76 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimereturn items, nil}+const promoteDueDeferredTasksForRuntimes = `-- name: PromoteDueDeferredTasksForRuntimes :many+UPDATE agent_task_queue+SET status = 'queued'+WHERE runtime_id = ANY($1::uuid[])+ AND status = 'deferred'+ AND fire_at <= now()+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id+`++// Batch variant of PromoteDueDeferredTasksForRuntime (MUL-4257): promotes all+// due deferred tasks across the runtime set in one UPDATE.+func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, runtimeIds []pgtype.UUID) ([]AgentTaskQueue, error) {+ rows, err := q.db.Query(ctx, promoteDueDeferredTasksForRuntimes, runtimeIds)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AgentTaskQueue{}+ for rows.Next() {+ var i AgentTaskQueue+ if err := rows.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const reclaimStaleDispatchedTaskForRuntime = `-- name: ReclaimStaleDispatchedTaskForRuntime :oneUPDATE agent_task_queueSET dispatched_at = now(),@@ -3607,6 +3752,102 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, argreturn i, err}+const reclaimStaleDispatchedTasksForRuntimes = `-- name: ReclaimStaleDispatchedTasksForRuntimes :many+UPDATE agent_task_queue+SET dispatched_at = now(),+ prepare_lease_expires_at = now() + make_interval(secs => $1::double precision)+WHERE id IN (+ SELECT atq.id FROM agent_task_queue atq+ WHERE atq.runtime_id = ANY($2::uuid[])+ AND atq.status = 'dispatched'+ AND atq.started_at IS NULL+ AND atq.dispatched_at < now() - make_interval(secs => $3::double precision)+ AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())+ ORDER BY atq.priority DESC, atq.dispatched_at ASC+ LIMIT $4::int+ FOR UPDATE SKIP LOCKED+)+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id+`++type ReclaimStaleDispatchedTasksForRuntimesParams struct {+ PrepareLeaseSecs float64 `json:"prepare_lease_secs"`+ RuntimeIds []pgtype.UUID `json:"runtime_ids"`+ ClaimRecoverySecs float64 `json:"claim_recovery_secs"`+ MaxTasks int32 `json:"max_tasks"`+}++// Batch variant of ReclaimStaleDispatchedTaskForRuntime (MUL-4257): re-delivers+// up to @max_tasks tasks across the whole runtime set in one round trip, so a+// machine-level batch claim recovers lost-response dispatches for every runtime+// it hosts without one query per runtime. Same eligibility as the singular+// query (dispatched, never started, past the recovery window, expired/absent+// prepare lease) and the same dispatched_at refresh; only the runtime filter+// (= ANY) and the LIMIT (max_tasks instead of 1) differ.+func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, arg ReclaimStaleDispatchedTasksForRuntimesParams) ([]AgentTaskQueue, error) {+ rows, err := q.db.Query(ctx, reclaimStaleDispatchedTasksForRuntimes,+ arg.PrepareLeaseSecs,+ arg.RuntimeIds,+ arg.ClaimRecoverySecs,+ arg.MaxTasks,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AgentTaskQueue{}+ for rows.Next() {+ var i AgentTaskQueue+ if err := rows.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const recoverOrphanedTasksForRuntime = `-- name: RecoverOrphanedTasksForRuntime :manyUPDATE agent_task_queueSET status = 'failed',diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex 9f2aca9075..4f931c6826 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -460,6 +460,54 @@ func (q *Queries) GetAgentRuntimeForWorkspace(ctx context.Context, arg GetAgentRreturn i, err}+const getAgentRuntimes = `-- name: GetAgentRuntimes :many+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name FROM agent_runtime+WHERE id = ANY($1::uuid[])+`++// Batch variant of GetAgentRuntime (MUL-4257): loads every runtime in the+// input set in one round trip so the machine-level batch claim handler can+// resolve+authorize all of a daemon's runtimes without one point query per+// runtime. Rows are returned only for ids that exist; the caller matches them+// back by id and skips any that are missing.+func (q *Queries) GetAgentRuntimes(ctx context.Context, ids []pgtype.UUID) ([]AgentRuntime, error) {+ rows, err := q.db.Query(ctx, getAgentRuntimes, ids)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AgentRuntime{}+ for rows.Next() {+ var i AgentRuntime+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.DaemonID,+ &i.Name,+ &i.RuntimeMode,+ &i.Provider,+ &i.Status,+ &i.DeviceInfo,+ &i.Metadata,+ &i.LastSeenAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.OwnerID,+ &i.LegacyDaemonID,+ &i.Visibility,+ &i.ProfileID,+ &i.CustomName,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listAgentRuntimes = `-- name: ListAgentRuntimes :manySELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name FROM agent_runtimeWHERE workspace_id = $1diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex d915827c80..e4e141028a 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -494,6 +494,30 @@ WHERE id = ()RETURNING *;+-- name: ReclaimStaleDispatchedTasksForRuntimes :many+-- Batch variant of ReclaimStaleDispatchedTaskForRuntime (MUL-4257): re-delivers+-- up to @max_tasks tasks across the whole runtime set in one round trip, so a+-- machine-level batch claim recovers lost-response dispatches for every runtime+-- it hosts without one query per runtime. Same eligibility as the singular+-- query (dispatched, never started, past the recovery window, expired/absent+-- prepare lease) and the same dispatched_at refresh; only the runtime filter+-- (= ANY) and the LIMIT (max_tasks instead of 1) differ.+UPDATE agent_task_queue+SET dispatched_at = now(),+ prepare_lease_expires_at = now() + make_interval(secs => @prepare_lease_secs::double precision)+WHERE id IN (+ SELECT atq.id FROM agent_task_queue atq+ WHERE atq.runtime_id = ANY(@runtime_ids::uuid[])+ AND atq.status = 'dispatched'+ AND atq.started_at IS NULL+ AND atq.dispatched_at < now() - make_interval(secs => @claim_recovery_secs::double precision)+ AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())+ ORDER BY atq.priority DESC, atq.dispatched_at ASC+ LIMIT @max_tasks::int+ FOR UPDATE SKIP LOCKED+)+RETURNING *;+-- name: ExtendAgentTaskPrepareLease :one-- Keeps a dispatched task protected while the daemon resolves/cache/materializes-- startup inputs before StartTask. Once the daemon stops extending this short@@ -931,6 +955,31 @@ WHERE runtime_id = @runtime_idAND fire_at <= now()RETURNING *;+-- name: ListQueuedClaimCandidatesByRuntimes :many+-- Batch variant of ListQueuedClaimCandidatesByRuntime (MUL-4257): returns+-- queued claim candidates across every runtime_id in the input set in ONE round+-- trip, so a daemon can list candidates for all of its runtimes with a single+-- query instead of one per runtime. Ordering matches the singular query+-- (priority, then FIFO) so the batch claim loop keeps the same fairness. The+-- runtime_id filter is served by the partial index+-- idx_agent_task_queue_claim_candidates; the cross-runtime ORDER BY still needs+-- a sort step (each runtime's slice is index-ordered, but merging several+-- runtimes' rows into one priority/FIFO order is not). The per-machine+-- candidate set is small, so this is cheap in practice.+SELECT * FROM agent_task_queue+WHERE runtime_id = ANY(@runtime_ids::uuid[]) AND status = 'queued'+ORDER BY priority DESC, created_at ASC;++-- name: PromoteDueDeferredTasksForRuntimes :many+-- Batch variant of PromoteDueDeferredTasksForRuntime (MUL-4257): promotes all+-- due deferred tasks across the runtime set in one UPDATE.+UPDATE agent_task_queue+SET status = 'queued'+WHERE runtime_id = ANY(@runtime_ids::uuid[])+ AND status = 'deferred'+ AND fire_at <= now()+RETURNING *;+-- name: CancelDeferredEscalationsForTask :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLdiff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex 123f35d8a1..6daf95f347 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -7,6 +7,15 @@ ORDER BY created_at ASC;SELECT * FROM agent_runtimeWHERE id = $1;+-- name: GetAgentRuntimes :many+-- Batch variant of GetAgentRuntime (MUL-4257): loads every runtime in the+-- input set in one round trip so the machine-level batch claim handler can+-- resolve+authorize all of a daemon's runtimes without one point query per+-- runtime. Rows are returned only for ids that exist; the caller matches them+-- back by id and skips any that are missing.+SELECT * FROM agent_runtime+WHERE id = ANY(@ids::uuid[]);+-- name: LockAgentRuntime :one-- Acquires a row-level exclusive lock on the runtime row. Used at the-- top of the cascade-delete transaction so that:diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 6d90c71ee0..0a2ca5cf40 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -118,6 +118,13 @@ const (EventDaemonRegister = "daemon:register"EventDaemonTaskAvailable = "daemon:task_available"EventDaemonRuntimeProfilesChanged = "daemon:runtime_profiles_changed"+ // Generic daemon→server request/response over the WebSocket control+ // connection (MUL-4257). The daemon sends EventDaemonRPCRequest with a+ // correlation id + method + body; the server replies EventDaemonRPCResponse+ // with the same request id. This is the transport for WS-first claim (with+ // HTTP fallback) and any future daemon→server RPC.+ EventDaemonRPCRequest = "daemon:rpc_request"+ EventDaemonRPCResponse = "daemon:rpc_response"// GitHub integration eventsEventGitHubInstallationCreated = "github_installation:created"diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex 66e89fcdc2..e3dcf043d3 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -5,8 +5,41 @@ import "encoding/json"const (DaemonCapabilitySkillBundlesV1 = "skill-bundles-v1"DaemonCapabilityCoalescedCommentsV1 = "coalesced-comments-v1"+ // DaemonCapabilityRPCV1 advertises that the daemon can carry+ // request/response RPCs over the WebSocket control connection (MUL-4257).+ // Gated so only daemons+servers that both support it route claim over WS;+ // everyone else keeps using the HTTP claim endpoint.+ DaemonCapabilityRPCV1 = "rpc-v1")+// RPCRequestPayload is the generic daemon→server request envelope carried in a+// protocol.Message of type EventDaemonRPCRequest. RequestID correlates the+// response; Method selects the server-side handler (e.g. "tasks.claim"); Body+// is the method-specific request JSON.+type RPCRequestPayload struct {+ RequestID string `json:"request_id"`+ Method string `json:"method"`+ Body json.RawMessage `json:"body,omitempty"`+ // TimeoutMs is the server-side execution budget in milliseconds. The server+ // bounds the handler's context by it so a slow RPC is cancelled (its work+ // rolled back) rather than committing after the daemon has already timed+ // out waiting and fallen back to HTTP (MUL-4257). 0 means no server-side+ // bound (connection-lifetime only).+ TimeoutMs int64 `json:"timeout_ms,omitempty"`+}++// RPCResponsePayload is the server→daemon reply, carried in a+// protocol.Message of type EventDaemonRPCResponse. RequestID echoes the+// request. Status mirrors an HTTP status so the daemon can treat WS and HTTP+// outcomes uniformly. Exactly one of Body / Error is meaningful: Body on+// success (2xx), Error on failure.+type RPCResponsePayload struct {+ RequestID string `json:"request_id"`+ Status int `json:"status"`+ Body json.RawMessage `json:"body,omitempty"`+ Error string `json:"error,omitempty"`+}+// Message is the envelope for all WebSocket messages.type Message struct {Type string `json:"type"`