Skip to content

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

Go

fix(runtimes): count exactly the selected days in runtime usage (#10415)

pseudoyub3ac285a9ce2
diff --git a/packages/views/runtimes/utils.test.ts b/packages/views/runtimes/utils.test.ts
index 697ddfd649..64d0002b86 100644
--- a/packages/views/runtimes/utils.test.ts
+++ b/packages/views/runtimes/utils.test.ts
@@ -1619,9 +1619,10 @@ describe("sliceWindow (timezone-aware)", () => {
makeUsage("2026-05-19"),
makeUsage("2026-05-20"),
];
+ // The Shanghai window is 05-14..05-20, so 05-13 falls out; a cutoff read
+ // from the host clock (today 05-19) would have kept it.
const { filtered } = sliceWindow(usage, 7, "Asia/Shanghai");
expect(filtered.map((u) => u.date)).toEqual([
- "2026-05-13",
"2026-05-19",
"2026-05-20",
]);
@@ -1639,6 +1640,20 @@ describe("sliceWindow (timezone-aware)", () => {
expect(filtered.map((u) => u.date)).toEqual(["2026-05-15", "2026-05-19"]);
expect(prevFiltered.map((u) => u.date)).toEqual(["2026-05-08"]);
});
+
+ it("covers exactly `days` calendar days, today included, in both windows", () => {
+ vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));
+ const usage = [
+ makeUsage("2026-05-05"),
+ makeUsage("2026-05-06"),
+ makeUsage("2026-05-12"),
+ makeUsage("2026-05-13"),
+ makeUsage("2026-05-19"),
+ ];
+ const { filtered, prevFiltered } = sliceWindow(usage, 7, "UTC");
+ expect(filtered.map((u) => u.date)).toEqual(["2026-05-13", "2026-05-19"]);
+ expect(prevFiltered.map((u) => u.date)).toEqual(["2026-05-06", "2026-05-12"]);
+ });
});
describe("aggregateByDate", () => {
diff --git a/packages/views/runtimes/utils.ts b/packages/views/runtimes/utils.ts
index d2f77e375e..2aba4d0a1d 100644
--- a/packages/views/runtimes/utils.ts
+++ b/packages/views/runtimes/utils.ts
@@ -1390,9 +1390,11 @@ export function sliceWindow(
days: number,
tz: string,
): { filtered: RuntimeUsage[]; prevFiltered: RuntimeUsage[] } {
+ // `days` calendar days including today. The backend's `days=N` series
+ // starts one day earlier on purpose, so the cutoff must not be today - N.
const today = todayIso(tz);
- const isoCurrent = addDaysIso(today, -days);
- const isoPrev = addDaysIso(today, -days * 2);
+ const isoCurrent = addDaysIso(today, -(days - 1));
+ const isoPrev = addDaysIso(today, -(days * 2 - 1));
return {
filtered: usage.filter((u) => u.date >= isoCurrent),
prevFiltered: usage.filter(
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index f3d9a3dde3..71b2a91226 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -235,9 +235,10 @@ func (h *Handler) GetRuntimeUsageByAgent(w http.ResponseWriter, r *http.Request)
}
// No date bucketing — tz only sets the cutoff boundary so "last 30
- // days" means 30 of the viewer's days.
+ // days" means 30 of the viewer's days. Without a date column the client
+ // cannot trim the extra day, so the window closes here.
viewTZ := h.resolveViewingTZ(r)
- since := parseSinceParamInTZ(r, 30, viewTZ)
+ since := parseExactSinceParamInTZ(r, 30, viewTZ)
rows, err := h.Queries.ListRuntimeUsageByAgent(r.Context(), db.ListRuntimeUsageByAgentParams{
RuntimeID: rt.ID,
@@ -348,14 +349,9 @@ func (h *Handler) GetRuntimeUsageByHour(w http.ResponseWriter, r *http.Request)
//
// The cutoff yields N+1 calendar buckets (today-days … today inclusive).
// The extra day versus a naive "-(days-1)" is deliberate headroom, not an
-// off-by-one:
-// - Runtime detail's sliceWindow filters `date >= today-days` (closed) and
-// its prior-window delta reaches back to today-2*days, so the today-days
-// bucket MUST exist or the oldest bar / KPI delta silently loses data.
-// - The workspace dashboard re-filters client-side with -(days-1); the one
-// extra day the backend returns is trimmed there — harmless.
-//
-// Do not "tighten" this to -(days-1): it would break the runtime detail page.
+// off-by-one: date-bucketed clients (runtime detail's sliceWindow, the
+// workspace dashboard) trim to -(days-1) themselves. Responses without a date
+// column cannot be trimmed and should use parseExactSinceParamInTZ instead.
func sinceFromDays(now time.Time, days int, loc *time.Location) time.Time {
local := now.In(loc)
startOfToday := time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, loc)
@@ -373,15 +369,13 @@ func parseSinceParamInTZ(r *http.Request, defaultDays int, tzName string) pgtype
// parseExactSinceParamInTZ is parseSinceParamInTZ without the extra day of
// headroom: `days=N` yields exactly N calendar buckets (today's partial
-// bucket + N-1 prior full days), which is the window the workspace dashboard
-// actually displays.
+// bucket + N-1 prior full days), which is the window the runtime detail page
+// and workspace dashboard actually display.
//
-// The N+1 cutoff exists so date-bucketed series can reach one bucket further
-// back than they render (runtime detail's prior-window delta needs it), and
-// the dashboard trims the surplus client-side with `-(days-1)`. A response
-// with NO date dimension cannot be trimmed that way, so an aggregate served
-// off the N+1 cutoff silently covers one more day than the chart beside it.
-// Endpoints whose rows carry no date use this variant instead.
+// Date-bucketed clients trim the surplus client-side with `-(days-1)`. A
+// response with NO date dimension cannot be trimmed that way, so an aggregate
+// served off the N+1 cutoff silently covers one more day than the chart beside
+// it. Endpoints whose rows carry no date should use this variant instead.
func parseExactSinceParamInTZ(r *http.Request, defaultDays int, tzName string) pgtype.Timestamptz {
return parseDaysCutoff(r, defaultDays, tzName, 1)
}
diff --git a/server/internal/handler/runtime_test.go b/server/internal/handler/runtime_test.go
index c85b417929..70d402460e 100644
--- a/server/internal/handler/runtime_test.go
+++ b/server/internal/handler/runtime_test.go
@@ -290,6 +290,90 @@ func TestListRuntimeUsageByAgent_MergesMixedCaseProvider(t *testing.T) {
}
}
+// TestGetRuntimeUsageByAgentUsesExactWindow pins the runtime detail page's
+// "Cost by agent" to the same N calendar days as the KPIs above it. The
+// by-agent rows carry no date, so the client cannot trim the extra day
+// parseSinceParamInTZ hands date-bucketed series; the handler has to close
+// the window itself, as the dashboard's per-agent rollups do (MUL-5551).
+func TestGetRuntimeUsageByAgentUsesExactWindow(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)
+ VALUES ($1, 'runtime by-agent window test', $2, 'member')
+ 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) })
+
+ // Usage at noon yesterday (UTC), under a model no other fixture uses.
+ // Noon keeps it clear of the midnight edge in either direction.
+ const windowModel = "runtime-exact-window-model"
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, created_at)
+ VALUES ($1, $2, $3, 'completed', 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) })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)
+ VALUES ($1, 'anthropic', $2, 7777, 0,
+ (((now() AT TIME ZONE 'UTC')::date - 1)::timestamp + interval '12 hours') AT TIME ZONE 'UTC')
+ `, taskID, windowModel); err != nil {
+ t.Fatalf("insert task_usage: %v", err)
+ }
+
+ seededTokens := func(days string) int64 {
+ w := httptest.NewRecorder()
+ req := newRequest("GET", "/api/runtimes/"+runtimeID+"/usage/by-agent?days="+days+"&tz=UTC", nil)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.GetRuntimeUsageByAgent(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("days=%s: expected 200, got %d: %s", days, w.Code, w.Body.String())
+ }
+ var rows []RuntimeUsageByAgentResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &rows); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ var n int64
+ for _, r := range rows {
+ if r.Model == windowModel {
+ n += r.InputTokens
+ }
+ }
+ return n
+ }
+
+ if got := seededTokens("1"); got != 0 {
+ t.Errorf("days=1 must not reach yesterday's tokens, but by-agent counted %d", got)
+ }
+ // days=2 covers today and yesterday, so the row must appear: the window
+ // closed, the fixture is reachable.
+ if got := seededTokens("2"); got != 7777 {
+ t.Errorf("days=2 must include yesterday's 7777 tokens, got %d", got)
+ }
+}
+
// TestListRuntimeUsageBucketsByViewerTimezone proves the runtime trend reads
// bucket the day boundary in the VIEWER's tz (the argument passed to
// listRuntimeUsage). The viewer tz is Asia/Shanghai; assertions only pass if