Skip to content

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

Go

fix(usage): recompute hourly rollups per hour key so legacy buckets keep every run (MUL-10204) (#11559)

Multica Eve1fda78b0df49
diff --git a/server/cmd/migrate/migrate_task_usage_hourly_rollup_hour_key_test.go b/server/cmd/migrate/migrate_task_usage_hourly_rollup_hour_key_test.go
new file mode 100644
index 0000000000..a9306e7696
--- /dev/null
+++ b/server/cmd/migrate/migrate_task_usage_hourly_rollup_hour_key_test.go
@@ -0,0 +1,138 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "math/rand/v2"
+ "testing"
+ "time"
+)
+
+// TestTaskUsageHourlyRollupConservesLegacyHourTotals upgrades a pre-735 hour
+// whose single hourly row combines standalone and squad usage, re-dirties one
+// run's usage, and recomputes: the rollup must still total the raw usage and
+// split it per squad, whichever side was touched.
+func TestTaskUsageHourlyRollupConservesLegacyHourTotals(t *testing.T) {
+ const (
+ squadA = "00000000-0000-0000-0000-00000000000a"
+ squadB = "00000000-0000-0000-0000-00000000000b"
+ )
+ type run struct {
+ squadID string // "" for a standalone run
+ tokens int64
+ }
+ for _, tc := range []struct {
+ name string
+ runs []run
+ touched int
+ }{
+ {"standalone touched", []run{{"", 10}, {squadA, 20}}, 0},
+ {"squad touched", []run{{"", 10}, {squadA, 20}}, 1},
+ {"standalone touched with two squads", []run{{"", 10}, {squadA, 20}, {squadB, 40}}, 0},
+ {"one of two squads touched", []run{{"", 10}, {squadA, 20}, {squadB, 40}}, 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancel()
+ pool, schema := newPre735TaskUsageSchema(ctx, t)
+
+ const (
+ wsID = "00000000-0000-0000-0000-000000000001"
+ rtID = "00000000-0000-0000-0000-000000000002"
+ agentID = "00000000-0000-0000-0000-000000000003"
+ )
+ exec := func(sql string, args ...any) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, sql, args...); err != nil {
+ t.Fatalf("exec %q: %v", sql, err)
+ }
+ }
+
+ // Pre-735 state: every run's usage sits in one hourly row without
+ // a squad dimension.
+ exec(`INSERT INTO agent (id, workspace_id) VALUES ($1, $2)`, agentID, wsID)
+ var rawTotal int64
+ want := map[string]int64{}
+ usageIDs := make([]string, len(tc.runs))
+ for i, r := range tc.runs {
+ taskID := fmt.Sprintf("00000000-0000-0000-0001-%012d", i)
+ usageIDs[i] = fmt.Sprintf("00000000-0000-0000-0002-%012d", i)
+ var squad any
+ if r.squadID != "" {
+ squad = r.squadID
+ }
+ exec(`INSERT INTO agent_task_queue (id, agent_id, runtime_id, squad_id) VALUES ($1, $2, $3, $4)`,
+ taskID, agentID, rtID, squad)
+ exec(`INSERT INTO task_usage (id, task_id, provider, model, input_tokens, created_at, updated_at)
+ VALUES ($1, $2, 'claude', 'claude-sonnet-4-6', $3, '2026-11-21 11:30+00', '2026-11-21 11:30+00')`,
+ usageIDs[i], taskID, r.tokens)
+ rawTotal += r.tokens
+ want[r.squadID] = r.tokens
+ }
+ exec(`INSERT INTO task_usage_hourly (
+ bucket_hour, workspace_id, runtime_id, agent_id, project_id,
+ provider, model, input_tokens, task_count, event_count
+ ) VALUES ('2026-11-21 11:00+00', $1, $2, $3, NULL, 'claude', 'claude-sonnet-4-6', $4, $5, $5)`,
+ wsID, rtID, agentID, rawTotal, len(tc.runs))
+
+ if err := runMigrations(ctx, pool, runOptions{
+ Direction: "up",
+ Files: realMigrationFiles(t, []string{
+ "735_task_usage_hourly_squad_col",
+ "736_task_usage_hourly_squad_uq_idx",
+ "737_task_usage_hourly_dirty_squad_uq_idx",
+ "738_task_usage_hourly_workspace_squad_idx",
+ "739_task_usage_hourly_squad_pipeline",
+ "740_task_usage_hourly_drop_legacy_key",
+ "741_task_usage_hourly_dirty_drop_legacy_key",
+ "742_task_usage_hourly_squad_rollback_merge",
+ "755_task_usage_hourly_rollup_hour_key",
+ }, "up"),
+ SchemaMigrationsTable: schema + ".schema_migrations",
+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,
+ Hooks: hooksForDirection("up"),
+ }); err != nil {
+ t.Fatalf("run up migrations: %v", err)
+ }
+
+ exec(`UPDATE task_usage SET updated_at = '2026-11-21 12:01+00' WHERE id = $1`, usageIDs[tc.touched])
+ exec(`SELECT rollup_task_usage_hourly_window('2026-11-21 12:00+00', '2026-11-21 12:02+00')`)
+
+ rows, err := pool.Query(ctx, `
+ SELECT COALESCE(squad_id::text, ''), input_tokens, task_count, event_count
+ FROM task_usage_hourly
+ WHERE bucket_hour = '2026-11-21 11:00+00'`)
+ if err != nil {
+ t.Fatalf("query hourly rollup: %v", err)
+ }
+ got := map[string]int64{}
+ var gotTotal int64
+ for rows.Next() {
+ var squad string
+ var tokens, tasks, events int64
+ if err := rows.Scan(&squad, &tokens, &tasks, &events); err != nil {
+ t.Fatalf("scan hourly row: %v", err)
+ }
+ if tasks != 1 || events != 1 {
+ t.Errorf("bucket %q task/event count = %d/%d, want 1/1", squad, tasks, events)
+ }
+ got[squad] = tokens
+ gotTotal += tokens
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatalf("iterate hourly rows: %v", err)
+ }
+ if gotTotal != rawTotal {
+ t.Fatalf("hourly rollup total = %d, want raw usage total %d (buckets %v)", gotTotal, rawTotal, got)
+ }
+ if len(got) != len(want) {
+ t.Fatalf("hourly buckets = %v, want %v", got, want)
+ }
+ for squad, tokens := range want {
+ if got[squad] != tokens {
+ t.Fatalf("hourly buckets = %v, want %v", got, want)
+ }
+ }
+ })
+ }
+}
diff --git a/server/cmd/migrate/migrate_task_usage_hourly_squad_test.go b/server/cmd/migrate/migrate_task_usage_hourly_squad_test.go
index 24bb6d38ba..17f053dd1e 100644
--- a/server/cmd/migrate/migrate_task_usage_hourly_squad_test.go
+++ b/server/cmd/migrate/migrate_task_usage_hourly_squad_test.go
@@ -9,9 +9,10 @@ import (
"time"
"github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
)
-// TestTaskUsageHourlySquadMigrationsUpDownUp exercises migrations 735–742 in
+// TestTaskUsageHourlySquadMigrationsUpDownUp exercises migrations 735–742 and 755 in
// both directions against an isolated schema seeded with the pre-735
// task_usage_hourly schema, proving:
// - UP (735–742) creates the concurrent squad indexes, switches the rollup
@@ -21,106 +22,11 @@ import (
// CONCURRENTLY (registered in concurrentDownIndexCleanups), attaches them
// via ADD CONSTRAINT ... UNIQUE USING INDEX as UNIQUE NULLS NOT DISTINCT,
// and drops the squad indexes and columns cleanly.
-// - Re-applying UP (735–742) succeeds cleanly on the rolled-back schema.
+// - Re-applying UP (735–742, 755) succeeds cleanly on the rolled-back schema.
func TestTaskUsageHourlySquadMigrationsUpDownUp(t *testing.T) {
- adminPool := openTestPool(t)
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
-
- suffix := fmt.Sprintf("%d_%d", time.Now().UnixNano(), rand.Uint32())
- schema := "migrate_task_usage_squad_" + suffix
- schemaIdent := pgx.Identifier{schema}.Sanitize()
- if _, err := adminPool.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 := adminPool.Exec(cleanupCtx, "DROP SCHEMA IF EXISTS "+schemaIdent+" CASCADE"); err != nil {
- t.Logf("drop schema %s: %v", schema, err)
- }
- })
-
- pool := openTestPoolWithSearchPath(t, schema)
- for _, stmt := range []string{
- `CREATE TABLE schema_migrations (
- version TEXT PRIMARY KEY,
- applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
- )`,
- `CREATE FUNCTION task_usage_hour_bucket(ts TIMESTAMPTZ) RETURNS TIMESTAMPTZ LANGUAGE SQL IMMUTABLE AS $$
- SELECT date_trunc('hour', ts AT TIME ZONE 'UTC') AT TIME ZONE 'UTC'
- $$`,
- `CREATE TABLE agent (
- id UUID PRIMARY KEY,
- workspace_id UUID NOT NULL
- )`,
- `CREATE TABLE issue (
- id UUID PRIMARY KEY,
- workspace_id UUID NOT NULL,
- project_id UUID
- )`,
- `CREATE TABLE agent_task_queue (
- id UUID PRIMARY KEY,
- agent_id UUID NOT NULL,
- runtime_id UUID,
- issue_id UUID,
- squad_id UUID
- )`,
- `CREATE TABLE task_usage (
- id UUID PRIMARY KEY,
- task_id UUID NOT NULL,
- provider TEXT NOT NULL,
- model TEXT NOT NULL,
- input_tokens BIGINT NOT NULL DEFAULT 0,
- output_tokens BIGINT NOT NULL DEFAULT 0,
- cache_read_tokens BIGINT NOT NULL DEFAULT 0,
- cache_write_tokens BIGINT NOT NULL DEFAULT 0,
- cost_usd_ticks BIGINT,
- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
- updated_at TIMESTAMPTZ
- )`,
- `CREATE TABLE task_usage_hourly (
- bucket_hour TIMESTAMPTZ NOT NULL,
- workspace_id UUID NOT NULL,
- runtime_id UUID NOT NULL,
- agent_id UUID NOT NULL,
- project_id UUID,
- provider TEXT NOT NULL,
- model TEXT NOT NULL,
- input_tokens BIGINT NOT NULL DEFAULT 0,
- output_tokens BIGINT NOT NULL DEFAULT 0,
- cache_read_tokens BIGINT NOT NULL DEFAULT 0,
- cache_write_tokens BIGINT NOT NULL DEFAULT 0,
- cost_usd_ticks BIGINT NOT NULL DEFAULT 0,
- uncosted_input_tokens BIGINT,
- uncosted_output_tokens BIGINT,
- uncosted_cache_read_tokens BIGINT,
- uncosted_cache_write_tokens BIGINT,
- task_count BIGINT NOT NULL DEFAULT 0,
- event_count BIGINT NOT NULL DEFAULT 0,
- updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
- CONSTRAINT uq_task_usage_hourly_key
- UNIQUE NULLS NOT DISTINCT
- (bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)
- )`,
- `CREATE TABLE task_usage_hourly_dirty (
- bucket_hour TIMESTAMPTZ NOT NULL,
- workspace_id UUID NOT NULL,
- runtime_id UUID NOT NULL,
- agent_id UUID NOT NULL,
- project_id UUID,
- provider TEXT NOT NULL,
- model TEXT NOT NULL,
- enqueued_at TIMESTAMPTZ NOT NULL DEFAULT now(),
- CONSTRAINT uq_task_usage_hourly_dirty_key
- UNIQUE NULLS NOT DISTINCT
- (bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)
- )`,
- } {
- if _, err := pool.Exec(ctx, stmt); err != nil {
- t.Fatalf("seed pre-735 schema: %v", err)
- }
- }
+ pool, schema := newPre735TaskUsageSchema(ctx, t)
versions := []string{
"735_task_usage_hourly_squad_col",
@@ -131,6 +37,7 @@ func TestTaskUsageHourlySquadMigrationsUpDownUp(t *testing.T) {
"740_task_usage_hourly_drop_legacy_key",
"741_task_usage_hourly_dirty_drop_legacy_key",
"742_task_usage_hourly_squad_rollback_merge",
+ "755_task_usage_hourly_rollup_hour_key",
}
reversed := make([]string, len(versions))
for i := range versions {
@@ -160,7 +67,8 @@ func TestTaskUsageHourlySquadMigrationsUpDownUp(t *testing.T) {
assertIndexExists(t, pool, schema, "uq_task_usage_hourly_key", false)
assertIndexExists(t, pool, schema, "uq_task_usage_hourly_dirty_key", false)
- // 1b. UP remaining 740..742 (forward no-ops paired with concurrent down rebuilds).
+ // 1b. UP remaining 740..742 (forward no-ops paired with concurrent down
+ // rebuilds) and 755.
runDir("up", versions[5:])
// Insert two split squad rows + one standalone row sharing the same legacy
@@ -193,7 +101,7 @@ func TestTaskUsageHourlySquadMigrationsUpDownUp(t *testing.T) {
t.Fatalf("seed squad dirty row: %v", err)
}
- // 2. DOWN: 742..735
+ // 2. DOWN: 755, 742..735
runDir("down", reversed)
// Split rows must have merged into one row totaling 3500 tokens & 4 tasks.
@@ -235,9 +143,112 @@ func TestTaskUsageHourlySquadMigrationsUpDownUp(t *testing.T) {
assertIndexExists(t, pool, schema, "uq_task_usage_hourly_dirty_squad_key_idx", false)
assertIndexExists(t, pool, schema, "idx_task_usage_hourly_workspace_squad_time", false)
- // 3. Re-UP: 735..742 must succeed cleanly on the rolled-back schema.
+ // 3. Re-UP: 735..742 and 755 must succeed cleanly on the rolled-back schema.
runDir("up", versions)
assertIndexValidity(t, pool, schema, "uq_task_usage_hourly_squad_key_idx", true)
assertIndexValidity(t, pool, schema, "uq_task_usage_hourly_dirty_squad_key_idx", true)
assertIndexValidity(t, pool, schema, "idx_task_usage_hourly_workspace_squad_time", true)
}
+
+// newPre735TaskUsageSchema creates an isolated schema holding the tables the
+// task_usage_hourly squad migrations read, in their pre-735 shape, and returns
+// a pool whose search_path points at it.
+func newPre735TaskUsageSchema(ctx context.Context, t *testing.T) (*pgxpool.Pool, string) {
+ t.Helper()
+ adminPool := openTestPool(t)
+ suffix := fmt.Sprintf("%d_%d", time.Now().UnixNano(), rand.Uint32())
+ schema := "migrate_task_usage_squad_" + suffix
+ schemaIdent := pgx.Identifier{schema}.Sanitize()
+ if _, err := adminPool.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 := adminPool.Exec(cleanupCtx, "DROP SCHEMA IF EXISTS "+schemaIdent+" CASCADE"); err != nil {
+ t.Logf("drop schema %s: %v", schema, err)
+ }
+ })
+
+ pool := openTestPoolWithSearchPath(t, schema)
+ for _, stmt := range []string{
+ `CREATE TABLE schema_migrations (
+ version TEXT PRIMARY KEY,
+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ )`,
+ `CREATE FUNCTION task_usage_hour_bucket(ts TIMESTAMPTZ) RETURNS TIMESTAMPTZ LANGUAGE SQL IMMUTABLE AS $$
+ SELECT date_trunc('hour', ts AT TIME ZONE 'UTC') AT TIME ZONE 'UTC'
+ $$`,
+ `CREATE TABLE agent (
+ id UUID PRIMARY KEY,
+ workspace_id UUID NOT NULL
+ )`,
+ `CREATE TABLE issue (
+ id UUID PRIMARY KEY,
+ workspace_id UUID NOT NULL,
+ project_id UUID
+ )`,
+ `CREATE TABLE agent_task_queue (
+ id UUID PRIMARY KEY,
+ agent_id UUID NOT NULL,
+ runtime_id UUID,
+ issue_id UUID,
+ squad_id UUID
+ )`,
+ `CREATE TABLE task_usage (
+ id UUID PRIMARY KEY,
+ task_id UUID NOT NULL,
+ provider TEXT NOT NULL,
+ model TEXT NOT NULL,
+ input_tokens BIGINT NOT NULL DEFAULT 0,
+ output_tokens BIGINT NOT NULL DEFAULT 0,
+ cache_read_tokens BIGINT NOT NULL DEFAULT 0,
+ cache_write_tokens BIGINT NOT NULL DEFAULT 0,
+ cost_usd_ticks BIGINT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ
+ )`,
+ `CREATE TABLE task_usage_hourly (
+ bucket_hour TIMESTAMPTZ NOT NULL,
+ workspace_id UUID NOT NULL,
+ runtime_id UUID NOT NULL,
+ agent_id UUID NOT NULL,
+ project_id UUID,
+ provider TEXT NOT NULL,
+ model TEXT NOT NULL,
+ input_tokens BIGINT NOT NULL DEFAULT 0,
+ output_tokens BIGINT NOT NULL DEFAULT 0,
+ cache_read_tokens BIGINT NOT NULL DEFAULT 0,
+ cache_write_tokens BIGINT NOT NULL DEFAULT 0,
+ cost_usd_ticks BIGINT NOT NULL DEFAULT 0,
+ uncosted_input_tokens BIGINT,
+ uncosted_output_tokens BIGINT,
+ uncosted_cache_read_tokens BIGINT,
+ uncosted_cache_write_tokens BIGINT,
+ task_count BIGINT NOT NULL DEFAULT 0,
+ event_count BIGINT NOT NULL DEFAULT 0,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT uq_task_usage_hourly_key
+ UNIQUE NULLS NOT DISTINCT
+ (bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)
+ )`,
+ `CREATE TABLE task_usage_hourly_dirty (
+ bucket_hour TIMESTAMPTZ NOT NULL,
+ workspace_id UUID NOT NULL,
+ runtime_id UUID NOT NULL,
+ agent_id UUID NOT NULL,
+ project_id UUID,
+ provider TEXT NOT NULL,
+ model TEXT NOT NULL,
+ enqueued_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT uq_task_usage_hourly_dirty_key
+ UNIQUE NULLS NOT DISTINCT
+ (bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)
+ )`,
+ } {
+ if _, err := pool.Exec(ctx, stmt); err != nil {
+ t.Fatalf("seed pre-735 schema: %v", err)
+ }
+ }
+ return pool, schema
+}
diff --git a/server/migrations/755_task_usage_hourly_rollup_hour_key.down.sql b/server/migrations/755_task_usage_hourly_rollup_hour_key.down.sql
new file mode 100644
index 0000000000..b2e646e4ad
--- /dev/null
+++ b/server/migrations/755_task_usage_hourly_rollup_hour_key.down.sql
@@ -0,0 +1,177 @@
+-- Restore the 739 rollup, which recomputes only the squad keys an update
+-- touched (plus squad_id = NULL).
+
+CREATE OR REPLACE FUNCTION rollup_task_usage_hourly_window(
+ p_from TIMESTAMPTZ,
+ p_to TIMESTAMPTZ
+)
+RETURNS BIGINT
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ v_rows BIGINT;
+BEGIN
+ IF p_from >= p_to THEN
+ RETURN 0;
+ END IF;
+
+ WITH
+ dirty_raw AS (
+ SELECT DISTINCT
+ task_usage_hour_bucket(tu.created_at) AS bucket_hour,
+ a.workspace_id AS workspace_id,
+ atq.runtime_id AS runtime_id,
+ atq.agent_id AS agent_id,
+ i.project_id AS project_id,
+ COALESCE(atq.usage_squad_id, atq.squad_id) AS squad_id,
+ tu.provider AS provider,
+ tu.model AS model
+ FROM task_usage tu
+ JOIN agent_task_queue atq ON atq.id = tu.task_id
+ JOIN agent a ON a.id = atq.agent_id
+ LEFT JOIN issue i ON i.id = atq.issue_id
+ WHERE atq.runtime_id IS NOT NULL
+ AND (
+ (tu.updated_at >= p_from AND tu.updated_at < p_to)
+ OR (tu.updated_at IS NULL
+ AND tu.created_at >= p_from
+ AND tu.created_at < p_to)
+ )
+ ),
+ dirty_from_updates AS (
+ SELECT bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, squad_id, provider, model
+ FROM dirty_raw
+ UNION
+ -- Heal pre-735 buckets (stored with squad_id = NULL) whenever a
+ -- squad-attributed task in that bucket is recomputed or backfilled.
+ SELECT bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, NULL::uuid AS squad_id, provider, model
+ FROM dirty_raw
+ WHERE squad_id IS NOT NULL
+ ),
+ dirty_queue_raw AS (
+ SELECT bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, squad_id, provider, model
+ FROM task_usage_hourly_dirty
+ WHERE enqueued_at < p_to
+ ),
+ dirty_from_queue AS (
+ SELECT bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, squad_id, provider, model
+ FROM dirty_queue_raw
+ UNION
+ -- Heal pre-735 legacy NULL-squad buckets when triggers (issue project
+ -- move, issue delete, task/task_usage delete) enqueue a squad-attributed
+ -- dirty key, preventing old NULL buckets from surviving and double-counting.
+ SELECT bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, NULL::uuid AS squad_id, provider, model
+ FROM dirty_queue_raw
+ WHERE squad_id IS NOT NULL
+ ),
+ dirty_keys AS (
+ SELECT * FROM dirty_from_updates
+ UNION
+ SELECT * FROM dirty_from_queue
+ ),
+ recomputed AS (
+ SELECT
+ dk.bucket_hour,
+ dk.workspace_id,
+ dk.runtime_id,
+ dk.agent_id,
+ dk.project_id,
+ dk.squad_id,
+ dk.provider,
+ dk.model,
+ SUM(tu.input_tokens)::bigint AS input_tokens,
+ SUM(tu.output_tokens)::bigint AS output_tokens,
+ SUM(tu.cache_read_tokens)::bigint AS cache_read_tokens,
+ SUM(tu.cache_write_tokens)::bigint AS cache_write_tokens,
+ COALESCE(SUM(tu.cost_usd_ticks), 0)::bigint AS cost_usd_ticks,
+ COALESCE(SUM(tu.input_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_input_tokens,
+ COALESCE(SUM(tu.output_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_output_tokens,
+ COALESCE(SUM(tu.cache_read_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_cache_read_tokens,
+ COALESCE(SUM(tu.cache_write_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_cache_write_tokens,
+ COUNT(DISTINCT tu.task_id)::bigint AS task_count,
+ COUNT(*)::bigint AS event_count
+ FROM dirty_keys dk
+ JOIN agent_task_queue atq ON atq.runtime_id = dk.runtime_id
+ AND atq.agent_id = dk.agent_id
+ AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NOT DISTINCT FROM dk.squad_id
+ JOIN agent a ON a.id = atq.agent_id
+ AND a.workspace_id = dk.workspace_id
+ LEFT JOIN issue i ON i.id = atq.issue_id
+ JOIN task_usage tu ON tu.task_id = atq.id
+ AND tu.provider = dk.provider
+ AND tu.model = dk.model
+ AND task_usage_hour_bucket(tu.created_at) = dk.bucket_hour
+ WHERE (i.project_id IS NOT DISTINCT FROM dk.project_id)
+ GROUP BY 1, 2, 3, 4, 5, 6, 7, 8
+ ),
+ upserted AS (
+ INSERT INTO task_usage_hourly AS d (
+ bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, squad_id, provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
+ cost_usd_ticks,
+ uncosted_input_tokens, uncosted_output_tokens,
+ uncosted_cache_read_tokens, uncosted_cache_write_tokens,
+ task_count, event_count
+ )
+ SELECT
+ bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, squad_id, provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
+ cost_usd_ticks,
+ uncosted_input_tokens, uncosted_output_tokens,
+ uncosted_cache_read_tokens, uncosted_cache_write_tokens,
+ task_count, event_count
+ FROM recomputed
+ ON CONFLICT (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model) DO UPDATE
+ SET input_tokens = EXCLUDED.input_tokens,
+ output_tokens = EXCLUDED.output_tokens,
+ cache_read_tokens = EXCLUDED.cache_read_tokens,
+ cache_write_tokens = EXCLUDED.cache_write_tokens,
+ cost_usd_ticks = EXCLUDED.cost_usd_ticks,
+ uncosted_input_tokens = EXCLUDED.uncosted_input_tokens,
+ uncosted_output_tokens = EXCLUDED.uncosted_output_tokens,
+ uncosted_cache_read_tokens = EXCLUDED.uncosted_cache_read_tokens,
+ uncosted_cache_write_tokens = EXCLUDED.uncosted_cache_write_tokens,
+ task_count = EXCLUDED.task_count,
+ event_count = EXCLUDED.event_count,
+ updated_at = now()
+ RETURNING 1
+ ),
+ deleted_empty AS (
+ DELETE FROM task_usage_hourly d
+ USING dirty_keys dk
+ WHERE d.bucket_hour = dk.bucket_hour
+ AND d.workspace_id = dk.workspace_id
+ AND d.runtime_id = dk.runtime_id
+ AND d.agent_id = dk.agent_id
+ AND d.project_id IS NOT DISTINCT FROM dk.project_id
+ AND d.squad_id IS NOT DISTINCT FROM dk.squad_id
+ AND d.provider = dk.provider
+ AND d.model = dk.model
+ AND NOT EXISTS (
+ SELECT 1 FROM recomputed r
+ WHERE r.bucket_hour = dk.bucket_hour
+ AND r.workspace_id = dk.workspace_id
+ AND r.runtime_id = dk.runtime_id
+ AND r.agent_id = dk.agent_id
+ AND r.project_id IS NOT DISTINCT FROM dk.project_id
+ AND r.squad_id IS NOT DISTINCT FROM dk.squad_id
+ AND r.provider = dk.provider
+ AND r.model = dk.model
+ )
+ RETURNING 1
+ )
+ SELECT (SELECT COUNT(*) FROM upserted) + (SELECT COUNT(*) FROM deleted_empty)
+ INTO v_rows;
+
+ DELETE FROM task_usage_hourly_dirty WHERE enqueued_at < p_to;
+
+ RETURN v_rows;
+END;
+$$;
diff --git a/server/migrations/755_task_usage_hourly_rollup_hour_key.up.sql b/server/migrations/755_task_usage_hourly_rollup_hour_key.up.sql
new file mode 100644
index 0000000000..fd89e074ce
--- /dev/null
+++ b/server/migrations/755_task_usage_hourly_rollup_hour_key.up.sql
@@ -0,0 +1,155 @@
+-- Recompute the hourly usage rollup per hour key (the pre-735 7-column key,
+-- without squad_id) instead of per touched squad key.
+--
+-- Before 735 one task_usage_hourly row held the standalone and every squad's
+-- usage for an hour. 739 recomputed only the squad keys an update touched
+-- (plus squad_id = NULL), so touching one run rewrote that legacy row to the
+-- touched side's share and dropped the untouched runs' usage from the rollup.
+--
+-- Every dirty key is now widened to its hour key; all squad and standalone
+-- buckets under that hour key are recomputed from raw task_usage, and rows
+-- under it that no longer have usage are deleted. A legacy row is therefore
+-- replaced as a whole the first time its hour is recomputed. Nothing is
+-- backfilled here: legacy hours keep their combined totals until their next
+-- recompute.
+
+CREATE OR REPLACE FUNCTION rollup_task_usage_hourly_window(
+ p_from TIMESTAMPTZ,
+ p_to TIMESTAMPTZ
+)
+RETURNS BIGINT
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ v_rows BIGINT;
+BEGIN
+ IF p_from >= p_to THEN
+ RETURN 0;
+ END IF;
+
+ WITH
+ dirty_hour_keys AS (
+ SELECT
+ task_usage_hour_bucket(tu.created_at) AS bucket_hour,
+ a.workspace_id AS workspace_id,
+ atq.runtime_id AS runtime_id,
+ atq.agent_id AS agent_id,
+ i.project_id AS project_id,
+ tu.provider AS provider,
+ tu.model AS model
+ FROM task_usage tu
+ JOIN agent_task_queue atq ON atq.id = tu.task_id
+ JOIN agent a ON a.id = atq.agent_id
+ LEFT JOIN issue i ON i.id = atq.issue_id
+ WHERE atq.runtime_id IS NOT NULL
+ AND (
+ (tu.updated_at >= p_from AND tu.updated_at < p_to)
+ OR (tu.updated_at IS NULL
+ AND tu.created_at >= p_from
+ AND tu.created_at < p_to)
+ )
+ UNION
+ SELECT bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, provider, model
+ FROM task_usage_hourly_dirty
+ WHERE enqueued_at < p_to
+ ),
+ recomputed AS (
+ SELECT
+ hk.bucket_hour,
+ hk.workspace_id,
+ hk.runtime_id,
+ hk.agent_id,
+ hk.project_id,
+ COALESCE(atq.usage_squad_id, atq.squad_id) AS squad_id,
+ hk.provider,
+ hk.model,
+ SUM(tu.input_tokens)::bigint AS input_tokens,
+ SUM(tu.output_tokens)::bigint AS output_tokens,
+ SUM(tu.cache_read_tokens)::bigint AS cache_read_tokens,
+ SUM(tu.cache_write_tokens)::bigint AS cache_write_tokens,
+ COALESCE(SUM(tu.cost_usd_ticks), 0)::bigint AS cost_usd_ticks,
+ COALESCE(SUM(tu.input_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_input_tokens,
+ COALESCE(SUM(tu.output_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_output_tokens,
+ COALESCE(SUM(tu.cache_read_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_cache_read_tokens,
+ COALESCE(SUM(tu.cache_write_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_cache_write_tokens,
+ COUNT(DISTINCT tu.task_id)::bigint AS task_count,
+ COUNT(*)::bigint AS event_count
+ FROM dirty_hour_keys hk
+ JOIN agent_task_queue atq ON atq.runtime_id = hk.runtime_id
+ AND atq.agent_id = hk.agent_id
+ JOIN agent a ON a.id = atq.agent_id
+ AND a.workspace_id = hk.workspace_id
+ LEFT JOIN issue i ON i.id = atq.issue_id
+ JOIN task_usage tu ON tu.task_id = atq.id
+ AND tu.provider = hk.provider
+ AND tu.model = hk.model
+ AND task_usage_hour_bucket(tu.created_at) = hk.bucket_hour
+ WHERE (i.project_id IS NOT DISTINCT FROM hk.project_id)
+ GROUP BY 1, 2, 3, 4, 5, 6, 7, 8
+ ),
+ upserted AS (
+ INSERT INTO task_usage_hourly AS d (
+ bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, squad_id, provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
+ cost_usd_ticks,
+ uncosted_input_tokens, uncosted_output_tokens,
+ uncosted_cache_read_tokens, uncosted_cache_write_tokens,
+ task_count, event_count
+ )
+ SELECT
+ bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, squad_id, provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
+ cost_usd_ticks,
+ uncosted_input_tokens, uncosted_output_tokens,
+ uncosted_cache_read_tokens, uncosted_cache_write_tokens,
+ task_count, event_count
+ FROM recomputed
+ ON CONFLICT (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model) DO UPDATE
+ SET input_tokens = EXCLUDED.input_tokens,
+ output_tokens = EXCLUDED.output_tokens,
+ cache_read_tokens = EXCLUDED.cache_read_tokens,
+ cache_write_tokens = EXCLUDED.cache_write_tokens,
+ cost_usd_ticks = EXCLUDED.cost_usd_ticks,
+ uncosted_input_tokens = EXCLUDED.uncosted_input_tokens,
+ uncosted_output_tokens = EXCLUDED.uncosted_output_tokens,
+ uncosted_cache_read_tokens = EXCLUDED.uncosted_cache_read_tokens,
+ uncosted_cache_write_tokens = EXCLUDED.uncosted_cache_write_tokens,
+ task_count = EXCLUDED.task_count,
+ event_count = EXCLUDED.event_count,
+ updated_at = now()
+ RETURNING 1
+ ),
+ deleted_empty AS (
+ DELETE FROM task_usage_hourly d
+ USING dirty_hour_keys hk
+ WHERE d.bucket_hour = hk.bucket_hour
+ AND d.workspace_id = hk.workspace_id
+ AND d.runtime_id = hk.runtime_id
+ AND d.agent_id = hk.agent_id
+ AND d.project_id IS NOT DISTINCT FROM hk.project_id
+ AND d.provider = hk.provider
+ AND d.model = hk.model
+ AND NOT EXISTS (
+ SELECT 1 FROM recomputed r
+ WHERE r.bucket_hour = d.bucket_hour
+ AND r.workspace_id = d.workspace_id
+ AND r.runtime_id = d.runtime_id
+ AND r.agent_id = d.agent_id
+ AND r.project_id IS NOT DISTINCT FROM d.project_id
+ AND r.squad_id IS NOT DISTINCT FROM d.squad_id
+ AND r.provider = d.provider
+ AND r.model = d.model
+ )
+ RETURNING 1
+ )
+ SELECT (SELECT COUNT(*) FROM upserted) + (SELECT COUNT(*) FROM deleted_empty)
+ INTO v_rows;
+
+ DELETE FROM task_usage_hourly_dirty WHERE enqueued_at < p_to;
+
+ RETURN v_rows;
+END;
+$$;