Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5823 fix(dashboard): count cancelled runs in usage run time (#6518)
Bohan Jiang2d993a6a8073
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 59b204ee36..ee7c8a1b57 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -6,6 +6,7 @@ import {FALLBACK_AUTOPILOT_RUN,CommentTriggerPreviewSchema,DashboardAgentRunTimeListSchema,+ DashboardRunTimeDailyListSchema,DashboardFailureByAgentListSchema,DashboardFailureDailyListSchema,DashboardUsageByAgentListSchema,@@ -724,6 +725,23 @@ describe("dashboard + runtime usage schema drift", () => {expect(parsed[0]?.agent_id).toBe("");});+ it("defaults a missing cancelled_count to 0 so a pre-cancelled-count server still renders", () => {+ // cancelled_count was added when the run-time rollups started counting+ // runs the user stopped mid-flight. A backend predating it omits the+ // field; the row must survive with a 0 segment rather than drop the+ // whole series (installed desktop clients hit older backends).+ expect(+ DashboardAgentRunTimeListSchema.parse([+ { agent_id: "a", total_seconds: 42, task_count: 3, failed_count: 0 },+ ])[0]?.cancelled_count,+ ).toBe(0);+ expect(+ DashboardRunTimeDailyListSchema.parse([+ { date: "2026-05-19", total_seconds: 42, task_count: 3, failed_count: 0 },+ ])[0]?.cancelled_count,+ ).toBe(0);+ });+it("coerces a missing agent_id key to \"\" for the usage-by-agent panel", () => {const parsed = DashboardUsageByAgentListSchema.parse([{ model: "claude-opus-4-7", input_tokens: 7 },diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex c64184a2f8..ecd6c57e12 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1030,11 +1030,15 @@ const DashboardUsageByAgentSchema = z.object({export const DashboardUsageByAgentListSchema = z.array(DashboardUsageByAgentSchema);+// `cancelled_count` defaults to 0 so an installed client pointed at a+// backend that predates it still renders: those rows simply carry no+// cancelled segment, which is exactly what that backend measured.const DashboardAgentRunTimeSchema = z.object({agent_id: z.string().default(""),total_seconds: z.number().default(0),task_count: z.number().default(0),failed_count: z.number().default(0),+ cancelled_count: z.number().default(0),}).loose();export const DashboardAgentRunTimeListSchema = z.array(DashboardAgentRunTimeSchema);@@ -1044,6 +1048,7 @@ const DashboardRunTimeDailySchema = z.object({total_seconds: z.number().default(0),task_count: z.number().default(0),failed_count: z.number().default(0),+ cancelled_count: z.number().default(0),}).loose();export const DashboardRunTimeDailyListSchema = z.array(DashboardRunTimeDailySchema);diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex cc53cc9b95..3e8b020dc5 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -1039,6 +1039,11 @@ export interface DashboardAgentRunTime {total_seconds: number;task_count: number;failed_count: number;+ // Runs the user stopped mid-flight. Disjoint from `failed_count`, and+ // both are subsets of `task_count` — the succeeded count is the+ // remainder. A stopped run still occupied an agent and still spent+ // tokens, so its seconds belong in `total_seconds`.+ cancelled_count: number;}// One (date) bucket of terminal-task run-time + counts for the workspace@@ -1050,6 +1055,8 @@ export interface DashboardRunTimeDaily {total_seconds: number;task_count: number;failed_count: number;+ // See DashboardAgentRunTime.cancelled_count.+ cancelled_count: number;}// One (date, failure_reason) bucket of terminal-task counts for the workspacediff --git a/packages/views/dashboard/utils.test.ts b/packages/views/dashboard/utils.test.tsindex 7d7c02d58e..0124be42a4 100644--- a/packages/views/dashboard/utils.test.ts+++ b/packages/views/dashboard/utils.test.ts@@ -6,6 +6,7 @@ import {aggregateAgentTokens,aggregateDailyCost,aggregateDailyErrors,+ aggregateDailyTasks,aggregateFailureClasses,aggregateFailureReasons,aggregateWeeklyErrors,@@ -166,6 +167,7 @@ describe("mergeAgentDashboardRows", () => {total_seconds: 600,task_count: 1, // truth: one task touched both modelsfailed_count: 0,+ cancelled_count: 0,},];const merged = mergeAgentDashboardRows(tokenRows, runTimeRows);@@ -192,7 +194,7 @@ describe("mergeAgentDashboardRows", () => {// list with zeroed-out token columns.const merged = mergeAgentDashboardRows([],- [{ agent_id: "agent-c", total_seconds: 30, task_count: 1, failed_count: 1 }],+ [{ agent_id: "agent-c", total_seconds: 30, task_count: 1, failed_count: 1, cancelled_count: 0 }],);expect(merged).toHaveLength(1);expect(merged[0]!.tokens).toBe(0);@@ -208,7 +210,7 @@ describe("mergeAgentDashboardRows", () => {{ agentId: "zero-cost-long", tokens: 0, cost: 0, taskCount: 0 },],[- { agent_id: "zero-cost-long", total_seconds: 1000, task_count: 5, failed_count: 0 },+ { agent_id: "zero-cost-long", total_seconds: 1000, task_count: 5, failed_count: 0, cancelled_count: 0 },],);expect(merged.map((r) => r.agentId)).toEqual(["high", "low", "zero-cost-long"]);@@ -368,9 +370,9 @@ describe("aggregateWeeklyTime", () => {// 2026-05-19 is a Tuesday → current week is Mon=05-18..Sun=05-24.vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));const rows = [- { date: "2026-05-11", total_seconds: 100, task_count: 0, failed_count: 0 },- { date: "2026-05-17", total_seconds: 50, task_count: 0, failed_count: 0 },- { date: "2026-05-18", total_seconds: 25, task_count: 0, failed_count: 0 },+ { date: "2026-05-11", total_seconds: 100, task_count: 0, failed_count: 0, cancelled_count: 0 },+ { date: "2026-05-17", total_seconds: 50, task_count: 0, failed_count: 0, cancelled_count: 0 },+ { date: "2026-05-18", total_seconds: 25, task_count: 0, failed_count: 0, cancelled_count: 0 },];const result = aggregateWeeklyTime(rows, "UTC", 2);expect(result).toHaveLength(2);@@ -397,7 +399,7 @@ describe("aggregateWeeklyTime", () => {const rows = [// 2026-04-13 is a Monday — exactly one week earlier than the oldest// in-range week (Mon=04-20) for a 5-week trailing window.- { date: "2026-04-13", total_seconds: 999, task_count: 0, failed_count: 0 },+ { date: "2026-04-13", total_seconds: 999, task_count: 0, failed_count: 0, cancelled_count: 0 },];const result = aggregateWeeklyTime(rows, "UTC", 5);expect(result.map((w) => w.weekStart)).toEqual([@@ -422,8 +424,8 @@ describe("aggregateWeeklyTasks", () => {it("splits completed and failed counts per calendar week", () => {vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));const rows = [- { date: "2026-05-12", total_seconds: 0, task_count: 5, failed_count: 1 },- { date: "2026-05-18", total_seconds: 0, task_count: 3, failed_count: 0 },+ { date: "2026-05-12", total_seconds: 0, task_count: 5, failed_count: 1, cancelled_count: 0 },+ { date: "2026-05-18", total_seconds: 0, task_count: 3, failed_count: 0, cancelled_count: 0 },];const result = aggregateWeeklyTasks(rows, "UTC", 2);expect(result[0]).toMatchObject({@@ -438,6 +440,72 @@ describe("aggregateWeeklyTasks", () => {partial: true,});});++ it("keeps cancelled runs out of the completed segment", () => {+ vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));+ const result = aggregateWeeklyTasks(+ [+ {+ date: "2026-05-12",+ total_seconds: 0,+ task_count: 6,+ failed_count: 1,+ cancelled_count: 2,+ },+ ],+ "UTC",+ 2,+ );+ expect(result[0]).toMatchObject({+ weekStart: "2026-05-11",+ completed: 3,+ failed: 1,+ cancelled: 2,+ });+ });+});++describe("aggregateDailyTasks", () => {+ // failed_count and cancelled_count are disjoint subsets of task_count, so+ // the succeeded segment is the remainder. Forgetting to subtract cancelled+ // is what renders a run the user stopped as a green "completed" bar.+ it("splits the stack three ways and sorts oldest-first", () => {+ const result = aggregateDailyTasks([+ {+ date: "2026-05-18",+ total_seconds: 0,+ task_count: 4,+ failed_count: 1,+ cancelled_count: 1,+ },+ {+ date: "2026-05-17",+ total_seconds: 0,+ task_count: 3,+ failed_count: 0,+ cancelled_count: 3,+ },+ ]);+ expect(result.map((r) => r.date)).toEqual(["2026-05-17", "2026-05-18"]);+ expect(result[0]).toMatchObject({ completed: 0, failed: 0, cancelled: 3 });+ expect(result[1]).toMatchObject({ completed: 2, failed: 1, cancelled: 1 });+ });++ // An older backend omits cancelled_count; the schema defaults it to 0, and+ // the segment math must degrade to the previous two-way split rather than+ // driving `completed` negative.+ it("clamps completed at zero when the counts overrun task_count", () => {+ const result = aggregateDailyTasks([+ {+ date: "2026-05-18",+ total_seconds: 0,+ task_count: 1,+ failed_count: 1,+ cancelled_count: 1,+ },+ ]);+ expect(result[0]).toMatchObject({ completed: 0, failed: 1, cancelled: 1 });+ });});// ---------------------------------------------------------------------------diff --git a/packages/views/dashboard/utils.ts b/packages/views/dashboard/utils.tsindex 392c8677df..82185d3526 100644--- a/packages/views/dashboard/utils.ts+++ b/packages/views/dashboard/utils.ts@@ -390,21 +390,32 @@ export function aggregateWeeklyTasks(weekCount: number,): WeeklyTasksData[] {const shells = buildWeekShells(tz, weekCount);- const buckets = new Map<string, { completed: number; failed: number }>();+ const buckets = new Map<+ string,+ { completed: number; failed: number; cancelled: number }+ >();for (const shell of shells)- buckets.set(shell.weekStart, { completed: 0, failed: 0 });+ buckets.set(shell.weekStart, { completed: 0, failed: 0, cancelled: 0 });for (const r of rows) {const wkStart = weekStartIso(r.date);const bucket = buckets.get(wkStart);if (!bucket) continue;const failed = r.failed_count;- const completed = Math.max(0, r.task_count - failed);+ const cancelled = r.cancelled_count;+ const completed = Math.max(0, r.task_count - failed - cancelled);bucket.completed += completed;bucket.failed += failed;+ bucket.cancelled += cancelled;}return shells.map((s) => {- const b = buckets.get(s.weekStart) ?? { completed: 0, failed: 0 };- return { ...s, completed: b.completed, failed: b.failed };+ const b =+ buckets.get(s.weekStart) ?? { completed: 0, failed: 0, cancelled: 0 };+ return {+ ...s,+ completed: b.completed,+ failed: b.failed,+ cancelled: b.cancelled,+ };});}@@ -420,19 +431,23 @@ export function aggregateDailyTime(rows: DashboardRunTimeDaily[]): DailyTimeData}));}-// Per-date run-time rows → one row per date with `completed` and `failed`-// counts for the DailyTasksChart's stacked bar (failed_count is a subset-// of task_count, so completed = task_count - failed_count).+// Per-date run-time rows → one row per date with `completed`, `failed` and+// `cancelled` counts for the DailyTasksChart's stacked bar. failed_count and+// cancelled_count are disjoint subsets of task_count, so the succeeded count+// is the remainder. Subtracting cancelled matters: without it a run the user+// stopped would render in the green "completed" segment.export function aggregateDailyTasks(rows: DashboardRunTimeDaily[]): DailyTasksData[] {return rows.toSorted((a, b) => a.date.localeCompare(b.date)).map((r) => {const failed = r.failed_count;- const completed = Math.max(0, r.task_count - failed);+ const cancelled = r.cancelled_count;+ const completed = Math.max(0, r.task_count - failed - cancelled);return {date: r.date,label: formatDateLabel(r.date),completed,failed,+ cancelled,};});}diff --git a/packages/views/runtimes/components/charts/daily-tasks-chart.tsx b/packages/views/runtimes/components/charts/daily-tasks-chart.tsxindex 2a998f7651..395ee049cf 100644--- a/packages/views/runtimes/components/charts/daily-tasks-chart.tsx+++ b/packages/views/runtimes/components/charts/daily-tasks-chart.tsx@@ -13,11 +13,13 @@ import {} from "@multica/ui/components/ui/chart";import { useT } from "../../../i18n";-// Two-segment stack — completed runs at the bottom (chart-1, primary-// brand), failed runs on top (chart-5 for distinct emphasis). Lets the-// user see day-over-day failure-rate trend without a separate chart.+// Three-segment stack — completed runs at the bottom (chart-1, primary+// brand), then cancelled (chart-3, muted: a manual stop is an outcome, not+// an error), failed on top (chart-5 for distinct emphasis). Lets the user+// see day-over-day failure-rate trend without a separate chart.const tasksChartConfig = {completed: { label: "Completed", color: "var(--chart-1)" },+ cancelled: { label: "Cancelled", color: "var(--chart-3)" },failed: { label: "Failed", color: "var(--chart-5)" },} satisfies ChartConfig;@@ -26,6 +28,7 @@ export interface DailyTasksData {label: string;completed: number;failed: number;+ cancelled: number;}export function DailyTasksChart({ data }: { data: DailyTasksData[] }) {@@ -77,6 +80,12 @@ export function DailyTasksChart({ data }: { data: DailyTasksData[] }) {fill="var(--color-completed)"radius={[0, 0, 0, 0]}/>+ <Bar+ dataKey="cancelled"+ stackId="tasks"+ fill="var(--color-cancelled)"+ radius={[0, 0, 0, 0]}+ /><BardataKey="failed"stackId="tasks"diff --git a/packages/views/runtimes/components/charts/weekly-tasks-chart.tsx b/packages/views/runtimes/components/charts/weekly-tasks-chart.tsxindex dcc1438827..5f2dead8a3 100644--- a/packages/views/runtimes/components/charts/weekly-tasks-chart.tsx+++ b/packages/views/runtimes/components/charts/weekly-tasks-chart.tsx@@ -14,12 +14,13 @@ import {} from "@multica/ui/components/ui/chart";import { useT } from "../../../i18n";-// Weekly counterpart of DailyTasksChart — same completed/failed stacked-// bar, but each bar groups a Mon–Sun calendar week. Partial-week bars at-// half opacity match WeeklyCostChart / WeeklyTokensChart so the in-progress-// week reads as visually subordinate everywhere.+// Weekly counterpart of DailyTasksChart — same completed/cancelled/failed+// stacked bar, but each bar groups a Mon–Sun calendar week. Partial-week+// bars at half opacity match WeeklyCostChart / WeeklyTokensChart so the+// in-progress week reads as visually subordinate everywhere.const weeklyTasksChartConfig = {completed: { label: "Completed", color: "var(--chart-1)" },+ cancelled: { label: "Cancelled", color: "var(--chart-3)" },failed: { label: "Failed", color: "var(--chart-5)" },} satisfies ChartConfig;@@ -32,6 +33,7 @@ export interface WeeklyTasksData {daysCovered: number;completed: number;failed: number;+ cancelled: number;}export function WeeklyTasksChart({ data }: { data: WeeklyTasksData[] }) {@@ -102,6 +104,16 @@ export function WeeklyTasksChart({ data }: { data: WeeklyTasksData[] }) {<Cell key={`${d.weekStart}-c`} fillOpacity={d.partial ? 0.5 : 1} />))}</Bar>+ <Bar+ dataKey="cancelled"+ stackId="tasks"+ fill="var(--color-cancelled)"+ radius={[0, 0, 0, 0]}+ >+ {data.map((d) => (+ <Cell key={`${d.weekStart}-x`} fillOpacity={d.partial ? 0.5 : 1} />+ ))}+ </Bar><BardataKey="failed"stackId="tasks"diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 1e9ba7671a..829e5c72a5 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -54,10 +54,16 @@ type preMigrationHook func(ctx context.Context, pool *pgxpool.Pool) error// failed build can leave an INVALID relation that IF NOT EXISTS would otherwise// mistake for a successful retry. The hook removes only that invalid leftover;// migration 257 can then rebuild it while the valid v1 index remains in place.+//+// MUL-5823: migration 261 replaces the terminal-task partial index the same+// way, so it carries the same hazard — an INVALID v2 leftover recorded as+// success would let migration 262 drop the still-valid v1, leaving all four+// dashboard rollups on a full table scan.var preMigrationHooks = map[string]preMigrationHook{"103_drop_legacy_daily_rollups": runTaskUsageHourlyHook,"198_agent_task_attribution_strict_constraint_validate": runAttributionStrictHook,"257_agent_task_queue_channel_media_pending_unique_v2": cleanupInvalidConcurrentIndexHook("idx_one_pending_task_per_issue_agent_v2"),+ "261_agent_task_queue_terminal_completed_at_v2": cleanupInvalidConcurrentIndexHook("idx_agent_task_queue_terminal_completed_at_v2"),}// cleanupInvalidConcurrentIndexHook removes an INVALID index left by andiff --git a/server/cmd/migrate/migrate_invalid_index_test.go b/server/cmd/migrate/migrate_invalid_index_test.goindex 474b042166..769fd941d9 100644--- a/server/cmd/migrate/migrate_invalid_index_test.go+++ b/server/cmd/migrate/migrate_invalid_index_test.go@@ -96,6 +96,171 @@ func TestRunMigrationsRepairsInvalidConcurrentIndexBeforeRetry(t *testing.T) {}}+// TestRunMigrationsRepairsInvalidTerminalCompletedAtIndex is the MUL-5823+// counterpart of the test above, for the 261/262 partial-index swap.+//+// The hazard is identical but the blast radius is different: 261 builds the+// replacement terminal-task index and 262 drops the v1 it replaces. If an+// interrupted 261 leaves an INVALID v2, `CREATE INDEX ... IF NOT EXISTS`+// reports success on retry, the runner records 261, and 262 then drops the+// only valid index — putting all four dashboard rollups on a full table scan.+//+// Unlike migration 257's unique index, this one cannot be failed with a+// duplicate row, so the build is interrupted the way a real one is: a+// concurrent open transaction blocks the wait phase until statement_timeout+// cancels it, which is exactly what leaves indisvalid = false behind.+func TestRunMigrationsRepairsInvalidTerminalCompletedAtIndex(t *testing.T) {+ pool := openTestPool(t)+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ defer cancel()++ suffix := fmt.Sprintf("%d_%d", time.Now().UnixNano(), rand.Uint32())+ schema := "migrate_terminal_idx_" + suffix+ schemaIdent := pgx.Identifier{schema}.Sanitize()+ if _, err := pool.Exec(ctx, "CREATE SCHEMA "+schemaIdent); err != nil {+ t.Fatalf("create schema: %v", err)+ }+ t.Cleanup(func() {+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cleanupCancel()+ if _, err := pool.Exec(cleanupCtx, "DROP SCHEMA IF EXISTS "+schemaIdent+" CASCADE"); err != nil {+ t.Logf("drop schema %s: %v", schema, err)+ }+ })++ const (+ v1Index = "idx_agent_task_queue_terminal_completed_at"+ v2Index = "idx_agent_task_queue_terminal_completed_at_v2"+ )+ tableName := pgx.Identifier{schema, "agent_task_queue"}.Sanitize()+ if _, err := pool.Exec(ctx, "CREATE TABLE "+tableName+` (+ id BIGSERIAL PRIMARY KEY,+ status TEXT NOT NULL,+ completed_at TIMESTAMPTZ+ )`); err != nil {+ t.Fatalf("create task table: %v", err)+ }+ if _, err := pool.Exec(ctx, "CREATE INDEX CONCURRENTLY "+pgx.Identifier{v1Index}.Sanitize()++ " ON "+tableName+" (completed_at) WHERE status IN ('completed', 'failed')"); err != nil {+ t.Fatalf("create valid v1 index: %v", err)+ }++ createV2 := "CREATE INDEX CONCURRENTLY IF NOT EXISTS " + pgx.Identifier{v2Index}.Sanitize() ++ " ON " + tableName + " (completed_at) WHERE status IN ('completed', 'failed', 'cancelled')"++ // Blocker: an open transaction that has written to the table owns an xid+ // the concurrent build must wait on, so the build is guaranteed to reach+ // its wait phase rather than finishing first.+ blocker, err := pool.Acquire(ctx)+ if err != nil {+ t.Fatalf("acquire blocker conn: %v", err)+ }+ blockerTx, err := blocker.Begin(ctx)+ if err != nil {+ blocker.Release()+ t.Fatalf("begin blocker tx: %v", err)+ }+ if _, err := blockerTx.Exec(ctx, "INSERT INTO "+tableName+" (status, completed_at) VALUES ('completed', now())"); err != nil {+ blocker.Release()+ t.Fatalf("blocker insert: %v", err)+ }++ builder, err := pool.Acquire(ctx)+ if err != nil {+ blocker.Release()+ t.Fatalf("acquire builder conn: %v", err)+ }+ // SET must ride the same connection as the build, and must be its own+ // protocol message — a multi-command string would put CREATE INDEX+ // CONCURRENTLY in an implicit transaction, which PostgreSQL rejects.+ if _, err := builder.Exec(ctx, "SET statement_timeout = '2s'"); err != nil {+ builder.Release()+ blocker.Release()+ t.Fatalf("set statement_timeout: %v", err)+ }+ _, buildErr := builder.Exec(ctx, createV2)+ // Clear the timeout before the connection goes back to the pool; pgxpool+ // does not reset session state, so leaving it set would arm a 2s fuse on+ // whichever later caller happens to draw this connection.+ if _, err := builder.Exec(ctx, "SET statement_timeout = DEFAULT"); err != nil {+ t.Logf("reset statement_timeout: %v", err)+ }+ builder.Release()+ if buildErr == nil {+ blocker.Release()+ t.Fatal("interrupted v2 build unexpectedly succeeded")+ }+ _ = blockerTx.Rollback(ctx)+ blocker.Release()++ assertIndexValidity(t, pool, schema, v1Index, true)+ assertIndexValidity(t, pool, schema, v2Index, false)++ // Guard the premise: without the hook, the retry is a silent no-op that+ // leaves the index invalid. This is what makes dropping v1 unsafe.+ if _, err := pool.Exec(ctx, createV2); err != nil {+ t.Fatalf("bare retry should report success: %v", err)+ }+ assertIndexValidity(t, pool, schema, v2Index, false)++ // The production hook names the index unqualified, which resolves against+ // the search_path — correct in production where it lives in public, but+ // invisible from this test's private schema. So assert the registration+ // exists, then run with a schema-qualified instance of the same hook.+ const version = "261_agent_task_queue_terminal_completed_at_v2"+ if preMigrationHooks[version] == nil {+ t.Fatalf("production hook is not registered for %s", version)+ }+ dir := t.TempDir()+ upPath := filepath.Join(dir, version+".up.sql")+ if err := os.WriteFile(upPath, []byte(createV2+";\n"), 0o600); err != nil {+ t.Fatalf("write retry migration: %v", err)+ }+ opts := runOptions{+ Direction: "up",+ Files: []string{upPath},+ SchemaMigrationsTable: schema + ".schema_migrations",+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,+ Hooks: map[string]preMigrationHook{+ version: cleanupInvalidConcurrentIndexHook(pgx.Identifier{schema, v2Index}.Sanitize()),+ },+ }+ if err := runMigrations(ctx, pool, opts); err != nil {+ t.Fatalf("retry migration with invalid-index cleanup: %v", err)+ }++ // v2 rebuilt for real, and v1 still standing to cover the window.+ assertIndexValidity(t, pool, schema, v1Index, true)+ assertIndexValidity(t, pool, schema, v2Index, true)++ // Only now is migration 262 safe: it drops v1 and the workspace is left+ // with a valid index rather than none.+ const dropVersion = "262_drop_agent_task_queue_terminal_completed_at_v1"+ dropPath := filepath.Join(dir, dropVersion+".up.sql")+ dropSQL := "DROP INDEX CONCURRENTLY IF EXISTS " + pgx.Identifier{schema, v1Index}.Sanitize() + ";\n"+ if err := os.WriteFile(dropPath, []byte(dropSQL), 0o600); err != nil {+ t.Fatalf("write drop migration: %v", err)+ }+ opts.Files = []string{dropPath}+ if err := runMigrations(ctx, pool, opts); err != nil {+ t.Fatalf("apply v1 drop: %v", err)+ }+ assertIndexValidity(t, pool, schema, v2Index, true)+ var v1Exists bool+ if err := pool.QueryRow(ctx, `+ SELECT EXISTS (+ SELECT 1 FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = $1 AND c.relname = $2+ )+ `, schema, v1Index).Scan(&v1Exists); err != nil {+ t.Fatalf("check v1 existence: %v", err)+ }+ if v1Exists {+ t.Fatal("migration 262 should have dropped v1")+ }+}+func assertIndexValidity(t *testing.T, pool interface {QueryRow(context.Context, string, ...any) pgx.Row}, schema, index string, want bool) {diff --git a/server/internal/handler/dashboard.go b/server/internal/handler/dashboard.goindex 98c1ade372..1b2c41de3c 100644--- a/server/internal/handler/dashboard.go+++ b/server/internal/handler/dashboard.go@@ -363,18 +363,21 @@ func (h *Handler) listDashboardUsageByAgent(}// DashboardAgentRunTimeResponse is one agent's total terminal-task run time-// over the window. Includes failed tasks so the dashboard can surface how-// much execution time was spent on runs that didn't succeed.+// over the window. Includes failed and cancelled tasks so the dashboard can+// surface how much execution time was spent on runs that didn't succeed.+// FailedCount and CancelledCount are disjoint subsets of TaskCount; the+// client derives the succeeded count as the remainder.type DashboardAgentRunTimeResponse struct {- AgentID string `json:"agent_id"`- TotalSeconds int64 `json:"total_seconds"`- TaskCount int32 `json:"task_count"`- FailedCount int32 `json:"failed_count"`+ AgentID string `json:"agent_id"`+ TotalSeconds int64 `json:"total_seconds"`+ TaskCount int32 `json:"task_count"`+ FailedCount int32 `json:"failed_count"`+ CancelledCount int32 `json:"cancelled_count"`}// GetDashboardAgentRunTime returns per-agent total task run time (seconds)// and task counts for the workspace, optionally scoped to a project. Only-// terminal tasks (completed or failed) with both started_at and+// terminal tasks (completed, failed, or cancelled) with both started_at and// completed_at populated contribute, since queued/running tasks have no// finite duration.func (h *Handler) GetDashboardAgentRunTime(w http.ResponseWriter, r *http.Request) {@@ -414,10 +417,11 @@ func (h *Handler) GetDashboardAgentRunTime(w http.ResponseWriter, r *http.Requesresp := make([]DashboardAgentRunTimeResponse, len(rows))for i, row := range rows {resp[i] = DashboardAgentRunTimeResponse{- AgentID: uuidToString(row.AgentID),- TotalSeconds: row.TotalSeconds,- TaskCount: row.TaskCount,- FailedCount: row.FailedCount,+ AgentID: uuidToString(row.AgentID),+ TotalSeconds: row.TotalSeconds,+ TaskCount: row.TaskCount,+ FailedCount: row.FailedCount,+ CancelledCount: row.CancelledCount,}}writeJSON(w, http.StatusOK, foldRestrictedAgentRunTime(resp, restricted))@@ -441,6 +445,7 @@ func foldRestrictedAgentRunTime(dst.TotalSeconds += src.TotalSecondsdst.TaskCount += src.TaskCountdst.FailedCount += src.FailedCount+ dst.CancelledCount += src.CancelledCountreturn dst},)@@ -448,19 +453,21 @@ func foldRestrictedAgentRunTime(// DashboardRunTimeDailyResponse is one (date) bucket of terminal-task run// time and counts. Powers the workspace dashboard's daily Time and Tasks-// charts — same toggle as Tokens / Cost, different metric.+// charts — same toggle as Tokens / Cost, different metric. FailedCount and+// CancelledCount are disjoint subsets of TaskCount.type DashboardRunTimeDailyResponse struct {- Date string `json:"date"`- TotalSeconds int64 `json:"total_seconds"`- TaskCount int32 `json:"task_count"`- FailedCount int32 `json:"failed_count"`+ Date string `json:"date"`+ TotalSeconds int64 `json:"total_seconds"`+ TaskCount int32 `json:"task_count"`+ FailedCount int32 `json:"failed_count"`+ CancelledCount int32 `json:"cancelled_count"`}// GetDashboardRunTimeDaily returns per-date total task run time and task// counts for the workspace, optionally scoped to a project. Only terminal-// tasks (completed or failed) with both started_at and completed_at-// populated contribute. Bucketed by completed_at so the day boundaries-// line up with the per-agent run-time card.+// tasks (completed, failed, or cancelled) with both started_at and+// completed_at populated contribute. Bucketed by completed_at so the day+// boundaries line up with the per-agent run-time card.func (h *Handler) GetDashboardRunTimeDaily(w http.ResponseWriter, r *http.Request) {workspaceID := h.resolveWorkspaceID(r)if _, ok := h.workspaceMember(w, r, workspaceID); !ok {@@ -489,10 +496,11 @@ func (h *Handler) GetDashboardRunTimeDaily(w http.ResponseWriter, r *http.Requesresp := make([]DashboardRunTimeDailyResponse, len(rows))for i, row := range rows {resp[i] = DashboardRunTimeDailyResponse{- Date: row.Date.Time.Format("2006-01-02"),- TotalSeconds: row.TotalSeconds,- TaskCount: row.TaskCount,- FailedCount: row.FailedCount,+ Date: row.Date.Time.Format("2006-01-02"),+ TotalSeconds: row.TotalSeconds,+ TaskCount: row.TaskCount,+ FailedCount: row.FailedCount,+ CancelledCount: row.CancelledCount,}}writeJSON(w, http.StatusOK, resp)diff --git a/server/internal/handler/dashboard_test.go b/server/internal/handler/dashboard_test.goindex 6822029359..b333a8b9ec 100644--- a/server/internal/handler/dashboard_test.go+++ b/server/internal/handler/dashboard_test.go@@ -424,6 +424,107 @@ func TestDashboardRunTimeDailyBucketsByViewerTimezone(t *testing.T) {}}+// TestDashboardRunTimeCountsCancelledRuns pins the fix for the run-time+// rollups dropping every run the user stopped mid-flight. CancelAgentTask+// accepts a 'running' task, so a cancelled row can carry both started_at and+// completed_at — real agent occupancy, and real tokens the cost rollup+// charges for regardless of status. The old `status IN ('completed','failed')`+// filter zeroed that time, so Time/Tasks and Cost/Tokens summed different+// task populations on the same dashboard.+//+// Also asserts the other half of the contract: a run cancelled while still+// queued (started_at NULL) must stay out, since it never occupied an agent.+func TestDashboardRunTimeCountsCancelledRuns(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var runtimeID, agentID string+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {+ t.Fatalf("fetch runtime: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {+ t.Fatalf("fetch agent: %v", err)+ }++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)+ VALUES ($1, 'run-time cancelled test', $2, 'member',+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })++ // Baseline before inserting, so a shared fixture DB with pre-existing+ // rows can't make the deltas below pass or fail spuriously.+ baseSeconds, baseTasks, baseCancelled := readAgentRunTime(t, agentID)++ // Stopped 15 minutes into the run: started_at and completed_at both set.+ var cancelledTaskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, started_at, completed_at, created_at)+ VALUES ($1, $2, $3, 'cancelled', now() - interval '15 minutes', now(), now())+ RETURNING id+ `, agentID, issueID, runtimeID).Scan(&cancelledTaskID); err != nil {+ t.Fatalf("insert cancelled task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, cancelledTaskID) })++ // Cancelled from the queue: never started, so it must not contribute.+ var queuedCancelID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, started_at, completed_at, created_at)+ VALUES ($1, $2, $3, 'cancelled', NULL, now(), now())+ RETURNING id+ `, agentID, issueID, runtimeID).Scan(&queuedCancelID); err != nil {+ t.Fatalf("insert queue-cancelled task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, queuedCancelID) })++ gotSeconds, gotTasks, gotCancelled := readAgentRunTime(t, agentID)++ // 15 minutes of occupancy, from exactly one of the two rows.+ if delta := gotSeconds - baseSeconds; delta < 890 || delta > 910 {+ t.Errorf("total_seconds delta = %d, want ~900 (15m from the stopped run only)", delta)+ }+ if delta := gotTasks - baseTasks; delta != 1 {+ t.Errorf("task_count delta = %d, want 1 (the queue-cancelled run must not count)", delta)+ }+ if delta := gotCancelled - baseCancelled; delta != 1 {+ t.Errorf("cancelled_count delta = %d, want 1", delta)+ }+}++// readAgentRunTime returns (total_seconds, task_count, cancelled_count) for+// one agent from GetDashboardAgentRunTime. Zeroes when the agent has no row.+func readAgentRunTime(t *testing.T, agentID string) (int64, int32, int32) {+ t.Helper()+ w := httptest.NewRecorder()+ testHandler.GetDashboardAgentRunTime(w, newRequest("GET", "/api/dashboard/agent-runtime?days=10&tz=UTC", nil))+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var rows []struct {+ AgentID string `json:"agent_id"`+ TotalSeconds int64 `json:"total_seconds"`+ TaskCount int32 `json:"task_count"`+ CancelledCount int32 `json:"cancelled_count"`+ }+ if err := json.NewDecoder(w.Body).Decode(&rows); err != nil {+ t.Fatalf("decode agent run time: %v", err)+ }+ for _, r := range rows {+ if r.AgentID == agentID {+ return r.TotalSeconds, r.TaskCount, r.CancelledCount+ }+ }+ return 0, 0, 0+}+// TestRollupTaskUsageHourlyIdempotentAndWatermark covers two pipeline// invariants the deleted runtime_rollup_test.go used to guard for the// legacy daily rollup: (1) re-running the window function over the samediff --git a/server/migrations/261_agent_task_queue_terminal_completed_at_v2.down.sql b/server/migrations/261_agent_task_queue_terminal_completed_at_v2.down.sqlnew file mode 100644index 0000000000..5706d9e72e--- /dev/null+++ b/server/migrations/261_agent_task_queue_terminal_completed_at_v2.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_terminal_completed_at_v2;diff --git a/server/migrations/261_agent_task_queue_terminal_completed_at_v2.up.sql b/server/migrations/261_agent_task_queue_terminal_completed_at_v2.up.sqlnew file mode 100644index 0000000000..01853f89d5--- /dev/null+++ b/server/migrations/261_agent_task_queue_terminal_completed_at_v2.up.sql@@ -0,0 +1,22 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+--+-- Supersedes idx_agent_task_queue_terminal_completed_at (migration 231). The+-- run-time rollups now also count runs the user stopped mid-flight, so their+-- status filter reads `IN ('completed','failed','cancelled')`. A partial+-- index is only usable when the planner can prove the query's predicate+-- implies the index predicate, and the v1 two-status predicate cannot cover+-- a three-status filter — leaving those rollups on a full scan of a table+-- whose lifetime row count dwarfs any 30-day window.+--+-- Widening the predicate rather than dropping it keeps the index off the+-- queued / dispatched / running rows that the hot dispatch path churns: a+-- row still enters this index exactly once, when it reaches a terminal state.+--+-- The two failure rollups (ListDashboardFailuresDaily / ...ByAgent) keep the+-- two-status filter on purpose — a manual stop is not a failure and must not+-- dilute the error rate. They stay index-eligible regardless, since their+-- narrower predicate implies this wider one.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_terminal_completed_at_v2+ ON agent_task_queue (completed_at)+ WHERE status IN ('completed', 'failed', 'cancelled');diff --git a/server/migrations/262_drop_agent_task_queue_terminal_completed_at_v1.down.sql b/server/migrations/262_drop_agent_task_queue_terminal_completed_at_v1.down.sqlnew file mode 100644index 0000000000..40d36decfa--- /dev/null+++ b/server/migrations/262_drop_agent_task_queue_terminal_completed_at_v1.down.sql@@ -0,0 +1,7 @@+-- Recreate v1 before migration 261's down step removes v2.+-- Do not use IF NOT EXISTS here: pre-migration hooks only run in the `up`+-- direction, so a leftover INVALID v1 must fail closed while the valid v2+-- index remains in place instead of being recorded as restored.+CREATE INDEX CONCURRENTLY idx_agent_task_queue_terminal_completed_at+ ON agent_task_queue (completed_at)+ WHERE status IN ('completed', 'failed');diff --git a/server/migrations/262_drop_agent_task_queue_terminal_completed_at_v1.up.sql b/server/migrations/262_drop_agent_task_queue_terminal_completed_at_v1.up.sqlnew file mode 100644index 0000000000..a331e3081d--- /dev/null+++ b/server/migrations/262_drop_agent_task_queue_terminal_completed_at_v1.up.sql@@ -0,0 +1,5 @@+-- Drop the superseded two-status partial index now that v2 is available.+--+-- Kept separate from migration 261 so both files contain exactly one+-- concurrent index statement and no rollout window is left without coverage.+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_terminal_completed_at;diff --git a/server/pkg/db/generated/task_usage.sql.go b/server/pkg/db/generated/task_usage.sql.goindex 9295a8af97..29336f6a2e 100644--- a/server/pkg/db/generated/task_usage.sql.go+++ b/server/pkg/db/generated/task_usage.sql.go@@ -105,12 +105,13 @@ SELECT0)::bigint AS total_seconds,COUNT(*)::int AS task_count,- COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count+ COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count,+ COUNT(*) FILTER (WHERE atq.status = 'cancelled')::int AS cancelled_countFROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idLEFT JOIN issue i ON i.id = atq.issue_idWHERE a.workspace_id = $1- AND atq.status IN ('completed', 'failed')+ AND atq.status IN ('completed', 'failed', 'cancelled')AND atq.started_at IS NOT NULLAND atq.completed_at IS NOT NULLAND atq.completed_at >= $2::timestamptz@@ -126,17 +127,21 @@ type ListDashboardAgentRunTimeParams struct {}type ListDashboardAgentRunTimeRow struct {- AgentID pgtype.UUID `json:"agent_id"`- TotalSeconds int64 `json:"total_seconds"`- TaskCount int32 `json:"task_count"`- FailedCount int32 `json:"failed_count"`+ AgentID pgtype.UUID `json:"agent_id"`+ TotalSeconds int64 `json:"total_seconds"`+ TaskCount int32 `json:"task_count"`+ FailedCount int32 `json:"failed_count"`+ CancelledCount int32 `json:"cancelled_count"`}// Per-agent total task run time and task count for the workspace, optionally-// scoped to a single project. Counts only terminal runs (completed or failed)-// with both started_at and completed_at populated — queued/running tasks have-// no finite duration. Anchored on completed_at so the window matches the-// token cost window (which is anchored on tu.created_at, ~= completion time).+// scoped to a single project. Counts only terminal runs (completed, failed,+// or cancelled) with both started_at and completed_at populated — queued/+// running tasks have no finite duration. Anchored on completed_at so the+// window matches the token cost window (which is anchored on tu.created_at,+// ~= completion time).+//+// See ListDashboardRunTimeDaily for why 'cancelled' belongs in the filter.//// No date bucketing, so no @tz — but @since is the viewer's local// start-of-day for the EXACT N-day window (parseExactSinceParamInTZ), so the@@ -157,6 +162,7 @@ func (q *Queries) ListDashboardAgentRunTime(ctx context.Context, arg ListDashboa&i.TotalSeconds,&i.TaskCount,&i.FailedCount,+ &i.CancelledCount,); err != nil {return nil, err}@@ -316,12 +322,13 @@ SELECT0)::bigint AS total_seconds,COUNT(*)::int AS task_count,- COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count+ COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count,+ COUNT(*) FILTER (WHERE atq.status = 'cancelled')::int AS cancelled_countFROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idLEFT JOIN issue i ON i.id = atq.issue_idWHERE a.workspace_id = $1- AND atq.status IN ('completed', 'failed')+ AND atq.status IN ('completed', 'failed', 'cancelled')AND atq.started_at IS NOT NULLAND atq.completed_at IS NOT NULLAND atq.completed_at >= $3::timestamptz@@ -338,10 +345,11 @@ type ListDashboardRunTimeDailyParams struct {}type ListDashboardRunTimeDailyRow struct {- Date pgtype.Date `json:"date"`- TotalSeconds int64 `json:"total_seconds"`- TaskCount int32 `json:"task_count"`- FailedCount int32 `json:"failed_count"`+ Date pgtype.Date `json:"date"`+ TotalSeconds int64 `json:"total_seconds"`+ TaskCount int32 `json:"task_count"`+ FailedCount int32 `json:"failed_count"`+ CancelledCount int32 `json:"cancelled_count"`}// Daily per-date run time + task counts for the workspace, optionally@@ -351,8 +359,16 @@ type ListDashboardRunTimeDailyRow struct {// caller-supplied @tz — same Viewing-tz treatment as ListDashboardUsageDaily// so the Time / Tasks tabs cut their day boundary identically to the// Cost / Tokens tabs (a viewer east of UTC would otherwise see the four-// tabs disagree on a "1d" window). Only terminal tasks (completed or-// failed) with both started_at and completed_at populated contribute.+// tabs disagree on a "1d" window). Only terminal tasks (completed, failed,+// or cancelled) with both started_at and completed_at populated contribute.+//+// 'cancelled' is in the filter because a run the user stopped mid-flight+// burned real agent time and real tokens before the stop landed+// (CancelAgentTask accepts 'running'). Excluding it zeroed that time while+// the cost rollup — which has no status filter at all — kept charging for+// it, so Time/Tasks and Cost/Tokens were summing different task populations+// on the same page. The started_at guard keeps a run cancelled while still+// queued out: it never occupied an agent.//// @since is already the viewer's local start-of-day-(N) (parseSinceParamInTZ)// — passed straight through, NOT re-truncated; see ListDashboardUsageDaily.@@ -375,6 +391,7 @@ func (q *Queries) ListDashboardRunTimeDaily(ctx context.Context, arg ListDashboa&i.TotalSeconds,&i.TaskCount,&i.FailedCount,+ &i.CancelledCount,); err != nil {return nil, err}diff --git a/server/pkg/db/queries/task_usage.sql b/server/pkg/db/queries/task_usage.sqlindex b2bbaa076b..89084c8ab4 100644--- a/server/pkg/db/queries/task_usage.sql+++ b/server/pkg/db/queries/task_usage.sql@@ -148,8 +148,16 @@ ORDER BY agent_id, LOWER(provider), model;-- caller-supplied @tz — same Viewing-tz treatment as ListDashboardUsageDaily-- so the Time / Tasks tabs cut their day boundary identically to the-- Cost / Tokens tabs (a viewer east of UTC would otherwise see the four--- tabs disagree on a "1d" window). Only terminal tasks (completed or--- failed) with both started_at and completed_at populated contribute.+-- tabs disagree on a "1d" window). Only terminal tasks (completed, failed,+-- or cancelled) with both started_at and completed_at populated contribute.+--+-- 'cancelled' is in the filter because a run the user stopped mid-flight+-- burned real agent time and real tokens before the stop landed+-- (CancelAgentTask accepts 'running'). Excluding it zeroed that time while+-- the cost rollup — which has no status filter at all — kept charging for+-- it, so Time/Tasks and Cost/Tokens were summing different task populations+-- on the same page. The started_at guard keeps a run cancelled while still+-- queued out: it never occupied an agent.---- @since is already the viewer's local start-of-day-(N) (parseSinceParamInTZ)-- — passed straight through, NOT re-truncated; see ListDashboardUsageDaily.@@ -160,12 +168,13 @@ SELECT0)::bigint AS total_seconds,COUNT(*)::int AS task_count,- COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count+ COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count,+ COUNT(*) FILTER (WHERE atq.status = 'cancelled')::int AS cancelled_countFROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idLEFT JOIN issue i ON i.id = atq.issue_idWHERE a.workspace_id = $1- AND atq.status IN ('completed', 'failed')+ AND atq.status IN ('completed', 'failed', 'cancelled')AND atq.started_at IS NOT NULLAND atq.completed_at IS NOT NULLAND atq.completed_at >= sqlc.arg('since')::timestamptz@@ -175,10 +184,13 @@ ORDER BY DATE(atq.completed_at AT TIME ZONE sqlc.arg('tz')::text) DESC;-- name: ListDashboardAgentRunTime :many-- Per-agent total task run time and task count for the workspace, optionally--- scoped to a single project. Counts only terminal runs (completed or failed)--- with both started_at and completed_at populated — queued/running tasks have--- no finite duration. Anchored on completed_at so the window matches the--- token cost window (which is anchored on tu.created_at, ~= completion time).+-- scoped to a single project. Counts only terminal runs (completed, failed,+-- or cancelled) with both started_at and completed_at populated — queued/+-- running tasks have no finite duration. Anchored on completed_at so the+-- window matches the token cost window (which is anchored on tu.created_at,+-- ~= completion time).+--+-- See ListDashboardRunTimeDaily for why 'cancelled' belongs in the filter.---- No date bucketing, so no @tz — but @since is the viewer's local-- start-of-day for the EXACT N-day window (parseExactSinceParamInTZ), so the@@ -192,12 +204,13 @@ SELECT0)::bigint AS total_seconds,COUNT(*)::int AS task_count,- COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count+ COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count,+ COUNT(*) FILTER (WHERE atq.status = 'cancelled')::int AS cancelled_countFROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idLEFT JOIN issue i ON i.id = atq.issue_idWHERE a.workspace_id = $1- AND atq.status IN ('completed', 'failed')+ AND atq.status IN ('completed', 'failed', 'cancelled')AND atq.started_at IS NOT NULLAND atq.completed_at IS NOT NULLAND atq.completed_at >= @since::timestamptz