Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(daemon): resolve skill bundles per-skill with size-scaled timeout (#4505) (#4530)

Bohan Jiangdfa384ffa286
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 8516fab6bf..4c8d782903 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -92,6 +92,13 @@ type Client struct {
token string
client *http.Client
+ // bundleClient downloads skill bundles. Unlike client it carries no fixed
+ // Timeout: bundles can be large and slow on jittery links, so the caller
+ // supplies a per-request, size-scaled deadline via context instead of
+ // being capped by the 30s control-plane timeout that fits heartbeat /
+ // claim but not a multi-megabyte body read. (GitHub #4505)
+ bundleClient *http.Client
+
// Identity headers sent on every request as X-Client-*. Populated by
// SetIdentity(); empty values are simply omitted.
platform string
@@ -102,10 +109,11 @@ type Client struct {
// NewClient creates a new daemon API client.
func NewClient(baseURL string) *Client {
return &Client{
- baseURL: baseURL,
- client: &http.Client{Timeout: 30 * time.Second},
- platform: "daemon",
- os: normalizeGOOS(runtime.GOOS),
+ baseURL: baseURL,
+ client: &http.Client{Timeout: 30 * time.Second},
+ bundleClient: &http.Client{},
+ platform: "daemon",
+ os: normalizeGOOS(runtime.GOOS),
}
}
@@ -164,16 +172,27 @@ func (c *Client) ClaimTask(ctx context.Context, runtimeID string) (*Task, error)
return resp.Task, nil
}
-func (c *Client) ResolveSkillBundles(ctx context.Context, runtimeID, taskID string, refs []SkillRefData) ([]SkillData, error) {
+// 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 within
+// whatever budget ctx leaves. Resolving one skill per request — rather than the
+// agent's whole bundle in one atomic body read — lets each download fit its own
+// deadline and be cached independently, so a slow link makes incremental
+// progress instead of failing the entire set on every dispatch. (GitHub #4505)
+func (c *Client) ResolveSkillBundle(ctx context.Context, runtimeID, taskID string, ref SkillRefData) (SkillData, error) {
var resp struct {
Bundles []SkillData `json:"bundles"`
}
- if err := c.postJSON(ctx, fmt.Sprintf("/api/daemon/runtimes/%s/tasks/%s/skill-bundles/resolve", runtimeID, taskID), map[string]any{
- "skills": refs,
- }, &resp); err != nil {
- return nil, err
+ path := fmt.Sprintf("/api/daemon/runtimes/%s/tasks/%s/skill-bundles/resolve", runtimeID, taskID)
+ if err := c.postJSONViaWithRetry(ctx, c.bundleClient, path, map[string]any{
+ "skills": []SkillRefData{ref},
+ }, &resp, skillBundleResolveRetrySchedule); err != nil {
+ return SkillData{}, err
}
- return resp.Bundles, nil
+ if len(resp.Bundles) != 1 {
+ return SkillData{}, fmt.Errorf("resolve skill bundle: expected 1 bundle, got %d", len(resp.Bundles))
+ }
+ return resp.Bundles[0], nil
}
func (c *Client) ExtendTaskPrepareLease(ctx context.Context, runtimeID, taskID string) error {
@@ -531,6 +550,16 @@ var defaultTerminalRetrySchedule = []time.Duration{
64 * time.Second,
}
+// skillBundleResolveRetrySchedule rides out brief transport blips on a single
+// bundle download. Kept short on purpose: the real budget is the size-scaled
+// context deadline the daemon sets per skill, and a skill that still fails is
+// retried on the next dispatch once its siblings are cached. N entries → N+1
+// attempts. (GitHub #4505)
+var skillBundleResolveRetrySchedule = []time.Duration{
+ 500 * time.Millisecond,
+ 2 * time.Second,
+}
+
// retrySleep is the sleep used between retry attempts. Pulled into a package
// variable so tests can swap in an instant sleep without rewriting the
// caller's schedule.
@@ -589,6 +618,13 @@ func isTransientError(err error) bool {
// idempotent success (see service/task.go), so a duplicate replay from a
// retry is safe even if the server's prior response was lost in transit.
func (c *Client) postJSONWithRetry(ctx context.Context, path string, reqBody any, respBody any, schedule []time.Duration) error {
+ return c.postJSONViaWithRetry(ctx, c.client, path, reqBody, respBody, schedule)
+}
+
+// postJSONViaWithRetry is postJSONWithRetry over an explicit http.Client, so
+// large-body endpoints can run on bundleClient (deadline from ctx) while the
+// control-plane keeps its fixed 30s client.
+func (c *Client) postJSONViaWithRetry(ctx context.Context, httpClient *http.Client, path string, reqBody any, respBody any, schedule []time.Duration) error {
var lastErr error
for attempt := 0; ; attempt++ {
if err := ctx.Err(); err != nil {
@@ -597,7 +633,7 @@ func (c *Client) postJSONWithRetry(ctx context.Context, path string, reqBody any
}
return err
}
- err := c.postJSON(ctx, path, reqBody, respBody)
+ err := c.postJSONVia(ctx, httpClient, path, reqBody, respBody)
if err == nil {
return nil
}
@@ -615,6 +651,13 @@ func (c *Client) postJSONWithRetry(ctx context.Context, path string, reqBody any
}
func (c *Client) postJSON(ctx context.Context, path string, reqBody any, respBody any) error {
+ return c.postJSONVia(ctx, c.client, path, reqBody, respBody)
+}
+
+// postJSONVia is postJSON over an explicit http.Client. Callers pick the client
+// to control the timeout regime: c.client (fixed 30s) for control-plane calls,
+// c.bundleClient (deadline from ctx) for large skill-bundle downloads.
+func (c *Client) postJSONVia(ctx context.Context, httpClient *http.Client, path string, reqBody any, respBody any) error {
var body io.Reader
if reqBody != nil {
data, err := json.Marshal(reqBody)
@@ -634,7 +677,7 @@ func (c *Client) postJSON(ctx context.Context, path string, reqBody any, respBod
}
c.setIdentityHeaders(req)
- resp, err := c.client.Do(req)
+ resp, err := httpClient.Do(req)
if err != nil {
return err
}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index a66b62053c..1f5fb68c4c 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -3214,23 +3214,20 @@ func (d *Daemon) ensureTaskSkillBundles(ctx context.Context, task *Task) error {
}
}
- if len(misses) > 0 {
- bundles, err := d.client.ResolveSkillBundles(ctx, task.RuntimeID, task.ID, misses)
+ // Resolve each missing bundle in its own request, caching it the moment it
+ // arrives. The download is the slow part on jittery links, so fetching the
+ // whole set in one atomic body read meant a single timeout discarded all
+ // progress and the cache never converged — every dispatch re-downloaded
+ // everything and timed out again. Per-skill, each download fits its own
+ // size-scaled deadline and is persisted independently, so even a dispatch
+ // that ultimately fails leaves the skills it did fetch cached for the next
+ // one. (GitHub #4505 / MUL-3650)
+ for _, ref := range misses {
+ bundle, err := d.resolveSkillBundle(ctx, task, ref)
if err != nil {
return fmt.Errorf("resolve skill bundles: %w", err)
}
- for _, bundle := range bundles {
- ref := skillRefFromBundle(bundle)
- if !validateSkillBundle(ref, bundle) {
- return fmt.Errorf("resolve skill bundle returned invalid bundle: skill_id=%s source=%s hash=%s", bundle.ID, bundle.Source, bundle.Hash)
- }
- if err := d.skillCache.WithRefLock(task.WorkspaceID, ref, func() error {
- return d.skillCache.Store(task.WorkspaceID, bundle)
- }); err != nil {
- return fmt.Errorf("store skill bundle cache: %w", err)
- }
- resolved[skillRefKey(bundle.Source, bundle.ID)] = bundle
- }
+ resolved[skillRefKey(bundle.Source, bundle.ID)] = bundle
}
skills := make([]SkillData, 0, len(task.Agent.SkillRefs))
@@ -3245,6 +3242,71 @@ func (d *Daemon) ensureTaskSkillBundles(ctx context.Context, task *Task) error {
return nil
}
+// resolveSkillBundle downloads one skill bundle and writes it to the on-disk
+// cache before returning. The request runs under its own deadline, scaled to
+// the bundle's declared size rather than the daemon's fixed 30s control-plane
+// timeout, so a large bundle on a slow link is given room to finish instead of
+// being cut off mid-body. Caching on success is what lets the resolve converge
+// across dispatches. (GitHub #4505 / MUL-3650)
+func (d *Daemon) resolveSkillBundle(ctx context.Context, task *Task, ref SkillRefData) (SkillData, error) {
+ reqCtx, cancel := context.WithTimeout(ctx, skillBundleResolveTimeout(ref.SizeBytes))
+ defer cancel()
+
+ bundle, err := d.client.ResolveSkillBundle(reqCtx, task.RuntimeID, task.ID, ref)
+ if err != nil {
+ return SkillData{}, err
+ }
+ // The resolve endpoint serves the agent's *current* bundle and hash, which
+ // may differ from the claim-time ref when the skill was edited between
+ // claim and prepare (see ResolveTaskSkillBundles). So confirm only that the
+ // server returned the skill we asked for (source/id), then validate the
+ // bundle for self-consistency against a ref derived from itself — pinning
+ // it to the possibly-stale requested hash would reject a legitimate update.
+ if bundle.Source != ref.Source || bundle.ID != ref.ID {
+ return SkillData{}, fmt.Errorf("resolve skill bundle returned wrong skill: requested source=%s id=%s, got source=%s id=%s", ref.Source, ref.ID, bundle.Source, bundle.ID)
+ }
+ bundleRef := skillRefFromBundle(bundle)
+ if !validateSkillBundle(bundleRef, bundle) {
+ return SkillData{}, fmt.Errorf("resolve skill bundle returned invalid bundle: skill_id=%s source=%s hash=%s", bundle.ID, bundle.Source, bundle.Hash)
+ }
+ if err := d.skillCache.WithRefLock(task.WorkspaceID, bundleRef, func() error {
+ return d.skillCache.Store(task.WorkspaceID, bundle)
+ }); err != nil {
+ return SkillData{}, fmt.Errorf("store skill bundle cache: %w", err)
+ }
+ return bundle, nil
+}
+
+const (
+ // skillBundleResolveMinTimeout floors the per-skill resolve deadline so a
+ // tiny bundle still tolerates connection setup and round-trip latency.
+ skillBundleResolveMinTimeout = 30 * time.Second
+ // skillBundleResolveMaxTimeout caps it so a wedged download cannot pin a
+ // task in prepare indefinitely.
+ skillBundleResolveMaxTimeout = 5 * time.Minute
+ // skillBundleResolveMinThroughput is the pessimistic floor throughput
+ // (bytes/sec) used to scale the deadline to bundle size — deliberately low
+ // to cover slow, jittery links rather than ideal bandwidth.
+ skillBundleResolveMinThroughput = 50 * 1024
+)
+
+// skillBundleResolveTimeout returns the deadline budget for downloading a
+// bundle of the given size: at least skillBundleResolveMinTimeout, scaled up at
+// skillBundleResolveMinThroughput, and capped at skillBundleResolveMaxTimeout.
+func skillBundleResolveTimeout(sizeBytes int64) time.Duration {
+ if sizeBytes <= 0 {
+ return skillBundleResolveMinTimeout
+ }
+ scaled := time.Duration(sizeBytes/skillBundleResolveMinThroughput) * time.Second
+ if scaled < skillBundleResolveMinTimeout {
+ return skillBundleResolveMinTimeout
+ }
+ if scaled > skillBundleResolveMaxTimeout {
+ return skillBundleResolveMaxTimeout
+ }
+ return scaled
+}
+
func (d *Daemon) startTaskPrepareLeaseExtender(ctx context.Context, task Task, taskLog *slog.Logger) func() {
leaseCtx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
diff --git a/server/internal/daemon/skill_bundle_resolve_test.go b/server/internal/daemon/skill_bundle_resolve_test.go
new file mode 100644
index 0000000000..5fbc85ae02
--- /dev/null
+++ b/server/internal/daemon/skill_bundle_resolve_test.go
@@ -0,0 +1,229 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+ "time"
+)
+
+func TestSkillBundleResolveTimeout(t *testing.T) {
+ cases := []struct {
+ name string
+ size int64
+ want time.Duration
+ }{
+ {"zero size floors to min", 0, skillBundleResolveMinTimeout},
+ {"negative size floors to min", -5, skillBundleResolveMinTimeout},
+ {"tiny bundle floors to min", 1024, skillBundleResolveMinTimeout},
+ {"scales with size above the floor", 2 * 1024 * 1024, 40 * time.Second},
+ {"huge bundle caps at max", 100 * 1024 * 1024, skillBundleResolveMaxTimeout},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := skillBundleResolveTimeout(tc.size); got != tc.want {
+ t.Fatalf("skillBundleResolveTimeout(%d) = %s, want %s", tc.size, got, tc.want)
+ }
+ })
+ }
+}
+
+// makeResolvableSkillBundleWith builds a self-consistent bundle from explicit
+// content, so validateSkillBundle accepts it and skillRefFromBundle yields the
+// ref the agent would carry. Varying content changes the hash, which lets tests
+// model a skill edited between claim and prepare.
+func makeResolvableSkillBundleWith(id, content, fileContent string) SkillData {
+ b := SkillData{
+ ID: id,
+ Source: "workspace",
+ Name: id,
+ Content: content,
+ Files: []SkillFileData{{Path: "rules.md", Content: fileContent}},
+ }
+ ref := skillRefFromBundle(b)
+ b.Hash = ref.Hash
+ b.SizeBytes = ref.SizeBytes
+ b.Files[0].SHA256 = ref.Files[0].SHA256
+ b.Files[0].SizeBytes = ref.Files[0].SizeBytes
+ return b
+}
+
+// makeResolvableSkillBundle is makeResolvableSkillBundleWith with default
+// content derived from the id.
+func makeResolvableSkillBundle(id string) SkillData {
+ return makeResolvableSkillBundleWith(id, "content-of-"+id, "rules-"+id)
+}
+
+// TestEnsureTaskSkillBundles_CachesEachSuccessAcrossDispatches is the core
+// regression for GitHub #4505: when one skill's download fails, the skills that
+// did resolve must still be cached, and the next dispatch must re-fetch only
+// the still-missing one — never the whole bundle. The pre-fix code resolved the
+// whole set in one atomic request and cached nothing on failure, so a large
+// bundle that could not finish in the fixed 30s timeout was re-downloaded in
+// full on every dispatch and never converged.
+func TestEnsureTaskSkillBundles_CachesEachSuccessAcrossDispatches(t *testing.T) {
+ defer noSleepRetry(t)()
+
+ var mu sync.Mutex
+ requested := map[string]int{}
+ failIDs := map[string]bool{}
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ Skills []SkillRefData `json:"skills"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ t.Errorf("decode request: %v", err)
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ // Each request must carry exactly one skill — the fix resolves
+ // per-skill so each download fits its own deadline and caches alone.
+ if len(req.Skills) != 1 {
+ t.Errorf("expected exactly 1 skill per request, got %d", len(req.Skills))
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ id := req.Skills[0].ID
+ mu.Lock()
+ requested[id]++
+ fail := failIDs[id]
+ mu.Unlock()
+ if fail {
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]any{"bundles": []SkillData{makeResolvableSkillBundle(id)}})
+ }))
+ defer srv.Close()
+
+ ids := []string{"skill-1", "skill-2", "skill-3"}
+ refs := make([]SkillRefData, len(ids))
+ for i, id := range ids {
+ refs[i] = skillRefFromBundle(makeResolvableSkillBundle(id))
+ }
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ skillCache: NewSkillBundleCache(t.TempDir()),
+ }
+ task := &Task{
+ ID: "task-1",
+ RuntimeID: "rt-1",
+ WorkspaceID: "ws-1",
+ Agent: &AgentData{ID: "agent-1", SkillRefs: refs},
+ }
+
+ // Dispatch 1: the last skill fails. The first two must still be cached.
+ mu.Lock()
+ failIDs["skill-3"] = true
+ mu.Unlock()
+
+ if err := d.ensureTaskSkillBundles(context.Background(), task); err == nil {
+ t.Fatal("dispatch 1: expected error because skill-3 fails, got nil")
+ }
+ if _, ok := d.skillCache.Load("ws-1", refs[0]); !ok {
+ t.Error("dispatch 1: skill-1 should be cached despite skill-3 failing")
+ }
+ if _, ok := d.skillCache.Load("ws-1", refs[1]); !ok {
+ t.Error("dispatch 1: skill-2 should be cached despite skill-3 failing")
+ }
+ if _, ok := d.skillCache.Load("ws-1", refs[2]); ok {
+ t.Error("dispatch 1: skill-3 must not be cached after a failed download")
+ }
+ // A 500 is transient, so skill-3 is retried over the full schedule.
+ mu.Lock()
+ wantSkill3 := len(skillBundleResolveRetrySchedule) + 1
+ if got := requested["skill-3"]; got != wantSkill3 {
+ t.Errorf("dispatch 1: skill-3 attempts = %d, want %d (initial + retries)", got, wantSkill3)
+ }
+ requested = map[string]int{}
+ failIDs = map[string]bool{}
+ mu.Unlock()
+
+ // Dispatch 2: everything succeeds. Only the previously-missing skill-3 may
+ // be re-fetched; the two cached skills must not hit the network again.
+ if err := d.ensureTaskSkillBundles(context.Background(), task); err != nil {
+ t.Fatalf("dispatch 2: expected success, got %v", err)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if got := requested["skill-1"]; got != 0 {
+ t.Errorf("dispatch 2: skill-1 was re-fetched %d times, want 0 (served from cache)", got)
+ }
+ if got := requested["skill-2"]; got != 0 {
+ t.Errorf("dispatch 2: skill-2 was re-fetched %d times, want 0 (served from cache)", got)
+ }
+ if got := requested["skill-3"]; got != 1 {
+ t.Errorf("dispatch 2: skill-3 fetched %d times, want exactly 1", got)
+ }
+ if len(task.Agent.Skills) != len(ids) {
+ t.Fatalf("dispatch 2: resolved %d skills, want %d", len(task.Agent.Skills), len(ids))
+ }
+ for i, id := range ids {
+ if task.Agent.Skills[i].ID != id {
+ t.Errorf("dispatch 2: skill[%d].ID = %q, want %q", i, task.Agent.Skills[i].ID, id)
+ }
+ }
+}
+
+// TestEnsureTaskSkillBundles_AcceptsServerSideSkillUpdate guards the resolve
+// endpoint's contract: when a skill is edited between claim and prepare, the
+// server returns the *current* bundle and hash even though the daemon asked
+// with the stale claim-time hash (see ResolveTaskSkillBundles). The daemon must
+// accept it — validating the bundle for self-consistency, not against the
+// requested hash — and cache it under its new hash. Pinning to the requested
+// hash would reject a legitimate update and fail the task.
+func TestEnsureTaskSkillBundles_AcceptsServerSideSkillUpdate(t *testing.T) {
+ defer noSleepRetry(t)()
+
+ current := makeResolvableSkillBundleWith("skill-1", "v2-content", "v2-rules")
+ currentRef := skillRefFromBundle(current)
+ staleRef := skillRefFromBundle(makeResolvableSkillBundleWith("skill-1", "v1-content", "v1-rules"))
+ if staleRef.Hash == currentRef.Hash {
+ t.Fatal("test setup: stale and current hash must differ")
+ }
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ Skills []SkillRefData `json:"skills"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ t.Errorf("decode request: %v", err)
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ if len(req.Skills) != 1 || req.Skills[0].Hash != staleRef.Hash {
+ t.Errorf("expected the stale ref to be sent, got %+v", req.Skills)
+ }
+ // Server ignores the requested (stale) hash and returns the current bundle.
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]any{"bundles": []SkillData{current}})
+ }))
+ defer srv.Close()
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ skillCache: NewSkillBundleCache(t.TempDir()),
+ }
+ task := &Task{
+ ID: "task-1",
+ RuntimeID: "rt-1",
+ WorkspaceID: "ws-1",
+ Agent: &AgentData{ID: "agent-1", SkillRefs: []SkillRefData{staleRef}},
+ }
+
+ if err := d.ensureTaskSkillBundles(context.Background(), task); err != nil {
+ t.Fatalf("expected success when server returns an updated bundle, got %v", err)
+ }
+ if len(task.Agent.Skills) != 1 || task.Agent.Skills[0].Hash != currentRef.Hash {
+ t.Fatalf("expected the resolved skill to be the updated bundle (hash %s), got %+v", currentRef.Hash, task.Agent.Skills)
+ }
+ if _, ok := d.skillCache.Load("ws-1", currentRef); !ok {
+ t.Error("updated bundle should be cached under its own (new) hash")
+ }
+}