Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
test(handler): stop the dashboard fixture finishing before its own window opens (MUL-6103) (#6871)
Xichang(Seacen) Zhaoa954dec8e2a2
diff --git a/server/internal/handler/dashboard_test.go b/server/internal/handler/dashboard_test.goindex b333a8b9ec..409cf50d25 100644--- a/server/internal/handler/dashboard_test.go+++ b/server/internal/handler/dashboard_test.go@@ -10,6 +10,138 @@ import ("time")+// dashboardFixtureTZ is the zone the day-boundary fixtures in this file are+// built in, and the zone their requests pin with `?tz=`. Both sides read this+// one constant because they have to agree: every `days=N` endpoint opens its+// window at start-of-day in the VIEWER's zone (resolveViewingTZ: `?tz=`, else+// the user's stored user.timezone, else UTC), so a fixture anchored in one+// zone and a window opened in another sit an offset apart. Without the+// `?tz=` these requests would inherit whatever user.timezone holds — NULL in+// the handler fixture, hence UTC.+//+// The zone is deliberately EAST of UTC, and that is what makes the pin+// load-bearing rather than decorative. A fixture built in UTC survives losing+// its `?tz=`: the fallback is UTC too, so the window opens where the fixture+// already sits and nothing notices. Built in Asia/Tokyo the run finishes at+// 15:10 UTC the previous day, so a request that falls back to UTC opens its+// window after the run ended and the assertions go red — which is the whole+// point of pinning it. Verified by mutation: dropping the parameter, and+// pinning it to UTC, both fail.+const dashboardFixtureTZ = "Asia/Tokyo"++// dashboardFixtureTZParam is dashboardFixtureTZ as a query fragment, so a+// request cannot pin a zone the fixture was not built in.+const dashboardFixtureTZParam = "tz=" + dashboardFixtureTZ++// dashboardFixtureLoc resolves dashboardFixtureTZ.+func dashboardFixtureLoc(t *testing.T) *time.Location {+ t.Helper()+ loc, err := time.LoadLocation(dashboardFixtureTZ)+ if err != nil {+ t.Fatalf("load fixture timezone %q: %v", dashboardFixtureTZ, err)+ }+ return loc+}++// runFinishedToday returns the started_at / completed_at of a ten-minute run+// placed in the first ten minutes of the day `now` falls in, read in loc.+//+// Every endpoint these fixtures exercise filters on `completed_at >= @since`+// — the END of the run, not its start — and for the per-agent rollups @since+// is start of today in the viewer's zone (parseExactSinceParamInTZ at+// days=1). Timestamps built as `now - 30m` therefore fall out of that window+// for the first twenty minutes after midnight: the run finished yesterday,+// the window opens today, and the assertions read the empty result as nothing+// having happened. A handler job that ran at 00:13 UTC failed on exactly+// that; the next one at 00:25 passed with nothing changed but the clock. The+// date-bucketed halves ride out those twenty minutes on the extra day+// parseSinceParamInTZ hands them, which is why only their per-agent siblings+// went red. Anchoring the run on the boundary itself takes the time of day+// out of the fixture rather than special-casing the twenty minutes it bites.+//+// Start-of-day is built the way sinceFromDays builds the cutoff, so fixture+// and window agree instant for instant. In the first ten minutes after+// midnight the run ends slightly in the future, which none of these queries+// mind: they bound completed_at from below only, and the token rollup keys+// off task_usage.created_at rather than the queue row.+func runFinishedToday(now time.Time, loc *time.Location) (started, completed time.Time) {+ local := now.In(loc)+ started = time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, loc)+ return started, started.Add(10 * time.Minute)+}++// pinDayWindowClock freezes the clock the request-side cutoff reads and hands+// back the same instant for the fixture, so both sides describe one moment.+//+// They read the wall clock at two different points otherwise — the fixture when+// it is built, the cutoff when the handler runs, with inserts and a rollup in+// between — and a suite that crosses midnight in that gap writes its run into+// one day and then asks for the next day's window. The gap is milliseconds, so+// it is rare and permanent: nothing about the assertions says which day they+// meant.+func pinDayWindowClock(t *testing.T, at time.Time) time.Time {+ t.Helper()+ prev := dayWindowNow+ dayWindowNow = func() time.Time { return at }+ t.Cleanup(func() { dayWindowNow = prev })+ return at+}++// TestDashboardFixtureRunLandsInsideTheWindow pins what runFinishedToday+// promises the two DB fixtures that call it: at any hour, in any zone, the+// run it places is inside the days=1 window the endpoints open. The window is+// taken from sinceFromDays — the production cutoff itself — rather than from+// a second copy of the helper's arithmetic.+//+// The midnight rows are the point of the table. A fixture built off the wall+// clock is outside that window for the first twenty minutes of the day and+// inside it for the other 23h40m, so only a synthetic clock can hold it to+// account: the suite would otherwise have to run at midnight to see the+// failure, which is how this reached CI in the first place.+func TestDashboardFixtureRunLandsInsideTheWindow(t *testing.T) {+ // Half-hour and negative offsets, so a helper that anchored on UTC+ // midnight while the request asked for another zone cannot pass.+ for _, tz := range []string{dashboardFixtureTZ, "Asia/Kolkata", "America/Los_Angeles"} {+ loc, err := time.LoadLocation(tz)+ if err != nil {+ t.Fatalf("load %s: %v", tz, err)+ }+ for _, clock := range []string{+ "2026-03-01 00:00:00",+ "2026-03-01 00:05:00",+ "2026-03-01 00:19:59",+ "2026-03-01 12:00:00",+ "2026-03-01 23:59:59",+ } {+ t.Run(tz+" "+clock, func(t *testing.T) {+ now, err := time.ParseInLocation("2006-01-02 15:04:05", clock, loc)+ if err != nil {+ t.Fatalf("parse %s: %v", clock, err)+ }+ started, completed := runFinishedToday(now, loc)++ // parseExactSinceParamInTZ trims a day off sinceFromDays, so+ // the days=1 cutoff these endpoints use is start of today.+ since := sinceFromDays(now, 0, loc)+ tomorrow := since.AddDate(0, 0, 1)++ if got := completed.Sub(started); got != 10*time.Minute {+ t.Errorf("run lasted %s, want 10m — the >=600s the run-time assertion reads", got)+ }+ if completed.Before(since) {+ t.Errorf("completed_at %s precedes the days=1 cutoff %s: `completed_at >= @since` drops the fixture", completed, since)+ }+ if !completed.Before(tomorrow) {+ t.Errorf("completed_at %s is past the day that opened at %s", completed, since)+ }+ if started.Before(since) {+ t.Errorf("started_at %s precedes the days=1 cutoff %s", started, since)+ }+ })+ }+ }+}+// TestDashboardEndpoints covers the workspace-dashboard rollups:// - daily token usage with and without project filter// - per-agent token usage with and without project filter@@ -75,9 +207,10 @@ func TestDashboardEndpoints(t *testing.T) {projectIssueID := mkIssue(true)otherIssueID := mkIssue(false)- now := time.Now().UTC()- started := now.Add(-30 * time.Minute)- completed := started.Add(10 * time.Minute) // 600s run+ // A 600s run that finished inside today's window at every hour of the+ // clock — see runFinishedToday for what a `now - 30m` fixture does to the+ // agent-runtime assertions just after midnight.+ started, completed := runFinishedToday(pinDayWindowClock(t, time.Now()), dashboardFixtureLoc(t))mkTaskWithUsage := func(issueID string, status string, tokens int64) {var taskID string@@ -129,7 +262,7 @@ func TestDashboardEndpoints(t *testing.T) {// daily — workspace-wide{w := httptest.NewRecorder()- testHandler.GetDashboardUsageDaily(w, newRequest("GET", "/api/dashboard/usage/daily?days=1", nil))+ testHandler.GetDashboardUsageDaily(w, newRequest("GET", "/api/dashboard/usage/daily?days=1&"+dashboardFixtureTZParam, nil))if w.Code != http.StatusOK {t.Fatalf("daily ws: expected 200, got %d: %s", w.Code, w.Body.String())}@@ -149,7 +282,7 @@ func TestDashboardEndpoints(t *testing.T) {// daily — project-scoped{w := httptest.NewRecorder()- testHandler.GetDashboardUsageDaily(w, newRequest("GET", "/api/dashboard/usage/daily?days=1&project_id="+projectID, nil))+ testHandler.GetDashboardUsageDaily(w, newRequest("GET", "/api/dashboard/usage/daily?days=1&"+dashboardFixtureTZParam+"&project_id="+projectID, nil))if w.Code != http.StatusOK {t.Fatalf("daily project: expected 200, got %d: %s", w.Code, w.Body.String())}@@ -175,7 +308,7 @@ func TestDashboardEndpoints(t *testing.T) {// by-agent — project-scoped{w := httptest.NewRecorder()- testHandler.GetDashboardUsageByAgent(w, newRequest("GET", "/api/dashboard/usage/by-agent?days=1&project_id="+projectID, nil))+ testHandler.GetDashboardUsageByAgent(w, newRequest("GET", "/api/dashboard/usage/by-agent?days=1&"+dashboardFixtureTZParam+"&project_id="+projectID, nil))if w.Code != http.StatusOK {t.Fatalf("by-agent project: expected 200, got %d: %s", w.Code, w.Body.String())}@@ -195,7 +328,7 @@ func TestDashboardEndpoints(t *testing.T) {// agent-runtime — project-scoped{w := httptest.NewRecorder()- testHandler.GetDashboardAgentRunTime(w, newRequest("GET", "/api/dashboard/agent-runtime?days=1&project_id="+projectID, nil))+ testHandler.GetDashboardAgentRunTime(w, newRequest("GET", "/api/dashboard/agent-runtime?days=1&"+dashboardFixtureTZParam+"&project_id="+projectID, nil))if w.Code != http.StatusOK {t.Fatalf("agent-runtime: expected 200, got %d: %s", w.Code, w.Body.String())}@@ -230,7 +363,7 @@ func TestDashboardEndpoints(t *testing.T) {// the no-project-filter shape matches up.{w := httptest.NewRecorder()- testHandler.GetDashboardUsageByAgent(w, newRequest("GET", "/api/dashboard/usage/by-agent?days=1", nil))+ testHandler.GetDashboardUsageByAgent(w, newRequest("GET", "/api/dashboard/usage/by-agent?days=1&"+dashboardFixtureTZParam, nil))if w.Code != http.StatusOK {t.Fatalf("by-agent ws: expected 200, got %d: %s", w.Code, w.Body.String())}@@ -1542,9 +1675,11 @@ func TestDashboardFailuresCountNeverStartedTasks(t *testing.T) {}t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })- now := time.Now().UTC()- started := now.Add(-30 * time.Minute)- completed := started.Add(10 * time.Minute)+ // Same window-safe fixture as TestDashboardEndpoints: the by-agent case+ // below runs on the exact start-of-day cutoff and filters on+ // completed_at, so a run timed off the wall clock disappears from it for+ // the first twenty minutes of the day.+ started, completed := runFinishedToday(pinDayWindowClock(t, time.Now()), dashboardFixtureLoc(t))// startedAt is nullable so the queue-expiry case can be modelled exactly:// completed_at set, started_at absent.@@ -1588,10 +1723,10 @@ func TestDashboardFailuresCountNeverStartedTasks(t *testing.T) {call func(w *httptest.ResponseRecorder)}{{"daily", func(w *httptest.ResponseRecorder) {- testHandler.GetDashboardFailuresDaily(w, newRequest("GET", "/api/dashboard/failures/daily?days=1", nil))+ testHandler.GetDashboardFailuresDaily(w, newRequest("GET", "/api/dashboard/failures/daily?days=1&"+dashboardFixtureTZParam, nil))}},{"by-agent", func(w *httptest.ResponseRecorder) {- testHandler.GetDashboardFailuresByAgent(w, newRequest("GET", "/api/dashboard/failures/by-agent?days=1", nil))+ testHandler.GetDashboardFailuresByAgent(w, newRequest("GET", "/api/dashboard/failures/by-agent?days=1&"+dashboardFixtureTZParam, nil))}},} {t.Run(tc.name, func(t *testing.T) {@@ -1907,3 +2042,112 @@ func TestDashboardFailureWireContractKeepsEmptyReason(t *testing.T) {})}}++// dashboardRunTimeSeconds inserts one finished run for the fixture agent and+// returns what agent-runtime reports for it under the given query string. The+// caller owns the clock: whatever pinDayWindowClock was given is what both the+// fixture and the handler's cutoff read.+func dashboardRunTimeSeconds(t *testing.T, at time.Time, loc *time.Location, query string) int64 {+ t.Helper()+ 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, 'clock fixture', $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) })++ started, completed := runFinishedToday(at, loc)+ 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', $4, $5, $4)+ RETURNING id+ `, agentID, issueID, runtimeID, started, completed).Scan(&taskID); err != nil {+ t.Fatalf("create task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })++ w := httptest.NewRecorder()+ testHandler.GetDashboardAgentRunTime(w, newRequest("GET", "/api/dashboard/agent-runtime?"+query, nil))+ if w.Code != http.StatusOK {+ t.Fatalf("agent-runtime: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var rows []struct {+ AgentID string `json:"agent_id"`+ TotalSeconds int64 `json:"total_seconds"`+ }+ _ = json.NewDecoder(w.Body).Decode(&rows)+ var seconds int64+ for _, r := range rows {+ if r.AgentID == agentID {+ seconds += r.TotalSeconds+ }+ }+ return seconds+}++// A fixture built a hair before midnight is still counted by a request handled+// a hair after it.+//+// The two sides used to read the wall clock at different moments — the fixture+// when it was built, the cutoff when the handler ran, with inserts and a rollup+// in between. Crossing midnight in that gap wrote the run into one day and then+// asked for the next day's window, and the row vanished. Pinning one instant is+// what removes the question; this asserts the removal at the instant where it+// used to bite, rather than trusting that the suite never runs at 23:59.+func TestDashboardFixtureSurvivesTheMidnightStraddle(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ loc := dashboardFixtureLoc(t)+ // 23:59:59.9 in the fixture's own zone: one tenth of a second of the day+ // left when the fixture is built.+ local := time.Date(2026, 3, 1, 23, 59, 59, 900_000_000, loc)+ at := pinDayWindowClock(t, local)++ if got := dashboardRunTimeSeconds(t, at, loc, "days=1&"+dashboardFixtureTZParam); got < 600 {+ t.Errorf("agent-runtime reported %ds for a run built at %s, want >=600 — "++ "the fixture and the cutoff have to describe the same day even when the clock is about to turn over",+ got, local.Format(time.RFC3339Nano))+ }+}++// The timezone pin is load-bearing, at an instant that proves it.+//+// A request that loses its `?tz=` falls back to the fixture user's stored zone+// — UTC — while the fixture stays in dashboardFixtureTZ, and the two windows+// then sit an offset apart. Whether that offset actually hides the run depends+// on the time of day, so asserting it against the wall clock proves nothing for+// most of the day. Pinned at 02:00 UTC on a fixed date, Tokyo's day began at+// 15:00 UTC the day before and UTC's began two hours ago: the run is behind the+// UTC cutoff and must not be counted.+func TestDashboardMismatchedRequestTimezoneHidesTheRun(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ loc := dashboardFixtureLoc(t)+ at := pinDayWindowClock(t, time.Date(2026, 3, 1, 2, 0, 0, 0, time.UTC))++ matched := dashboardRunTimeSeconds(t, at, loc, "days=1&"+dashboardFixtureTZParam)+ if matched < 600 {+ t.Fatalf("the matched-timezone request reported %ds, want >=600 — this test's premise is gone", matched)+ }+ if mismatched := dashboardRunTimeSeconds(t, at, loc, "days=1&tz=UTC"); mismatched != 0 {+ t.Errorf("a request pinned to UTC counted %ds of a run the fixture placed in %s — "++ "the pin is meant to be the thing that keeps the two windows together, so a mismatch has to be visible here",+ mismatched, dashboardFixtureTZ)+ }+}diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex 87d0145b4e..da1fe35ba2 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -421,6 +421,16 @@ func parseExactSinceParamInTZ(r *http.Request, defaultDays int, tzName string) p// parseDaysCutoff is the shared body of the two cutoff parsers. `trimDays`// pulls the cutoff forward, so 0 keeps the N+1 headroom and 1 closes the// window to exactly N calendar days.+// dayWindowNow is the clock every `days=N` cutoff reads.+//+// A variable so a test can pin it. Without one, a fixture and the cutoff that+// has to contain it read the wall clock at two different moments — the fixture+// when it is built, the cutoff when the request is handled, with inserts and a+// rollup in between. A suite that crosses midnight in that gap builds its run+// in one day and then asks for the next day's window, and the row it just+// wrote is excluded. Production always reads the real clock.+var dayWindowNow = time.Now+func parseDaysCutoff(r *http.Request,defaultDays int,@@ -441,7 +451,7 @@ func parseDaysCutoff(// window by one would put the cutoff at start-of-today+0 — still correct// ("today only"), which is exactly what days=1 means.return pgtype.Timestamptz{- Time: sinceFromDays(time.Now(), days-trimDays, loc),+ Time: sinceFromDays(dayWindowNow(), days-trimDays, loc),Valid: true,}}