Skip to content

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

Go

fix(usage): close the per-agent rollup windows so the leaderboard cannot exceed the totals (MUL-5551) (#6194)

Multica Evee6610c08310b
diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsx
index 9bb0f97d67..3eae62cbac 100644
--- a/packages/views/dashboard/components/dashboard-page.tsx
+++ b/packages/views/dashboard/components/dashboard-page.tsx
@@ -284,6 +284,13 @@ export function DashboardPage() {
const dailyQuery = useQuery(
dashboardUsageDailyOptions(wsId, chartFetchDays, projectId, viewTZ),
);
+ // The three per-agent rollups carry no date, so `dailyCutoffIso` below
+ // cannot trim them — their window is closed server-side at exactly `days`
+ // calendar buckets (parseExactSinceParamInTZ). Anything derived from these
+ // three is therefore already on the same span as the trimmed daily series;
+ // do NOT put a per-agent rollup back on the N+1 cutoff, or the leaderboard
+ // and the Run time / Tasks KPIs silently widen by one day while the chart
+ // and the Cost / Tokens KPIs beside them do not (MUL-5551).
const byAgentQuery = useQuery(
dashboardUsageByAgentOptions(wsId, days, projectId, viewTZ),
);
diff --git a/server/internal/handler/dashboard.go b/server/internal/handler/dashboard.go
index 05f45c11e4..98c1ade372 100644
--- a/server/internal/handler/dashboard.go
+++ b/server/internal/handler/dashboard.go
@@ -25,6 +25,15 @@ import (
// ?project_id=<uuid> to scope the rollup to a single project. With no
// project_id the data spans the whole workspace.
//
+// Cutoff convention: the three date-bucketed series use parseSinceParamInTZ
+// (N+1 calendar days, the surplus day trimmed client-side with `-(days-1)`),
+// and the three per-AGENT rollups use parseExactSinceParamInTZ (exactly N).
+// Rows without a date cannot be trimmed client-side, so serving them off the
+// N+1 cutoff makes the leaderboard and the Run time / Tasks KPIs cover one
+// calendar day more than the chart and the Cost / Tokens KPIs beside them —
+// at 1D that let a single agent's row read higher than the workspace total
+// (MUL-5551). Keep the two halves of each pair on matching windows.
+//
// Cost is computed client-side from a per-model pricing table — the model
// dimension is intentionally preserved on the wire (same convention as the
// per-runtime usage endpoints).
@@ -265,9 +274,15 @@ func (h *Handler) GetDashboardUsageByAgent(w http.ResponseWriter, r *http.Reques
return
}
// "By agent" has no date grouping in the SQL — tz only determines
- // the cutoff boundary, not the bucket axis.
+ // the cutoff boundary, not the bucket axis. Which is exactly why the
+ // cutoff must be the EXACT N-day one: the client trims the surplus day
+ // `parseSinceParamInTZ` hands back with `-(days-1)`, and a response
+ // carrying no date cannot be trimmed that way. On the N+1 cutoff this
+ // leaderboard covered one calendar day more than the Tokens/Cost KPI and
+ // the chart directly above it, so at 1D a single agent's row could read
+ // higher than the workspace total (MUL-5551).
tz := h.resolveViewingTZ(r)
- since := parseSinceParamInTZ(r, 30, tz)
+ since := parseExactSinceParamInTZ(r, 30, tz)
resp, err := h.listDashboardUsageByAgent(r.Context(), parseUUID(workspaceID), since, projectID)
if err != nil {
@@ -377,9 +392,14 @@ func (h *Handler) GetDashboardAgentRunTime(w http.ResponseWriter, r *http.Reques
return
}
// Cutoff in the viewer's tz so the "last N days" window matches the
- // per-agent cost card (GetDashboardUsageByAgent).
+ // per-agent cost card (GetDashboardUsageByAgent). Exact N-day cutoff for
+ // the same reason: these rows carry no date, so the client cannot trim
+ // the extra calendar day `parseSinceParamInTZ` returns. This response
+ // feeds BOTH the leaderboard's Time/Tasks columns and the Run time /
+ // Tasks KPI tiles, so the N+1 cutoff put those two tiles on a wider
+ // window than the Cost / Tokens tiles beside them (MUL-5551).
tz := h.resolveViewingTZ(r)
- since := parseSinceParamInTZ(r, 30, tz)
+ since := parseExactSinceParamInTZ(r, 30, tz)
rows, err := h.Queries.ListDashboardAgentRunTime(r.Context(), db.ListDashboardAgentRunTimeParams{
WorkspaceID: parseUUID(workspaceID),
diff --git a/server/internal/handler/dashboard_test.go b/server/internal/handler/dashboard_test.go
index fec9be0245..6822029359 100644
--- a/server/internal/handler/dashboard_test.go
+++ b/server/internal/handler/dashboard_test.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
"time"
)
@@ -1617,6 +1618,160 @@ func TestDashboardFailuresByAgentUsesExactWindow(t *testing.T) {
}
}
+// TestDashboardPerAgentRollupsUseExactWindow is MUL-5551: the Usage page's
+// leaderboard reported MORE tokens for a single agent than the Tokens KPI
+// reported for the entire workspace.
+//
+// Both halves read the same underlying rows; they disagreed only on the
+// window. usage/daily and runtime/daily are date-bucketed, so the client
+// trims `parseSinceParamInTZ`'s extra calendar day back to `-(days-1)` before
+// computing the KPIs and the chart. usage/by-agent and agent-runtime carry no
+// date, so nothing trimmed them and they kept the whole N+1 span — at days=1
+// that is today PLUS yesterday. One busy agent's two-day total then trivially
+// exceeded the workspace's one-day total.
+//
+// Sibling of TestDashboardFailuresByAgentUsesExactWindow, which pinned the
+// same cutoff for the third date-less rollup. All three now close their own
+// window server-side.
+func TestDashboardPerAgentRollupsUseExactWindow(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, 'per-agent window 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) })
+
+ // A token bucket at noon YESTERDAY, under a provider/model pair no other
+ // fixture uses so the assertion can't be satisfied by ambient rows.
+ // Seeded straight into task_usage_hourly (same shortcut as the tz-bucket
+ // test) — the rollup's own source column is task_usage.created_at, which
+ // is `now()`-defaulted and awkward to backdate.
+ const windowProvider = "exact-window-test"
+ const windowModel = "exact-window-model"
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM task_usage_hourly WHERE runtime_id = $1 AND provider = $2`, runtimeID, windowProvider)
+ })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_usage_hourly (
+ bucket_hour, workspace_id, runtime_id, agent_id, project_id,
+ provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, event_count
+ )
+ VALUES (
+ ((CURRENT_DATE - 1)::timestamp + interval '12 hours') AT TIME ZONE 'UTC',
+ $1, $2, $3, NULL, $4, $5,
+ 7777, 0, 0, 0, 1
+ )
+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_key DO UPDATE
+ SET input_tokens = EXCLUDED.input_tokens
+ `, testWorkspaceID, runtimeID, agentID, windowProvider, windowModel); err != nil {
+ t.Fatalf("seed hourly row: %v", err)
+ }
+
+ // A terminal task that ran for 900s and completed at noon yesterday, for
+ // the agent-runtime half. Noon keeps both fixtures clear of the midnight
+ // edge in either direction.
+ var taskID 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, 'completed',
+ ((CURRENT_DATE - 1)::timestamp + interval '11 hours 45 minutes') AT TIME ZONE 'UTC',
+ ((CURRENT_DATE - 1)::timestamp + interval '12 hours') AT TIME ZONE 'UTC',
+ now()
+ )
+ RETURNING id
+ `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {
+ t.Fatalf("insert task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+
+ seededTokens := func(body []byte) int64 {
+ var rows []struct {
+ AgentID string `json:"agent_id"`
+ Provider string `json:"provider"`
+ Model string `json:"model"`
+ InputTokens int64 `json:"input_tokens"`
+ }
+ if err := json.Unmarshal(body, &rows); err != nil {
+ t.Fatalf("decode by-agent: %v", err)
+ }
+ var n int64
+ for _, r := range rows {
+ if r.Model == windowModel {
+ n += r.InputTokens
+ }
+ }
+ return n
+ }
+ agentSeconds := func(body []byte) int64 {
+ var rows []struct {
+ AgentID string `json:"agent_id"`
+ TotalSeconds int64 `json:"total_seconds"`
+ }
+ if err := json.Unmarshal(body, &rows); err != nil {
+ t.Fatalf("decode agent-runtime: %v", err)
+ }
+ var n int64
+ for _, r := range rows {
+ if r.AgentID == agentID {
+ n += r.TotalSeconds
+ }
+ }
+ return n
+ }
+
+ get := func(path string) []byte {
+ w := httptest.NewRecorder()
+ switch {
+ case strings.HasPrefix(path, "/api/dashboard/usage/by-agent"):
+ testHandler.GetDashboardUsageByAgent(w, newRequest("GET", path, nil))
+ default:
+ testHandler.GetDashboardAgentRunTime(w, newRequest("GET", path, nil))
+ }
+ if w.Code != http.StatusOK {
+ t.Fatalf("%s: expected 200, got %d: %s", path, w.Code, w.Body.String())
+ }
+ return w.Body.Bytes()
+ }
+
+ // days=1 means "today". Neither per-agent rollup may reach yesterday.
+ if got := seededTokens(get("/api/dashboard/usage/by-agent?days=1&tz=UTC")); got != 0 {
+ t.Errorf("days=1 must not reach yesterday's tokens, but by-agent counted %d", got)
+ }
+ oneDaySeconds := agentSeconds(get("/api/dashboard/agent-runtime?days=1&tz=UTC"))
+
+ // days=2 covers today + yesterday, so both fixtures must now appear —
+ // proving the window closed rather than the fixtures being unreachable.
+ if got := seededTokens(get("/api/dashboard/usage/by-agent?days=2&tz=UTC")); got < 7777 {
+ t.Errorf("days=2 must include yesterday's 7777 tokens, got %d", got)
+ }
+ twoDaySeconds := agentSeconds(get("/api/dashboard/agent-runtime?days=2&tz=UTC"))
+ if twoDaySeconds-oneDaySeconds < 900 {
+ t.Errorf(
+ "days=1 leaked yesterday's 900s run: days=1 reported %ds, days=2 %ds (delta %d, want >=900)",
+ oneDaySeconds, twoDaySeconds, twoDaySeconds-oneDaySeconds,
+ )
+ }
+}
+
// TestDashboardFailureWireContractKeepsEmptyReason pins the success bucket's
// wire form. The client's zod schema defaults a missing `failure_reason` to
// "" — the succeeded bucket — which is only safe while the server always
diff --git a/server/pkg/db/generated/task_usage.sql.go b/server/pkg/db/generated/task_usage.sql.go
index 00f31d65ee..7636ff6946 100644
--- a/server/pkg/db/generated/task_usage.sql.go
+++ b/server/pkg/db/generated/task_usage.sql.go
@@ -139,8 +139,10 @@ type ListDashboardAgentRunTimeRow struct {
// token cost window (which is anchored on tu.created_at, ~= completion time).
//
// No date bucketing, so no @tz — but @since is the viewer's local
-// start-of-day-(N) so the "last N days" window lines up with the per-agent
-// cost card; passed straight through without re-truncation.
+// start-of-day for the EXACT N-day window (parseExactSinceParamInTZ), so the
+// "last N days" window lines up with the per-agent cost card and the daily
+// charts the client trims to the same span; passed straight through without
+// re-truncation.
func (q *Queries) ListDashboardAgentRunTime(ctx context.Context, arg ListDashboardAgentRunTimeParams) ([]ListDashboardAgentRunTimeRow, error) {
rows, err := q.db.Query(ctx, listDashboardAgentRunTime, arg.WorkspaceID, arg.Since, arg.ProjectID)
if err != nil {
diff --git a/server/pkg/db/queries/task_usage.sql b/server/pkg/db/queries/task_usage.sql
index 8973094410..2d1531e044 100644
--- a/server/pkg/db/queries/task_usage.sql
+++ b/server/pkg/db/queries/task_usage.sql
@@ -154,8 +154,10 @@ ORDER BY DATE(atq.completed_at AT TIME ZONE sqlc.arg('tz')::text) DESC;
-- token cost window (which is anchored on tu.created_at, ~= completion time).
--
-- No date bucketing, so no @tz — but @since is the viewer's local
--- start-of-day-(N) so the "last N days" window lines up with the per-agent
--- cost card; passed straight through without re-truncation.
+-- start-of-day for the EXACT N-day window (parseExactSinceParamInTZ), so the
+-- "last N days" window lines up with the per-agent cost card and the daily
+-- charts the client trims to the same span; passed straight through without
+-- re-truncation.
SELECT
atq.agent_id,
COALESCE(