Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6792: perf(server): batch skill-file loads in LoadAgentSkills (#7689)
importcppbe93feb0631a
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex fe60d3ad68..dc2b0d8f2e 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1837,6 +1837,28 @@ func (h *Handler) rejectClaimSourceLoad(ctx context.Context, task *db.AgentTaskQ}}+// rejectClaimSkillLoad settles a claim whose agent skills could not be read.+// It mirrors rejectClaimSourceLoad's transient branch — preserve the+// just-dispatched task so the stale-dispatched reclaim redelivers it — because+// this is the same kind of failure: a transient read on the claim-build path.+//+// Dispatching with whatever loaded is not the safer half-measure it looks+// like. LoadAgentSkills reads the whole skill set in two queries, so a failure+// means every skill loses its supporting files or the agent loses every skill,+// and the ref hashes sent to the daemon are computed over that same truncated+// content — so the daemon validates the bundle, caches it, and the agent runs+// with rules silently missing. There is no ErrNoRows branch to mirror: an+// agent with no skills is a legitimate empty result, not a missing row.+func (h *Handler) rejectClaimSkillLoad(task *db.AgentTaskQueue, err error) *claimBuildFailure {+ slog.Error("task claim: agent skill load failed; preserving task for redelivery",+ "task_id", uuidToString(task.ID), "agent_id", uuidToString(task.AgentID), "error", err)+ return &claimBuildFailure{+ outcome: "error_skill_load",+ status: http.StatusInternalServerError,+ message: "failed to load agent skills",+ }+}+// rejectClaimOnWorkspaceMismatch enforces the claim's tenant boundary against// the workspace that OWNS the task's context (issue / chat session / autopilot// / quick-create), which is the only authority for MULTICA_WORKSPACE_ID in the@@ -2165,11 +2187,17 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQuresp.Agent.Instructions = service.ComposeMikaInstructions(agent.Name, agent.Instructions)}if useSkillRefs {- _, skillRefs := h.TaskService.LoadAgentSkillBundles(r.Context(), task.AgentID)+ _, skillRefs, err := h.TaskService.LoadAgentSkillBundles(r.Context(), task.AgentID)+ if err != nil {+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, h.rejectClaimSkillLoad(task, err)+ }agentSkillCount = len(skillRefs)resp.Agent.SkillRefs = skillRefs} else {- skills := h.TaskService.LoadAgentSkills(r.Context(), task.AgentID)+ skills, err := h.TaskService.LoadAgentSkills(r.Context(), task.AgentID)+ if err != nil {+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, h.rejectClaimSkillLoad(task, err)+ }agentSkillCount = len(skills)builtinSkills := h.TaskService.BuiltinSkills()builtinSkillCount = len(builtinSkills)@@ -3420,7 +3448,16 @@ func (h *Handler) ResolveTaskSkillBundles(w http.ResponseWriter, r *http.Requestreturn}- bundles, _ := h.TaskService.LoadAgentSkillBundles(r.Context(), task.AgentID)+ bundles, _, err := h.TaskService.LoadAgentSkillBundles(r.Context(), task.AgentID)+ if err != nil {+ // 5xx, not a partial answer: the daemon's resolve retry can recover a+ // transient read, and a bundle assembled from a failed read would pass+ // its client-side validation and be cached as if it were complete.+ slog.Error("resolve skill bundles: load agent skills failed",+ "task_id", uuidToString(task.ID), "agent_id", uuidToString(task.AgentID), "error", err)+ writeError(w, http.StatusInternalServerError, "failed to load skill bundles")+ return+ }allowed := make(map[string]service.AgentSkillData, len(bundles))for _, bundle := range bundles {allowed[bundle.Source+"\x00"+bundle.ID] = bundlediff --git a/server/internal/handler/daemon_skill_load_failure_test.go b/server/internal/handler/daemon_skill_load_failure_test.gonew file mode 100644index 0000000000..e82c0bf926--- /dev/null+++ b/server/internal/handler/daemon_skill_load_failure_test.go@@ -0,0 +1,172 @@+package handler++import (+ "context"+ "errors"+ "net/http"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// The batched skill-file read introduced for GH #7688 owns EVERY skill's files+// in one query, so a failure there is not a smaller payload — it is a+// different one: all supporting files vanish at once, and the ref hashes the+// daemon validates against are computed over that same truncated content. The+// daemon therefore accepts and caches it, and the agent runs with rules+// silently missing. These tests pin that neither claim call site nor the+// resolve endpoint dispatches on a failed read.++var errInjectedSkillFileRead = errors.New("injected skill file read failure")++// skillFileBatchFailDBTX passes every statement through to the real pool+// EXCEPT the batched skill-file read, which it fails.+type skillFileBatchFailDBTX struct{ inner db.DBTX }++func (f skillFileBatchFailDBTX) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {+ return f.inner.Exec(ctx, sql, args...)+}++func (f skillFileBatchFailDBTX) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {+ if strings.Contains(sql, "ListSkillFilesBySkillIDs") {+ return nil, errInjectedSkillFileRead+ }+ return f.inner.Query(ctx, sql, args...)+}++func (f skillFileBatchFailDBTX) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {+ return f.inner.QueryRow(ctx, sql, args...)+}++// newSkillFileReadFailureHandler is testHandler with the skill-file read+// broken. It shares the same pool, hub and bus so everything else on the claim+// path behaves normally.+func newSkillFileReadFailureHandler(t *testing.T) *Handler {+ t.Helper()+ return New(+ db.New(skillFileBatchFailDBTX{inner: testPool}),+ testPool,+ testHandler.Hub,+ testHandler.Bus,+ testHandler.EmailService,+ nil,+ nil,+ analytics.NoopClient{},+ Config{},+ )+}++// seedSkillLoadFixture creates a runtime, an agent carrying one workspace+// skill with a supporting file, and a queued task for it.+func seedSkillLoadFixture(t *testing.T, ctx context.Context, name string) (runtimeID, taskID, skillID string) {+ t.Helper()++ runtimeID = createClaimReclaimRuntime(t, ctx, name+" runtime")+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, name+" agent")++ skillID = dbfx.Insert(t, "skill", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "name": name + "-skill",+ "description": "Skill read failure fixture",+ "content": "main skill content",+ "config": testutil.Raw("'{}'::jsonb"),+ "created_by": testUserID,+ })+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM agent_skill WHERE skill_id = $1`, skillID)+ testPool.Exec(ctx, `DELETE FROM skill_file WHERE skill_id = $1`, skillID)+ testPool.Exec(ctx, `DELETE FROM skill WHERE id = $1`, skillID)+ })+ dbfx.Exec(t, `INSERT INTO skill_file (skill_id, path, content) VALUES ($1, 'rules.md', 'rules content')`, skillID)+ dbfx.Exec(t, `INSERT INTO agent_skill (agent_id, skill_id) VALUES ($1, $2)`, agentID, skillID)++ taskID = dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ })+ return runtimeID, taskID, skillID+}++// TestClaimTaskByRuntime_SkillReadFailurePreservesTask covers both claim call+// sites — the slim skill-refs claim and the legacy inline-skills claim. Each+// must refuse the claim and LEAVE THE TASK DISPATCHED so the stale-dispatched+// reclaim redelivers it, rather than settling it or handing the daemon an+// agent whose skills silently lost their files.+func TestClaimTaskByRuntime_SkillReadFailurePreservesTask(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ tests := []struct {+ name string+ fixture string+ capability string+ }{+ {name: "slim skill refs claim", fixture: "skillrefsfail", capability: protocol.DaemonCapabilitySkillBundlesV1},+ {name: "inline skills claim", fixture: "skillinlinefail", capability: ""},+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ ctx := context.Background()+ failing := newSkillFileReadFailureHandler(t)+ runtimeID, taskID, _ := seedSkillLoadFixture(t, ctx, tc.fixture)++ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "skill-read-fail-daemon")+ if tc.capability != "" {+ req.Header.Set("X-Client-Capabilities", tc.capability)+ }+ req = withURLParam(req, "runtimeId", runtimeID)+ testutil.Call(t, failing.ClaimTaskByRuntime, req).Want(http.StatusInternalServerError)++ // Preserved, not settled: still dispatched and never started, which+ // is exactly what the stale-dispatched reclaim picks back up.+ var status string+ var started bool+ dbfx.QueryRow(t, `SELECT status, started_at IS NOT NULL FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status, &started)+ if status != "dispatched" {+ t.Fatalf("task status = %q, want dispatched (a failed skill read must not settle the task)", status)+ }+ if started {+ t.Fatal("task was marked started despite the claim being refused")+ }+ })+ }+}++// TestResolveTaskSkillBundles_SkillReadFailureReturns500 pins the resolve side:+// a 5xx is what the daemon's existing resolve retry recovers from, and it is+// the only answer that keeps a bundle built from a failed read out of the+// daemon's on-disk cache — the daemon validates a bundle against a ref derived+// from that same bundle, so a truncated one would validate.+func TestResolveTaskSkillBundles_SkillReadFailureReturns500(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ runtimeID, taskID, skillID := seedSkillLoadFixture(t, ctx, "skillresolvefail")+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'dispatched', dispatched_at = now() WHERE id = $1`, taskID)++ body := resolveSkillBundlesRequest{Skills: []resolveSkillBundleRef{{+ ID: skillID,+ Source: "workspace",+ Hash: "sha256:whatever",+ }}}++ // The same request succeeds on the healthy handler, so the 500 below is+ // the injected read failure and not a malformed fixture.+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", body, testWorkspaceID, "skill-read-fail-daemon")+ req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)+ testutil.Call(t, testHandler.ResolveTaskSkillBundles, req).Want(http.StatusOK)++ failing := newSkillFileReadFailureHandler(t)+ req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", body, testWorkspaceID, "skill-read-fail-daemon")+ req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)+ testutil.Call(t, failing.ResolveTaskSkillBundles, req).Want(http.StatusInternalServerError)+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 9064dfc146..9a31da4ff6 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -6324,35 +6324,68 @@ func (s *TaskService) publishAgentStatus(agent db.Agent) {}// LoadAgentSkills loads an agent's skills with their files for task execution.-func (s *TaskService) LoadAgentSkills(ctx context.Context, agentID pgtype.UUID) []AgentSkillData {+//+// A read failure is REPORTED, never swallowed into a shorter skill set. Both+// reads are all-or-nothing for the agent's entire skill set — the file load+// covers every skill in one query — so a swallowed error does not degrade the+// payload, it silently replaces it: every skill loses its supporting files, or+// the agent loses every skill. Nothing downstream can tell that apart from an+// agent that genuinely has none, because the bundle hash is computed over+// whatever did load, so the daemon's own validation passes and the agent+// starts on rules it is missing. Callers must settle the failure (preserve the+// claim for redelivery, or 5xx the resolve) instead of dispatching that.+func (s *TaskService) LoadAgentSkills(ctx context.Context, agentID pgtype.UUID) ([]AgentSkillData, error) {skills, err := s.Queries.ListAgentSkills(ctx, agentID)- if err != nil || len(skills) == 0 {- return nil+ if err != nil {+ return nil, fmt.Errorf("list agent skills: %w", err)+ }+ if len(skills) == 0 {+ return nil, nil+ }++ // Load every skill's files in one round trip instead of one query per+ // skill (N+1 on the task-claim hot path). Group by skill_id in a single+ // linear pass — the query orders by skill_id, path.+ skillIDs := make([]pgtype.UUID, len(skills))+ for i, sk := range skills {+ skillIDs[i] = sk.ID+ }+ files, err := s.Queries.ListSkillFilesBySkillIDs(ctx, skillIDs)+ if err != nil {+ return nil, fmt.Errorf("list skill files for %d skills: %w", len(skills), err)+ }+ filesBySkill := make(map[string][]AgentSkillFileData, len(skills))+ for _, f := range files {+ id := util.UUIDToString(f.SkillID)+ filesBySkill[id] = append(filesBySkill[id], AgentSkillFileData{Path: f.Path, Content: f.Content})}result := make([]AgentSkillData, 0, len(skills))for _, sk := range skills {- data := AgentSkillData{+ result = append(result, AgentSkillData{ID: util.UUIDToString(sk.ID),Name: sk.Name,Description: sk.Description,Content: sk.Content,- }- files, _ := s.Queries.ListSkillFiles(ctx, sk.ID)- for _, f := range files {- data.Files = append(data.Files, AgentSkillFileData{Path: f.Path, Content: f.Content})- }- result = append(result, data)+ Files: filesBySkill[util.UUIDToString(sk.ID)],+ })}- return result+ return result, nil}// LoadAgentSkillBundles returns every skill visible to an agent, including// built-ins, with stable bundle hashes and lightweight refs for slim claims.-func (s *TaskService) LoadAgentSkillBundles(ctx context.Context, agentID pgtype.UUID) ([]AgentSkillData, []AgentSkillRefData) {- skills := s.LoadAgentSkills(ctx, agentID)+// It fails closed on a workspace-skill read error for the reason in+// LoadAgentSkills: a bundle set built from a partial read is indistinguishable+// from a correct one.+func (s *TaskService) LoadAgentSkillBundles(ctx context.Context, agentID pgtype.UUID) ([]AgentSkillData, []AgentSkillRefData, error) {+ skills, err := s.LoadAgentSkills(ctx, agentID)+ if err != nil {+ return nil, nil, err+ }skills = append(skills, s.BuiltinSkills()...)- return BuildAgentSkillBundles(skills)+ bundles, refs := BuildAgentSkillBundles(skills)+ return bundles, refs, nil}func BuildAgentSkillBundles(skills []AgentSkillData) ([]AgentSkillData, []AgentSkillRefData) {diff --git a/server/internal/service/task_agent_skills_test.go b/server/internal/service/task_agent_skills_test.gonew file mode 100644index 0000000000..30ac3f94a4--- /dev/null+++ b/server/internal/service/task_agent_skills_test.go@@ -0,0 +1,242 @@+package service++import (+ "context"+ "errors"+ "fmt"+ "reflect"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// errInjectedSkillRead is the transient read failure these tests inject. The+// point of every failure case below is that it reaches the caller: a swallowed+// read here does not shrink the payload, it silently replaces it with a+// smaller one that hashes and validates like a correct one.+var errInjectedSkillRead = errors.New("injected skill read failure")++// sliceRows is a pgx.Rows over canned column values, so the skill loaders can+// be exercised without a database. Values must match the destination field+// types exactly; Scan assigns them positionally.+type sliceRows struct {+ rows [][]any+ i int+}++func (r *sliceRows) Close() {}+func (r *sliceRows) Err() error { return nil }+func (r *sliceRows) CommandTag() pgconn.CommandTag { return pgconn.NewCommandTag("") }+func (r *sliceRows) FieldDescriptions() []pgconn.FieldDescription { return nil }+func (r *sliceRows) Values() ([]any, error) { return nil, nil }+func (r *sliceRows) RawValues() [][]byte { return nil }+func (r *sliceRows) Conn() *pgx.Conn { return nil }++func (r *sliceRows) Next() bool {+ if r.i >= len(r.rows) {+ return false+ }+ r.i+++ return true+}++func (r *sliceRows) Scan(dest ...any) error {+ if r.i == 0 || r.i > len(r.rows) {+ return fmt.Errorf("Scan called outside a row")+ }+ values := r.rows[r.i-1]+ if len(values) != len(dest) {+ return fmt.Errorf("scan: %d destinations for %d columns", len(dest), len(values))+ }+ for i, d := range dest {+ dv := reflect.ValueOf(d)+ if dv.Kind() != reflect.Pointer || dv.IsNil() {+ return fmt.Errorf("scan: destination %d is not a non-nil pointer", i)+ }+ sv := reflect.ValueOf(values[i])+ if !sv.IsValid() || !sv.Type().AssignableTo(dv.Elem().Type()) {+ return fmt.Errorf("scan: column %d is %T, destination is %s", i, values[i], dv.Elem().Type())+ }+ dv.Elem().Set(sv)+ }+ return nil+}++// skillReadDBTX serves canned skill / skill_file result sets and can fail one+// chosen query. perSkillFileCalls counts the pre-batch ListSkillFiles query so+// a test can prove the N+1 loop is gone rather than just assuming it.+type skillReadDBTX struct {+ skills [][]any+ files [][]any+ failQuery string+ perSkillFileCall int+}++func (d *skillReadDBTX) Exec(context.Context, string, ...any) (pgconn.CommandTag, error) {+ return pgconn.NewCommandTag(""), nil+}++func (d *skillReadDBTX) QueryRow(context.Context, string, ...any) pgx.Row { return noRow{} }++func (d *skillReadDBTX) Query(_ context.Context, sql string, _ ...any) (pgx.Rows, error) {+ // Checked longest-name-first: the batch query's text also contains the+ // per-skill query's name as a prefix.+ switch {+ case strings.Contains(sql, "ListSkillFilesBySkillIDs"):+ if d.failQuery == "ListSkillFilesBySkillIDs" {+ return nil, errInjectedSkillRead+ }+ return &sliceRows{rows: d.files}, nil+ case strings.Contains(sql, "ListSkillFiles"):+ d.perSkillFileCall+++ return &sliceRows{}, nil+ case strings.Contains(sql, "ListAgentSkills"):+ if d.failQuery == "ListAgentSkills" {+ return nil, errInjectedSkillRead+ }+ return &sliceRows{rows: d.skills}, nil+ }+ return nil, fmt.Errorf("unexpected query: %s", sql)+}++// skillRow / skillFileRow build result rows in the column order the generated+// ListAgentSkills / ListSkillFilesBySkillIDs scanners read.+func skillRow(id pgtype.UUID, name, description, content string) []any {+ return []any{+ id, testUUID(0xF0), name, description, content,+ []byte(nil), pgtype.UUID{}, pgtype.Timestamptz{}, pgtype.Timestamptz{}, pgtype.UUID{},+ }+}++func skillFileRow(skillID pgtype.UUID, path, content string) []any {+ return []any{+ testUUID(0xF1), skillID, path, content,+ pgtype.Timestamptz{}, pgtype.Timestamptz{},+ }+}++// TestLoadAgentSkills_GroupsBatchedFilesBySkillID pins the batch assembly.+// ListAgentSkills orders by name and ListSkillFilesBySkillIDs orders by+// skill_id, so the two result sets are in DIFFERENT orders — the fixture makes+// them disagree deliberately. Grouping must be by skill_id; a positional zip+// of the two would hand each skill another skill's files.+func TestLoadAgentSkills_GroupsBatchedFilesBySkillID(t *testing.T) {+ alpha, beta, gamma := testUUID(3), testUUID(1), testUUID(2)++ fake := &skillReadDBTX{+ // ListAgentSkills order: name ASC.+ skills: [][]any{+ skillRow(alpha, "alpha", "first", "alpha body"),+ skillRow(beta, "beta", "second", "beta body"),+ skillRow(gamma, "gamma", "third", "gamma body"),+ },+ // ListSkillFilesBySkillIDs order: skill_id, path ASC. gamma has none.+ files: [][]any{+ skillFileRow(beta, "a.md", "beta a"),+ skillFileRow(beta, "z.md", "beta z"),+ skillFileRow(alpha, "docs/one.md", "alpha one"),+ skillFileRow(alpha, "docs/two.md", "alpha two"),+ },+ }+ svc := &TaskService{Queries: db.New(fake)}++ got, err := svc.LoadAgentSkills(context.Background(), testUUID(9))+ if err != nil {+ t.Fatalf("LoadAgentSkills: %v", err)+ }+ if len(got) != 3 {+ t.Fatalf("loaded %d skills, want 3", len(got))+ }++ // Skill order follows ListAgentSkills, not the file result set.+ wantNames := []string{"alpha", "beta", "gamma"}+ for i, want := range wantNames {+ if got[i].Name != want {+ t.Fatalf("skill %d is %q, want %q", i, got[i].Name, want)+ }+ }++ wantFiles := map[string][]AgentSkillFileData{+ "alpha": {{Path: "docs/one.md", Content: "alpha one"}, {Path: "docs/two.md", Content: "alpha two"}},+ "beta": {{Path: "a.md", Content: "beta a"}, {Path: "z.md", Content: "beta z"}},+ "gamma": nil,+ }+ for _, skill := range got {+ if !reflect.DeepEqual(skill.Files, wantFiles[skill.Name]) {+ t.Fatalf("skill %q files = %+v, want %+v", skill.Name, skill.Files, wantFiles[skill.Name])+ }+ }+ // A skill with no files keeps the nil (omitempty) list it had before the+ // batch load, not an empty slice that would serialize as `"files": []`.+ if got[2].Files != nil {+ t.Fatalf("skill without files got %v, want nil", got[2].Files)+ }++ if fake.perSkillFileCall != 0 {+ t.Fatalf("per-skill ListSkillFiles ran %d times, want 0 (the N+1 loop is what this replaced)", fake.perSkillFileCall)+ }+}++// TestLoadAgentSkills_ReportsReadFailures is the review regression for #7689:+// batching made ONE query own every skill's files, so swallowing its error+// strips attachments from ALL of them at once — and the caller cannot tell+// that apart from an agent whose skills genuinely have no files, because the+// bundle hash is then computed over the truncated content. Both reads must+// surface the failure instead.+func TestLoadAgentSkills_ReportsReadFailures(t *testing.T) {+ tests := []struct {+ name string+ failQuery string+ }{+ {name: "batch file query fails", failQuery: "ListSkillFilesBySkillIDs"},+ {name: "agent skill query fails", failQuery: "ListAgentSkills"},+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ fake := &skillReadDBTX{+ skills: [][]any{skillRow(testUUID(1), "alpha", "first", "alpha body")},+ files: [][]any{skillFileRow(testUUID(1), "a.md", "alpha a")},+ failQuery: tc.failQuery,+ }+ svc := &TaskService{Queries: db.New(fake)}++ got, err := svc.LoadAgentSkills(context.Background(), testUUID(9))+ if err == nil {+ t.Fatalf("LoadAgentSkills returned nil error and %d skills; a failed read must not look like a smaller skill set", len(got))+ }+ if !errors.Is(err, errInjectedSkillRead) {+ t.Fatalf("error %v does not wrap the injected read failure", err)+ }+ if got != nil {+ t.Fatalf("LoadAgentSkills returned %d skills alongside an error, want none", len(got))+ }+ })+ }+}++// TestLoadAgentSkillBundles_FailsClosedOnReadFailure covers the same failure+// one level up. Returning the built-ins alone would be the worst outcome: a+// well-formed bundle set with valid hashes and refs that the daemon accepts+// and caches, for an agent that is missing every workspace skill it owns.+func TestLoadAgentSkillBundles_FailsClosedOnReadFailure(t *testing.T) {+ fake := &skillReadDBTX{+ skills: [][]any{skillRow(testUUID(1), "alpha", "first", "alpha body")},+ failQuery: "ListSkillFilesBySkillIDs",+ }+ svc := &TaskService{Queries: db.New(fake)}++ bundles, refs, err := svc.LoadAgentSkillBundles(context.Background(), testUUID(9))+ if err == nil {+ t.Fatalf("LoadAgentSkillBundles returned nil error with %d bundles / %d refs", len(bundles), len(refs))+ }+ if !errors.Is(err, errInjectedSkillRead) {+ t.Fatalf("error %v does not wrap the injected read failure", err)+ }+ if bundles != nil || refs != nil {+ t.Fatalf("returned %d bundles / %d refs alongside an error, want none", len(bundles), len(refs))+ }+}diff --git a/server/pkg/db/generated/skill.sql.go b/server/pkg/db/generated/skill.sql.goindex c56153341c..ec5a9c7008 100644--- a/server/pkg/db/generated/skill.sql.go+++ b/server/pkg/db/generated/skill.sql.go@@ -464,6 +464,45 @@ func (q *Queries) ListSkillFiles(ctx context.Context, skillID pgtype.UUID) ([]Skreturn items, nil}+const listSkillFilesBySkillIDs = `-- name: ListSkillFilesBySkillIDs :many+SELECT id, skill_id, path, content, created_at, updated_at FROM skill_file+WHERE skill_id = ANY($1::uuid[])+ORDER BY skill_id, path ASC+`++// Batch variant of ListSkillFiles: loads every file for a set of skills in one+// round trip so LoadAgentSkills doesn't issue one query per skill on the+// task-claim hot path. Ordered by skill_id so the caller can group in a single+// linear pass. Like ListSkillFiles it returns full file bodies — callers that+// only need metadata must use ListSkillFileMetadata instead. Uses+// idx_skill_file_skill.+func (q *Queries) ListSkillFilesBySkillIDs(ctx context.Context, skillIds []pgtype.UUID) ([]SkillFile, error) {+ rows, err := q.db.Query(ctx, listSkillFilesBySkillIDs, skillIds)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []SkillFile{}+ for rows.Next() {+ var i SkillFile+ if err := rows.Scan(+ &i.ID,+ &i.SkillID,+ &i.Path,+ &i.Content,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listSkillSummariesByWorkspace = `-- name: ListSkillSummariesByWorkspace :manySELECT id, workspace_id, name, description, config, created_by, created_at, updated_atFROM skilldiff --git a/server/pkg/db/queries/skill.sql b/server/pkg/db/queries/skill.sqlindex 103b0d39c2..70b632f980 100644--- a/server/pkg/db/queries/skill.sql+++ b/server/pkg/db/queries/skill.sql@@ -55,6 +55,17 @@ SELECT * FROM skill_fileWHERE skill_id = $1ORDER BY path ASC;+-- name: ListSkillFilesBySkillIDs :many+-- Batch variant of ListSkillFiles: loads every file for a set of skills in one+-- round trip so LoadAgentSkills doesn't issue one query per skill on the+-- task-claim hot path. Ordered by skill_id so the caller can group in a single+-- linear pass. Like ListSkillFiles it returns full file bodies — callers that+-- only need metadata must use ListSkillFileMetadata instead. Uses+-- idx_skill_file_skill.+SELECT * FROM skill_file+WHERE skill_id = ANY(sqlc.arg('skill_ids')::uuid[])+ORDER BY skill_id, path ASC;+-- name: ListSkillFileMetadata :many-- Metadata-only variant of ListSkillFiles: path, byte size and content hash-- without the body. Same reason as ListSkillSummariesByWorkspace — a skill