Skip to content

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

Go

MUL-6530: report bytes transferred when a skill bundle download fails (#7386) (#7494)

Bohan Jiang1ea6d18f6b79
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index ba835f840c..52d77c1c9c 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -322,6 +322,60 @@ func (c *Client) claimTasksLegacy(ctx context.Context, runtimeIDs []string, maxT
return out, nil
}
+// TransferStats records successful HTTP response-body bytes read by a logical
+// call. For a skill-bundle download it separates "the link never produced a
+// successful response" from "a 2xx body arrived but did not finish" — a
+// distinction the failure text could not previously express, so a connectivity
+// fault read as a broken skill and sent reporters chasing the wrong thing
+// (GitHub #7386).
+//
+// Across retries the fields keep the high-water mark rather than the last
+// attempt: the question they answer is "did this link ever get anywhere", and
+// one attempt that reached the body says more than a later one that did not.
+// The zero value is usable, and every method is nil-safe so callers that do
+// not want the accounting can pass nil.
+type TransferStats struct {
+ // ResponseStarted reports whether 2xx response headers ever arrived. Error
+ // response bodies are deliberately excluded: their bytes describe a server
+ // business error, not progress downloading a skill bundle.
+ ResponseStarted bool
+ // BytesRead is the most response-body bytes any single attempt read.
+ BytesRead int64
+}
+
+func (t *TransferStats) observeResponseStarted() {
+ if t != nil {
+ t.ResponseStarted = true
+ }
+}
+
+// wrap returns r instrumented to feed this attempt's byte count back into t.
+func (t *TransferStats) wrap(r io.Reader) io.Reader {
+ if t == nil {
+ return r
+ }
+ return &countingReader{inner: r, stats: t}
+}
+
+// countingReader tallies one attempt and raises the parent high-water mark as
+// it goes, so a failure mid-body still reports how far that attempt got.
+type countingReader struct {
+ inner io.Reader
+ stats *TransferStats
+ attempt int64
+}
+
+func (c *countingReader) Read(p []byte) (int, error) {
+ n, err := c.inner.Read(p)
+ if n > 0 {
+ c.attempt += int64(n)
+ if c.attempt > c.stats.BytesRead {
+ c.stats.BytesRead = c.attempt
+ }
+ }
+ return n, err
+}
+
// 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
@@ -329,20 +383,21 @@ func (c *Client) claimTasksLegacy(ctx context.Context, runtimeIDs []string, maxT
// 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) {
+func (c *Client) ResolveSkillBundle(ctx context.Context, runtimeID, taskID string, ref SkillRefData) (SkillData, TransferStats, error) {
var resp struct {
Bundles []SkillData `json:"bundles"`
}
+ var stats TransferStats
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
+ }, &resp, skillBundleResolveRetrySchedule, &stats); err != nil {
+ return SkillData{}, stats, err
}
if len(resp.Bundles) != 1 {
- return SkillData{}, fmt.Errorf("resolve skill bundle: expected 1 bundle, got %d", len(resp.Bundles))
+ return SkillData{}, stats, fmt.Errorf("resolve skill bundle: expected 1 bundle, got %d", len(resp.Bundles))
}
- return resp.Bundles[0], nil
+ return resp.Bundles[0], stats, nil
}
func (c *Client) ExtendTaskPrepareLease(ctx context.Context, runtimeID, taskID string) error {
@@ -1007,13 +1062,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)
+ return c.postJSONViaWithRetry(ctx, c.client, path, reqBody, respBody, schedule, nil)
}
// 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 {
+func (c *Client) postJSONViaWithRetry(ctx context.Context, httpClient *http.Client, path string, reqBody any, respBody any, schedule []time.Duration, stats *TransferStats) error {
var lastErr error
for attempt := 0; ; attempt++ {
if err := ctx.Err(); err != nil {
@@ -1022,7 +1077,7 @@ func (c *Client) postJSONViaWithRetry(ctx context.Context, httpClient *http.Clie
}
return err
}
- err := c.postJSONVia(ctx, httpClient, path, reqBody, respBody)
+ err := c.postJSONViaObserved(ctx, httpClient, path, reqBody, respBody, stats)
if err == nil {
return nil
}
@@ -1047,6 +1102,14 @@ func (c *Client) postJSON(ctx context.Context, path string, reqBody any, respBod
// 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 {
+ return c.postJSONViaObserved(ctx, httpClient, path, reqBody, respBody, nil)
+}
+
+// postJSONViaObserved is postJSONVia that additionally records what the attempt
+// moved into stats (nil to skip). Callers use it to tell "the link never
+// produced a response" apart from "the body arrived too slowly to finish" —
+// see TransferStats.
+func (c *Client) postJSONViaObserved(ctx context.Context, httpClient *http.Client, path string, reqBody any, respBody any, stats *TransferStats) error {
var body io.Reader
if reqBody != nil {
data, err := json.Marshal(reqBody)
@@ -1071,16 +1134,17 @@ func (c *Client) postJSONVia(ctx context.Context, httpClient *http.Client, path
return err
}
defer resp.Body.Close()
-
- if resp.StatusCode >= 400 {
+ if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return &requestError{Method: http.MethodPost, Path: path, StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(data))}
}
+ stats.observeResponseStarted()
+ respReader := stats.wrap(resp.Body)
if respBody == nil {
- io.Copy(io.Discard, resp.Body)
+ io.Copy(io.Discard, respReader)
return nil
}
- return json.NewDecoder(resp.Body).Decode(respBody)
+ return json.NewDecoder(respReader).Decode(respBody)
}
func (c *Client) getJSON(ctx context.Context, path string, respBody any) error {
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 2cd125222b..fbb6b44802 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -8,6 +8,7 @@ import (
"hash/fnv"
"log/slog"
"math/rand"
+ "net"
"net/http"
"os"
"os/exec"
@@ -6000,17 +6001,19 @@ func (d *Daemon) ensureTaskSkillBundles(ctx context.Context, task *Task) error {
// one. (GitHub #4505 / MUL-3650)
for _, ref := range misses {
started := time.Now()
- bundle, err := d.resolveSkillBundle(ctx, task, ref)
+ bundle, stats, err := d.resolveSkillBundle(ctx, task, ref)
if err != nil {
- // Name the skill, its declared size, and how long we actually
- // waited. The bare "resolve skill bundles: context deadline
- // exceeded" this replaced was indistinguishable from a generic
- // network fault, and cost a community thread three hours of
- // guesswork (MUL-5370): size + elapsed separate "this bundle is
- // too big for the link" from "the link is dead".
- return fmt.Errorf("%w: skill %q (id=%s, %d bytes) after %s: %w",
- errSkillBundleUnavailable, ref.Name, ref.ID, ref.SizeBytes,
- time.Since(started).Round(time.Millisecond), err)
+ if isSkillBundleTransferFailure(err) {
+ // Only transport failures and incomplete 2xx bodies get the
+ // network diagnosis. HTTP error responses and invalid complete
+ // payloads retain their server semantics instead of being
+ // relabelled as connectivity problems (GitHub #7386).
+ return fmt.Errorf("%w: %s: %w",
+ errSkillBundleUnavailable,
+ describeSkillBundleFailure(ref, stats, time.Since(started)),
+ err)
+ }
+ return fmt.Errorf("%w: %w", errSkillBundleUnavailable, err)
}
resolved[skillRefKey(bundle.Source, bundle.ID)] = bundle
}
@@ -6033,13 +6036,13 @@ func (d *Daemon) ensureTaskSkillBundles(ctx context.Context, task *Task) error {
// 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) {
+func (d *Daemon) resolveSkillBundle(ctx context.Context, task *Task, ref SkillRefData) (SkillData, TransferStats, error) {
reqCtx, cancel := context.WithTimeout(ctx, skillBundleResolveTimeout(ref.SizeBytes))
defer cancel()
- bundle, err := d.client.ResolveSkillBundle(reqCtx, task.RuntimeID, task.ID, ref)
+ bundle, stats, err := d.client.ResolveSkillBundle(reqCtx, task.RuntimeID, task.ID, ref)
if err != nil {
- return SkillData{}, err
+ return SkillData{}, stats, 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
@@ -6048,7 +6051,7 @@ func (d *Daemon) resolveSkillBundle(ctx context.Context, task *Task, ref SkillRe
// 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)
+ return SkillData{}, stats, 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)
validationRef := bundleRef
@@ -6056,7 +6059,7 @@ func (d *Daemon) resolveSkillBundle(ctx context.Context, task *Task, ref SkillRe
validationRef = ref
}
if !validateSkillBundle(validationRef, bundle) {
- return SkillData{}, fmt.Errorf("resolve skill bundle returned invalid bundle: skill_id=%s source=%s hash=%s", bundle.ID, bundle.Source, bundle.Hash)
+ return SkillData{}, stats, 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, validationRef, func() error {
return d.skillCache.Store(task.WorkspaceID, bundle)
@@ -6071,7 +6074,87 @@ func (d *Daemon) resolveSkillBundle(ctx context.Context, task *Task, ref SkillRe
)
}
}
- return bundle, nil
+ return bundle, stats, nil
+}
+
+// isSkillBundleTransferFailure identifies errors for which byte-level network
+// diagnostics are meaningful. A requestError is an explicit server response;
+// malformed but complete JSON and bundle-validation errors are server payload
+// problems. Neither should be presented as a slow or dead network link. In
+// particular, json.Decoder can synthesize io.ErrUnexpectedEOF after its source
+// ended with a clean EOF, so that decoder error alone is not transport proof.
+func isSkillBundleTransferFailure(err error) bool {
+ var reqErr *requestError
+ if errors.As(err, &reqErr) {
+ return false
+ }
+ if errors.Is(err, context.DeadlineExceeded) {
+ return true
+ }
+ var netErr net.Error
+ return errors.As(err, &netErr)
+}
+
+// describeSkillBundleFailure renders the diagnostic half of a failed bundle
+// download: what was being fetched, how many HTTP response-body bytes arrived,
+// the separately declared decoded content size, and whether this host has a
+// proxy at all.
+//
+// The three facts answer the three wrong turns the old text invited. "network
+// error downloading skill X" instead of "skill X unavailable" stops the reader
+// blaming the skill. The response byte count distinguishes a dead link from a
+// partial response without pretending JSON wire bytes and decoded skill-content
+// bytes form one progress ratio. The proxy note catches the case behind GitHub
+// #7386, where a daemon that inherited no proxy on a cross-border link never got
+// a byte through while the same host succeeded through a local proxy.
+func describeSkillBundleFailure(ref SkillRefData, stats TransferStats, elapsed time.Duration) string {
+ elapsed = elapsed.Round(time.Millisecond)
+ var transfer string
+ switch {
+ case !stats.ResponseStarted:
+ transfer = fmt.Sprintf("no successful response from server after %s overall", elapsed)
+ case stats.BytesRead == 0:
+ transfer = fmt.Sprintf("a successful response started but delivered no body bytes before failing after %s overall", elapsed)
+ default:
+ // BytesRead is a single-attempt high-water mark, while elapsed covers
+ // the logical call including retries and backoff. State both scopes
+ // rather than deriving a rate from mismatched measurements.
+ transfer = fmt.Sprintf("received up to %s of response body data in one attempt; failed after %s overall",
+ formatBytes(stats.BytesRead), elapsed)
+ }
+ return fmt.Sprintf("network error downloading skill %q (id=%s): %s; declared skill content size %s; %s; the skill content is not at fault",
+ ref.Name, ref.ID, transfer, formatBytes(ref.SizeBytes), proxyEnvSummary())
+}
+
+// proxyEnvSummary reports whether the daemon inherited any proxy setting. It
+// names the variable but never its value: proxy URLs routinely embed
+// credentials, and this string lands in task failure text the whole workspace
+// can read.
+//
+// Go's transport only consults these variables — it does not read the Windows
+// system proxy — and it reads them at process start, so a daemon that was
+// already running when they were set still shows none (GitHub #7386).
+func proxyEnvSummary() string {
+ for _, key := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"} {
+ if strings.TrimSpace(os.Getenv(key)) != "" {
+ return fmt.Sprintf("proxy configured (%s)", key)
+ }
+ }
+ return "no proxy configured (HTTPS_PROXY unset)"
+}
+
+// formatBytes renders a byte count for humans reading a failure message.
+func formatBytes(n int64) string {
+ switch {
+ case n < 0:
+ return "unknown size"
+ case n < 1024:
+ return fmt.Sprintf("%d B", n)
+ case n < 1024*1024:
+ return fmt.Sprintf("%.0f KB", float64(n)/1024)
+ default:
+ return fmt.Sprintf("%.2f MB", float64(n)/(1024*1024))
+ }
}
const (
diff --git a/server/internal/daemon/skill_bundle_resolve_test.go b/server/internal/daemon/skill_bundle_resolve_test.go
index bf7db94cd5..ff6ad50aba 100644
--- a/server/internal/daemon/skill_bundle_resolve_test.go
+++ b/server/internal/daemon/skill_bundle_resolve_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "io"
"io/fs"
"net/http"
"net/http/httptest"
@@ -357,3 +358,281 @@ func TestEnsureTaskSkillBundles_DeadlineIsLabelledStructurally(t *testing.T) {
t.Errorf("taskRunFailureReason = %q, want %q (retryable platform-side reason)", got, want)
}
}
+
+// clearProxyEnv unsets every variable proxyEnvSummary consults, so a developer
+// machine that happens to run behind a proxy does not flip these assertions.
+func clearProxyEnv(t *testing.T) {
+ t.Helper()
+ for _, key := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"} {
+ t.Setenv(key, "")
+ }
+}
+
+// TestDescribeSkillBundleFailure is the GitHub #7386 regression. The reporter
+// spent a day re-importing xlsx because the message named the skill and said
+// nothing about the wire; the whole point of this text is that a reader can
+// tell, without a packet capture, whether the link was dead or merely slow.
+func TestDescribeSkillBundleFailure(t *testing.T) {
+ clearProxyEnv(t)
+ ref := SkillRefData{Name: "xlsx", ID: "c5034ed6", SizeBytes: 1101426}
+
+ t.Run("dead link reports no response and separates declared content size", func(t *testing.T) {
+ got := describeSkillBundleFailure(ref, TransferStats{}, 30*time.Second)
+ for _, want := range []string{
+ "network error downloading skill \"xlsx\"",
+ "no successful response from server after 30s overall",
+ "declared skill content size 1.05 MB",
+ "no proxy configured",
+ "the skill content is not at fault",
+ } {
+ if !strings.Contains(got, want) {
+ t.Errorf("missing %q in:\n%s", want, got)
+ }
+ }
+ })
+
+ t.Run("partial response reports response bytes without an inferred rate", func(t *testing.T) {
+ stats := TransferStats{ResponseStarted: true, BytesRead: 552960}
+ got := describeSkillBundleFailure(ref, stats, 30*time.Second)
+ for _, want := range []string{
+ "received up to 540 KB of response body data in one attempt",
+ "failed after 30s overall",
+ "declared skill content size 1.05 MB",
+ } {
+ if !strings.Contains(got, want) {
+ t.Errorf("missing %q in:\n%s", want, got)
+ }
+ }
+ if strings.Contains(got, "KB/s") || strings.Contains(got, "MB/s") {
+ t.Errorf("cross-retry elapsed time must not be presented as a transfer rate:\n%s", got)
+ }
+ if strings.Contains(got, "no response from server") {
+ t.Errorf("a link that delivered bytes must not read as no-response:\n%s", got)
+ }
+ })
+
+ t.Run("wire bytes may exceed declared content size", func(t *testing.T) {
+ stats := TransferStats{ResponseStarted: true, BytesRead: 1388598}
+ got := describeSkillBundleFailure(ref, stats, 30*time.Second)
+ for _, want := range []string{
+ "received up to 1.32 MB of response body data",
+ "declared skill content size 1.05 MB",
+ } {
+ if !strings.Contains(got, want) {
+ t.Errorf("missing %q in:\n%s", want, got)
+ }
+ }
+ if strings.Contains(got, "1.32 MB of 1.05 MB") {
+ t.Errorf("wire and decoded content sizes must not be shown as one progress ratio:\n%s", got)
+ }
+ })
+
+ t.Run("configured proxy is named but never valued", func(t *testing.T) {
+ clearProxyEnv(t)
+ t.Setenv("HTTPS_PROXY", "http://user:[email protected]:7890")
+ got := describeSkillBundleFailure(ref, TransferStats{}, time.Second)
+ if !strings.Contains(got, "proxy configured (HTTPS_PROXY)") {
+ t.Errorf("expected the proxy to be reported as configured:\n%s", got)
+ }
+ // Proxy URLs routinely carry credentials and this string is shown to
+ // the whole workspace.
+ if strings.Contains(got, "secret") || strings.Contains(got, "7890") {
+ t.Errorf("proxy value must never be echoed into failure text:\n%s", got)
+ }
+ })
+}
+
+func TestFormatBytes(t *testing.T) {
+ cases := []struct {
+ n int64
+ want string
+ }{
+ {0, "0 B"},
+ {512, "512 B"},
+ {1024, "1 KB"},
+ {552960, "540 KB"},
+ {1101426, "1.05 MB"},
+ }
+ for _, tc := range cases {
+ if got := formatBytes(tc.n); got != tc.want {
+ t.Errorf("formatBytes(%d) = %q, want %q", tc.n, got, tc.want)
+ }
+ }
+}
+
+func TestEnsureTaskSkillBundles_ServerErrorsKeepServerSemantics(t *testing.T) {
+ defer noSleepRetry(t)()
+
+ for _, status := range []int{
+ http.StatusMultipleChoices,
+ http.StatusUnauthorized,
+ http.StatusNotFound,
+ http.StatusConflict,
+ http.StatusInternalServerError,
+ } {
+ t.Run(http.StatusText(status), func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _, _ = io.WriteString(w, `{"error":"task is not preparing"}`)
+ }))
+ defer srv.Close()
+
+ ref := skillRefFromBundle(makeResolvableSkillBundle("frontend-review"))
+ 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{ref}},
+ }
+
+ err := d.ensureTaskSkillBundles(context.Background(), task)
+ if err == nil {
+ t.Fatal("expected server error")
+ }
+ if !errors.Is(err, errSkillBundleUnavailable) {
+ t.Errorf("sentinel must survive, got %v", err)
+ }
+ var reqErr *requestError
+ if !errors.As(err, &reqErr) || reqErr.StatusCode != status {
+ t.Errorf("requestError status = %v, want %d; err=%v", reqErr, status, err)
+ }
+ if got := err.Error(); strings.Contains(got, "network error") || strings.Contains(got, "skill content is not at fault") {
+ t.Errorf("HTTP %d must keep server semantics instead of being relabelled as a network failure:\n%s", status, got)
+ }
+ })
+ }
+}
+
+func TestResolveSkillBundle_ServerErrorBodyIsNotCountedAsBundleData(t *testing.T) {
+ defer noSleepRetry(t)()
+
+ for _, status := range []int{http.StatusMultipleChoices, http.StatusConflict, http.StatusInternalServerError} {
+ t.Run(http.StatusText(status), func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(status)
+ _, _ = io.WriteString(w, `{"error":"task is not preparing"}`)
+ }))
+ defer srv.Close()
+
+ client := NewClient(srv.URL)
+ _, stats, err := client.ResolveSkillBundle(context.Background(), "rt-1", "task-1", SkillRefData{ID: "skill-1"})
+ if err == nil {
+ t.Fatal("expected server error")
+ }
+ if stats.ResponseStarted || stats.BytesRead != 0 {
+ t.Errorf("HTTP %d error body was counted as bundle data: %+v", status, stats)
+ }
+ })
+ }
+}
+
+func TestEnsureTaskSkillBundles_MalformedSuccessfulResponseIsNotNetworkError(t *testing.T) {
+ defer noSleepRetry(t)()
+
+ for _, tc := range []struct {
+ name string
+ body string
+ wantUnexpectedEOF bool
+ }{
+ {name: "invalid token", body: `{"bundles": definitely-not-json}`},
+ {name: "clean EOF after truncated JSON", body: `{"bundles":`, wantUnexpectedEOF: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, tc.body)
+ }))
+ defer srv.Close()
+
+ ref := skillRefFromBundle(makeResolvableSkillBundle("frontend-review"))
+ 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{ref}},
+ }
+
+ err := d.ensureTaskSkillBundles(context.Background(), task)
+ if err == nil {
+ t.Fatal("expected malformed response error")
+ }
+ if tc.wantUnexpectedEOF && !errors.Is(err, io.ErrUnexpectedEOF) {
+ t.Fatalf("truncated JSON must exercise json.Decoder's io.ErrUnexpectedEOF path, got %v", err)
+ }
+ if got := err.Error(); strings.Contains(got, "network error") || strings.Contains(got, "skill content is not at fault") {
+ t.Errorf("malformed JSON ending at a clean EOF is a server payload error, not a network failure:\n%s", got)
+ }
+ })
+ }
+}
+
+// TestTransferStatsKeepsHighWaterMark pins the across-retries semantics: the
+// question the counter answers is "did this link ever get anywhere", so an
+// attempt that reached the body must not be erased by a later one that died
+// during connect.
+func TestTransferStatsKeepsHighWaterMark(t *testing.T) {
+ var stats TransferStats
+ first := stats.wrap(strings.NewReader("0123456789"))
+ if _, err := io.ReadAll(first); err != nil {
+ t.Fatalf("read: %v", err)
+ }
+ if stats.BytesRead != 10 {
+ t.Fatalf("BytesRead = %d, want 10", stats.BytesRead)
+ }
+ // A second, shorter attempt must not lower the mark.
+ second := stats.wrap(strings.NewReader("abc"))
+ if _, err := io.ReadAll(second); err != nil {
+ t.Fatalf("read: %v", err)
+ }
+ if stats.BytesRead != 10 {
+ t.Errorf("a shorter retry lowered the high-water mark to %d, want 10", stats.BytesRead)
+ }
+ // nil must stay usable so callers can opt out of the accounting.
+ var nilStats *TransferStats
+ if got := nilStats.wrap(strings.NewReader("x")); got == nil {
+ t.Error("nil TransferStats must still return a usable reader")
+ }
+ nilStats.observeResponseStarted()
+}
+
+// TestEnsureTaskSkillBundles_SlowLinkReportsPartialTransfer is the other half
+// of #7386. A link that accepts the connection and then trickles must be
+// reported as a partial transfer, not as "no response" — that is exactly the
+// distinction that decides whether raising the deadline would have helped.
+func TestEnsureTaskSkillBundles_SlowLinkReportsPartialTransfer(t *testing.T) {
+ defer noSleepRetry(t)()
+ clearProxyEnv(t)
+
+ block := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ // Emit a valid prefix of the response, flush it so it really lands on
+ // the wire, then stall — a body that started but cannot finish.
+ io.WriteString(w, `{"bundles":[{"id":"x","content":"`+strings.Repeat("a", 4096))
+ w.(http.Flusher).Flush()
+ <-block
+ }))
+ defer srv.Close()
+ defer close(block)
+
+ ref := skillRefFromBundle(makeResolvableSkillBundle("frontend-review"))
+ 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{ref}},
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
+ defer cancel()
+
+ err := d.ensureTaskSkillBundles(ctx, task)
+ if err == nil {
+ t.Fatal("expected an error when the body never completes")
+ }
+ if !errors.Is(err, errSkillBundleUnavailable) {
+ t.Errorf("sentinel must survive, got %v", err)
+ }
+ if got := err.Error(); !strings.Contains(got, "received") || strings.Contains(got, "no response from server") {
+ t.Errorf("a stalled body must report a partial transfer, got:\n%s", got)
+ }
+}