Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
perf(issues): scope working-agent facet tasks by visible agents (MUL-7838) (#9004)
Multica Eved36ef1d1bd43
diff --git a/server/internal/handler/issue_table_facets.go b/server/internal/handler/issue_table_facets.goindex ce798e5865..58b4a1f47f 100644--- a/server/internal/handler/issue_table_facets.go+++ b/server/internal/handler/issue_table_facets.go@@ -204,6 +204,13 @@ func (h *Handler) issueTableFacetQuery(w http.ResponseWriter, r *http.Request, rcase "label":query = fmt.Sprintf(`SELECT itl.label_id::text, COUNT(DISTINCT i.id)::bigint FROM issue i JOIN issue_to_label itl ON itl.issue_id = i.id WHERE %s GROUP BY itl.label_id`, compiled.where)case "working_agents":+ agentIDs, ok := h.issueTableWorkingAgentIDs(w, r, compiled.workspaceID)+ if !ok {+ return response, false+ }+ if len(agentIDs) == 0 {+ return response, true+ }// One row per agent currently running issue work inside THIS surface,// with its running-task count. Same predicate as// ListWorkspaceWorkingAgents with type=issue (chat > autopilot > issue@@ -211,17 +218,24 @@ func (h *Handler) issueTableFacetQuery(w http.ResponseWriter, r *http.Request, r// comes from the surface's own compiled scope + filters instead of a// second, independent workspace-wide definition. That is what keeps the// header chip's count equal to the rows clicking it leaves (MUL-5525).- query = fmt.Sprintf(`SELECT a.id::text, COUNT(*)::bigint-FROM issue i-JOIN agent_task_queue atq ON atq.issue_id = i.id-JOIN agent a ON a.id = atq.agent_id AND a.workspace_id = i.workspace_id-WHERE %s- AND a.kind = 'user'- AND a.archived_at IS NULL- AND atq.status = 'running'- AND atq.chat_session_id IS NULL- AND atq.autopilot_run_id IS NULL-GROUP BY a.id`, compiled.where)+ // Join the unique visible-agent ids as a relation. With a large roster,+ // ANY(array) can become a per-task linear filter on a global running+ // scan; a relation also permits a hash join. Materialization bounds the+ // intermediate set, not the optimizer's task access or issue join plan.+ query = fmt.Sprintf(`WITH running AS MATERIALIZED (+ SELECT atq.agent_id, atq.issue_id+ FROM unnest($%d::uuid[]) AS cand(agent_id)+ JOIN agent_task_queue atq+ ON atq.agent_id = cand.agent_id AND atq.status = 'running'+ WHERE atq.chat_session_id IS NULL+ AND atq.autopilot_run_id IS NULL+ AND atq.issue_id IS NOT NULL+)+SELECT r.agent_id::text, COUNT(*)::bigint+FROM running r+WHERE EXISTS (SELECT 1 FROM issue i WHERE i.id = r.issue_id AND %s)+GROUP BY r.agent_id`, len(compiled.args)+1, compiled.where)+ compiled.args = append(compiled.args, agentIDs)case "property":propertyID, err := util.ParseUUID(facet.PropertyID)if err != nil {@@ -292,50 +306,45 @@ GROUP BY a.id`, compiled.where)writeIssueTableQueryFailure(w, r, "failed to list table facets")return response, false}- if facet.Kind == "working_agents" {- values, ok := h.filterAccessibleAgentFacetValues(w, r, compiled.workspaceID, response.Values)- if !ok {- return response, false- }- response.Values = values- }sort.Slice(response.Values, func(i, j int) bool {return strings.Compare(response.Values[i].Key, response.Values[j].Key) < 0})return response, true}-// The working-agents facet keys are agent ids, so it discloses agent identity-// and must pass the same visibility gate as every other workspace-wide agent-// aggregation: a private or non-allow-listed agent is never exposed by its id,-// its count, or even its presence.-func (h *Handler) filterAccessibleAgentFacetValues(+// The working-agents facet discloses agent identity. Resolve its visible,+// active user agents inside the table snapshot before scanning their tasks.+// accessibleAgentIDs intentionally includes archived agents for other+// aggregations, so it cannot supply this facet's candidate set.+func (h *Handler) issueTableWorkingAgentIDs(w http.ResponseWriter,r *http.Request,workspaceUUID pgtype.UUID,- values []issueTableFacetValueResponse,-) ([]issueTableFacetValueResponse, bool) {- if len(values) == 0 {- return values, true- }+) ([]pgtype.UUID, bool) {workspaceID := util.UUIDToString(workspaceUUID)member, ok := h.workspaceMember(w, r, workspaceID)if !ok {return nil, false}actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)- allowed, ok := h.accessibleAgentIDs(r.Context(), workspaceID, actorType, actorID, member.Role)+ agents, err := h.Queries.ListAgents(r.Context(), workspaceUUID)+ if err != nil {+ writeIssueTableQueryFailure(w, r, "failed to resolve agent access")+ return nil, false+ }+ targetsByAgent, ok := h.loadInvocationTargetsByAgent(r.Context(), agents)if !ok {writeIssueTableQueryFailure(w, r, "failed to resolve agent access")return nil, false}- filtered := make([]issueTableFacetValueResponse, 0, len(values))- for _, value := range values {- if _, permitted := allowed[value.Key]; permitted {- filtered = append(filtered, value)+ ids := make([]pgtype.UUID, 0, len(agents))+ for _, agent := range agents {+ if actorType == "member" && !memberAllowedToViewAgent(agent, targetsByAgent[uuidToString(agent.ID)], actorID, member.Role) {+ continue}+ ids = append(ids, agent.ID)}- return filtered, true+ return ids, true}func (h *Handler) ListIssueTableFacets(w http.ResponseWriter, r *http.Request) {diff --git a/server/internal/handler/issue_table_working_agents_facet_bench_test.go b/server/internal/handler/issue_table_working_agents_facet_bench_test.gonew file mode 100644index 0000000000..3eb45e5ddf--- /dev/null+++ b/server/internal/handler/issue_table_working_agents_facet_bench_test.go@@ -0,0 +1,86 @@+package handler++import (+ "fmt"+ "maps"+ "net/http"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// Keep the large-roster/sparse-work case: array membership can dominate the+// task scan when the planner prefers the global running index (MUL-7838).+// Measure the whole handler, including permission reads and snapshot setup.+func BenchmarkIssueTableWorkingAgentsFacet(b *testing.B) {+ for _, tc := range []struct {+ agents, running int+ }{{60, 40}, {800, 2}} {+ b.Run(fmt.Sprintf("agents=%d/running=%d", tc.agents, tc.running), func(b *testing.B) {+ workspaceID, projectID, want := seedWorkingAgentsFacetBenchmark(b, tc.agents, tc.running)+ b.ResetTimer()+ for range b.N {+ req := workingAgentsFacetRequest(map[string]any{"kind": "project", "project_id": projectID}, nil)+ req.Header.Set("X-Workspace-ID", workspaceID)+ var response issueTableFacetsResponse+ testutil.Call(b, testHandler.ListIssueTableFacets, req).Want(http.StatusOK).JSON(&response)+ got := map[string]int64{}+ for _, value := range response.Facets[0].Values {+ got[value.Key] = value.Count+ }+ if !maps.Equal(got, want) {+ b.Fatalf("working agents = %v, want %v", got, want)+ }+ }+ b.StopTimer()+ })+ }+}++func seedWorkingAgentsFacetBenchmark(tb testutil.TB, agentCount, runningCount int) (string, string, map[string]int64) {+ tb.Helper()+ workspaceID := dbfx.Workspace(tb, "working facet benchmark", fmt.Sprintf("working-facet-bench-%d", time.Now().UnixNano()))+ dbfx.Member(tb, workspaceID, testUserID, "owner")+ fx := testutil.New(testPool, workspaceID, testUserID)+ projectID := fx.Project(tb, "working facet benchmark")+ ids := make([]pgtype.UUID, 0, agentCount)+ want := map[string]int64{}+ for n := range agentCount {+ id := fx.Agent(tb, fmt.Sprintf("working facet benchmark %d", n), "")+ ids = append(ids, parseUUID(id))+ }+ for n := range runningCount {+ // Only the first twelve agents hold work in the small-roster case.+ want[uuidToString(ids[n%12])]+++ }+ fx.Cleanup(tb, `DELETE FROM issue WHERE project_id = $1`, projectID)+ fx.Exec(tb, `INSERT INTO issue (workspace_id, project_id, title, number, creator_type, creator_id, assignee_type, assignee_id)+ SELECT $1, $2, 'working facet benchmark ' || n, n, 'member', $3,+ CASE WHEN n <= 4000 THEN 'member' ELSE NULL END,+ CASE WHEN n <= 4000 THEN $3::uuid ELSE NULL END+ FROM generate_series(1,20000) n`, workspaceID, projectID, testUserID)+ foreignWorkspace := dbfx.Workspace(tb, "working facet benchmark foreign", fmt.Sprintf("working-facet-foreign-%d", time.Now().UnixNano()))+ foreignAgent := dbfx.Agent(tb, "working facet benchmark foreign", "", testutil.Cols{"workspace_id": foreignWorkspace})+ foreignIssue := dbfx.Issue(tb, "working facet benchmark foreign", testutil.Cols{"workspace_id": foreignWorkspace})+ fx.Cleanup(tb, `DELETE FROM agent_task_queue atq+ USING unnest($1::uuid[] || ARRAY[$2::uuid]) cand(agent_id)+ WHERE atq.agent_id = cand.agent_id`, ids, foreignAgent)+ fx.Exec(tb, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status)+ SELECT ($1::uuid[])[1 + ((i.number - 1) % 12)], $2, i.id, 'running'+ FROM issue i WHERE i.project_id = $3 AND i.number <= $4`, ids, testRuntimeID, projectID, runningCount)+ fx.Exec(tb, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status)+ SELECT $1, $2, $3, 'running' FROM generate_series(1,20000)`, foreignAgent, testRuntimeID, foreignIssue)+ // Historical local work makes agent selectivity alone a poor predictor of+ // running membership, as on a busy long-lived workspace. With only foreign+ // running rows, statistics can trivially exclude the foreign agent instead.+ fx.Exec(tb, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status)+ SELECT ($1::uuid[])[1 + ((n - 1) % cardinality($1::uuid[]))], $2, i.id, 'completed'+ FROM generate_series(1,500000) n+ CROSS JOIN (SELECT id FROM issue WHERE project_id = $3 AND number = 1) i`, ids, testRuntimeID, projectID)+ for _, table := range []string{"agent", "issue", "agent_task_queue"} {+ fx.Exec(tb, "ANALYZE "+table)+ }+ return workspaceID, projectID, want+}diff --git a/server/internal/handler/issue_table_working_agents_facet_test.go b/server/internal/handler/issue_table_working_agents_facet_test.goindex 738bc55701..b15696ed5a 100644--- a/server/internal/handler/issue_table_working_agents_facet_test.go+++ b/server/internal/handler/issue_table_working_agents_facet_test.go@@ -2,10 +2,13 @@ package handlerimport ("context"- "encoding/json"+ "fmt"+ "maps""net/http"- "net/http/httptest""testing"+ "time"++ "github.com/multica-ai/multica/server/internal/testutil")// workingAgentsFacetCounts posts one facets request and returns the@@ -16,20 +19,16 @@ func workingAgentsFacetCounts() map[string]int64 {t.Helper()- recorder := httptest.NewRecorder()- testHandler.ListIssueTableFacets(recorder, request)- if recorder.Code != http.StatusOK {- t.Fatalf("facets status = %d: %s", recorder.Code, recorder.Body.String())- }var response issueTableFacetsResponse- if err := json.NewDecoder(recorder.Body).Decode(&response); err != nil {- t.Fatalf("decode facets: %v", err)- }+ testutil.Call(t, testHandler.ListIssueTableFacets, request).Want(http.StatusOK).JSON(&response)counts := map[string]int64{}for _, facet := range response.Facets {if facet.Kind != "working_agents" {continue}+ if facet.Values == nil {+ t.Fatal("working-agents values must be an array, including when empty")+ }for _, value := range facet.Values {counts[value.Key] = value.Count}@@ -37,6 +36,165 @@ func workingAgentsFacetCounts(return counts}+func TestIssueTableWorkingAgentsFacetCountsOnlyEligibleRuns(t *testing.T) {+ projectID := dbfx.Project(t, "working facet eligibility")+ issueID := dbfx.Issue(t, "working facet issue", testutil.Cols{"project_id": projectID})+ agentID := dbfx.Agent(t, "working facet active", "")+ archivedID := dbfx.Agent(t, "working facet archived", "", testutil.Cols{"archived_at": testutil.Raw("now()")})+ systemID := dbfx.Agent(t, "working facet system", "", testutil.Cols{"kind": "system"})+ foreignWorkspaceID := dbfx.Workspace(t, "working facet foreign", fmt.Sprintf("working-facet-%d", time.Now().UnixNano()))+ foreignAgentID := dbfx.Agent(t, "working facet foreign", "", testutil.Cols{"workspace_id": foreignWorkspaceID})+ // Deliberately cross-link both sides: task agents and issues must each be+ // bounded to the request workspace, even if their other ids match.+ foreignIssueID := dbfx.Issue(t, "working facet foreign issue", testutil.Cols{+ "workspace_id": foreignWorkspaceID, "project_id": projectID,+ })+ chatID := dbfx.ChatSession(t, agentID)+ autopilotID := insertListTestAutopilot(t, agentID, "working-facet-autopilot")+ runID := dbfx.Insert(t, "autopilot_run", testutil.Cols{+ "autopilot_id": autopilotID, "source": "manual", "status": "running",+ })++ // Two tasks on the same issue are two runs, not one distinct issue.+ for range 2 {+ dbfx.Task(t, agentID, testutil.Cols{"runtime_id": testRuntimeID, "issue_id": issueID, "status": "running"})+ }+ for _, excludedID := range []string{archivedID, systemID, foreignAgentID} {+ dbfx.Task(t, excludedID, testutil.Cols{"runtime_id": testRuntimeID, "issue_id": issueID, "status": "running"})+ }+ for _, status := range []string{"queued", "dispatched", "completed", "failed", "cancelled"} {+ statusIssueID := dbfx.Issue(t, "working facet "+status, testutil.Cols{"project_id": projectID})+ dbfx.Task(t, agentID, testutil.Cols{"runtime_id": testRuntimeID, "issue_id": statusIssueID, "status": status})+ }+ for _, cols := range []testutil.Cols{+ {"issue_id": issueID, "chat_session_id": chatID},+ {"issue_id": issueID, "autopilot_run_id": runID},+ {"issue_id": issueID, "chat_session_id": chatID, "autopilot_run_id": runID},+ {"issue_id": foreignIssueID},+ {}, // Quick-create work has no issue yet.+ } {+ cols["status"] = "running"+ cols["runtime_id"] = testRuntimeID+ dbfx.Task(t, agentID, cols)+ }+ for _, scope := range []map[string]any{+ {"kind": "project", "project_id": projectID},+ {"kind": "workspace"},+ } {+ counts := workingAgentsFacetCounts(t, workingAgentsFacetRequest(scope, nil))+ if !maps.Equal(counts, map[string]int64{agentID: 2}) {+ t.Errorf("scope %v: counts = %v, want only active agent with 2 issue runs", scope, counts)+ }+ }++ // The final running -> completed transition must be visible on the next+ // request, without changing query identity or waiting for a cache TTL.+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed' WHERE agent_id = $1`, agentID)+ counts := workingAgentsFacetCounts(t, workingAgentsFacetRequest(map[string]any{"kind": "workspace"}, nil))+ if len(counts) != 0 {+ t.Errorf("after completion: counts = %v, want empty", counts)+ }+}++func TestIssueTableWorkingAgentsFacetVisibility(t *testing.T) {+ memberID := dbfx.User(t, "working facet member", "[email protected]")+ dbfx.Member(t, testWorkspaceID, memberID, "member")+ issueID := dbfx.Issue(t, "working facet visibility")+ privateID := dbfx.Agent(t, "working facet private", "")+ ownedID := dbfx.Agent(t, "working facet member-owned", "", testutil.Cols{"owner_id": memberID})+ workspaceID := dbfx.Agent(t, "working facet workspace", "", testutil.Cols{"permission_mode": "public_to"})+ allowedID := dbfx.Agent(t, "working facet allow-listed", "", testutil.Cols{"permission_mode": "public_to"})+ deniedID := dbfx.Agent(t, "working facet other allow-list", "", testutil.Cols{"permission_mode": "public_to"})+ for _, target := range []struct{ agentID, kind, id string }{+ {workspaceID, "workspace", testWorkspaceID},+ {allowedID, "member", memberID},+ {deniedID, "member", testUserID},+ } {+ dbfx.Insert(t, "agent_invocation_target", testutil.Cols{+ "agent_id": target.agentID, "target_type": target.kind, "target_id": target.id,+ })+ }+ all := map[string]int64{}+ for _, id := range []string{privateID, ownedID, workspaceID, allowedID, deniedID} {+ dbfx.Task(t, id, testutil.Cols{"runtime_id": testRuntimeID, "issue_id": issueID, "status": "running"})+ all[id] = 1+ }+ for _, tc := range []struct {+ name string+ userID string+ asAgent bool+ want map[string]int64+ }{+ {"member", memberID, false, map[string]int64{ownedID: 1, workspaceID: 1, allowedID: 1}},+ {"workspace owner", testUserID, false, all},+ {"agent actor", memberID, true, all},+ } {+ t.Run(tc.name, func(t *testing.T) {+ req := workingAgentsFacetRequest(map[string]any{"kind": "workspace"}, nil)+ req.Header.Set("X-User-ID", tc.userID)+ if tc.asAgent {+ // Emulate the trusted identity stamped by task-token middleware.+ req.Header.Set("X-Actor-Source", "task_token")+ req.Header.Set("X-Agent-ID", ownedID)+ }+ if got := workingAgentsFacetCounts(t, req); !maps.Equal(got, tc.want) {+ t.Errorf("counts = %v, want %v", got, tc.want)+ }+ })+ }+}++func TestIssueTableWorkingAgentsFacetMyRelations(t *testing.T) {+ otherID := dbfx.User(t, "working facet other member", "[email protected]")+ dbfx.Member(t, testWorkspaceID, otherID, "admin")+ agentID := dbfx.Agent(t, "working facet my agent", "")+ for _, cols := range []testutil.Cols{+ {"creator_id": otherID, "assignee_type": "member", "assignee_id": testUserID},+ {"creator_id": testUserID},+ {"creator_id": otherID, "assignee_type": "agent", "assignee_id": agentID},+ {"creator_id": otherID, "assignee_type": "member", "assignee_id": otherID},+ } {+ issueID := dbfx.Issue(t, "working facet my relation", cols)+ dbfx.Task(t, agentID, testutil.Cols{"runtime_id": testRuntimeID, "issue_id": issueID, "status": "running"})+ }+ for _, tc := range []struct {+ userID string+ relation string+ want int64+ }{+ {testUserID, "assigned", 1}, {testUserID, "created", 1},+ {testUserID, "involved", 1}, {testUserID, "any", 3}, {testUserID, "", 3},+ {otherID, "assigned", 1}, {otherID, "created", 3},+ {otherID, "involved", 0}, {otherID, "any", 3},+ } {+ req := workingAgentsFacetRequest(map[string]any{"kind": "my", "relation": tc.relation}, nil)+ req.Header.Set("X-User-ID", tc.userID)+ got := workingAgentsFacetCounts(t, req)+ want := map[string]int64{}+ if tc.want > 0 {+ want[agentID] = tc.want+ }+ if !maps.Equal(got, want) {+ t.Errorf("user %s relation %q: counts = %v, want %v", tc.userID, tc.relation, got, want)+ }+ }+}++func TestIssueTableWorkingAgentsFacetNoActiveAgents(t *testing.T) {+ workspaceID := dbfx.Workspace(t, "working facet empty", fmt.Sprintf("working-facet-empty-%d", time.Now().UnixNano()))+ dbfx.Member(t, workspaceID, testUserID, "owner")+ agentID := dbfx.Agent(t, "working facet only archived", "", testutil.Cols{+ "workspace_id": workspaceID, "archived_at": testutil.Raw("now()"),+ })+ issueID := dbfx.Issue(t, "working facet archived issue", testutil.Cols{"workspace_id": workspaceID})+ dbfx.Task(t, agentID, testutil.Cols{"runtime_id": testRuntimeID, "issue_id": issueID, "status": "running"})+ req := workingAgentsFacetRequest(map[string]any{"kind": "workspace"}, nil)+ req.Header.Set("X-Workspace-ID", workspaceID)+ if got := workingAgentsFacetCounts(t, req); len(got) != 0 {+ t.Errorf("counts = %v, want empty for workspace with only archived agents", got)+ }+}+func workingAgentsFacetRequest(scope, filters map[string]any) *http.Request {if filters == nil {filters = map[string]any{}