package pipeline import ( "context" "fmt" "math" "path/filepath" "testing" ) func TestUsageStatsCountAllHistoryAndZeroFillDailyActivity(t *testing.T) { ctx := context.Background() store, err := Open(filepath.Join(t.TempDir(), "stats.db")) if err != nil { t.Fatal(err) } defer store.Close() stats, err := store.UsageStats(ctx) if err != nil || stats.Total != 0 || len(stats.Days) != 14 || len(stats.Pipelines) != 0 { t.Fatal("empty statistics", stats, err) } source := "# stage worker\n```output\nOutput map.\n```\n```prompt\nTask\n```\n```configs\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n```edges\nsuccess -> #success\nerror -> #failure\n```\n" if _, err := store.Submit(ctx, "busy", source); err != nil { t.Fatal(err) } if _, err := store.Submit(ctx, "unused", source); err != nil { t.Fatal(err) } items, err := store.List(ctx) if err != nil { t.Fatal(err) } var id int64 for _, p := range items { if p.Name == "busy" { id = p.ID } } d, err := store.Get(ctx, id, 0) if err != nil { t.Fatal(err) } for i := 0; i < 60; i++ { run, _, err := store.CreateRun(ctx, d, fmt.Sprintf("key-%d", i), "/repo", false, nil, nil) if err != nil { t.Fatal(err) } status := "succeeded" if i == 0 { status = "failed" } if i == 1 { status = "canceled" } if i == 2 { status = "running" } if i == 3 { status = "interrupted" } _, err = store.db.ExecContext(ctx, `UPDATE pipeline_runs SET status=?,created_at=datetime('now','-60 seconds'),finished_at=CASE WHEN ?='running' THEN NULL ELSE datetime('now') END WHERE id=?`, status, status, run) if err != nil { t.Fatal(err) } } stats, err = store.UsageStats(ctx) if err != nil { t.Fatal(err) } if stats.Total != 60 || stats.Succeeded != 56 || stats.Failed != 1 || stats.Canceled != 1 || stats.Interrupted != 1 || stats.Active != 1 || math.Abs(stats.AverageSeconds-60) > .01 { t.Fatal("incorrect all-history aggregation", stats) } if len(stats.Pipelines) != 2 || stats.Pipelines[0].Total != 60 || stats.Pipelines[1].Total != 0 { t.Fatal("missing unused pipeline or per-pipeline usage", stats.Pipelines) } total := 0 for _, day := range stats.Days { total += day.Runs } if total != 60 { t.Fatal("daily totals", stats.Days) } runs, err := store.ListRuns(ctx) if err != nil || len(runs) != stats.Total { t.Fatal("run list and all-history statistics disagree", len(runs), stats.Total, err) } }