mirror of
https://github.com/multica-ai/multica.git
synced 2026-07-05 13:29:44 +02:00
* fix(server): aggregate task_usage into daily rollup table to cut DB load ListRuntimeUsage previously did a SUM(...) GROUP BY DATE(created_at), provider, model over the raw task_usage stream once per runtime row on the runtimes list and once per detail page load, scaling O(events) per call. This is the hot read path responsible for sustained load on Postgres. Switch the read path to a materialized daily rollup table maintained by a pg_cron job: - 072_task_usage_daily_rollup: schema for task_usage_daily + task_usage_rollup_state, plus rollup_task_usage_daily_window(p_from, p_to) (window primitive used by both cron and offline backfill, idempotent via ON CONFLICT DO UPDATE adding deltas) and rollup_task_usage_daily() (cron entry point — pg_try_advisory_lock(4242) for serialization, watermark advancement, 5-minute safety lag for late-visible inserts). Also adds idx_task_usage_created_at to help the two lazy endpoints (ListRuntimeUsageByAgent / GetRuntimeUsageByHour) that still hit the raw table. - 073_task_usage_daily_pgcron: CREATE EXTENSION IF NOT EXISTS pg_cron in a DO/EXCEPTION block (mirrors the migration 032 pg_bigm pattern so envs without shared_preload_libraries=pg_cron skip gracefully) and schedules rollup_task_usage_daily() every 5 minutes when the extension is present. - queries/runtime_usage.sql ListRuntimeUsage rewritten to read from task_usage_daily; sqlc regenerated. Other usage queries unchanged. - cmd/backfill_task_usage_daily: one-shot Go command that walks task_usage in monthly slices through rollup_task_usage_daily_window, then stamps the watermark to now()-5m so the cron resumes cleanly. Run once after migrations have applied, before relying on the rollup. - runtime_test.go: TestGetRuntimeUsage_BucketsByUsageTime now invokes rollup_task_usage_daily_window after fixture inserts so the handler sees the rolled-up rows. Synthetic daily rows cleaned up after each test. - runtime_rollup_test.go: new tests covering aggregation correctness, idempotency contract of ON CONFLICT DO UPDATE, and the watermark advancing exactly to now()-5m via the cron entry point. Deployment order: apply migrations → run backfill_task_usage_daily once → pg_cron picks up subsequent windows automatically. Today bucket may be up to ~10 minutes stale (5 min cron + 5 min lag) by design. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: multica-agent <github@multica.ai> * fix(server): make task_usage_daily rollup safe to overlap, replay, and correct Addresses 4 review blockers on the original PR: 1. Cron/backfill double-count race: the rollup function is now idempotent. Window calls find DIRTY KEYS via task_usage.updated_at, then RECOMPUTE each bucket from ground truth and REPLACE the daily row (no more additive ON CONFLICT). Cron and backfill can now overlap safely. 2. Silent pg_cron absence: the read path is gated behind a new USAGE_DAILY_ROLLUP_ENABLED feature flag (default off). The raw task_usage scan is preserved as the fallback. Operators flip the flag per-environment after backfill + cron are confirmed healthy (task_usage_rollup_lag_seconds() helper added for monitoring). 3. UpsertTaskUsage corrections invisible to rollup: added task_usage.updated_at column (default now(), backfilled from created_at), and bumped it on conflict. Corrections now mark the bucket dirty and the next window call recomputes it correctly. 4. CREATE INDEX blocking writes on hot table: split into separate single-statement migrations using CREATE INDEX CONCURRENTLY (074, 075), matching the 035/067 pattern. Also: cron.schedule() removed from migrations entirely. Migration 076 only enables the extension (gracefully on unsupported envs); the actual schedule is a documented operator runbook step that runs AFTER backfill. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: multica-agent <github@multica.ai> * fix(server): trigger-driven invalidation + online-safe migration for task_usage_daily Round-2 review feedback on PR #2256: 1. Add explicit dirty-bucket queue (task_usage_daily_dirty) populated by triggers on agent_task_queue (UPDATE OF runtime_id, DELETE) and task_usage (DELETE). The rollup window function drains both this queue and the updated_at-based discovery, so runtime reassignment and issue-cascade deletes no longer leave the rollup divergent from the raw query. Triggers join via agent (not issue) to look up workspace_id, because when the cascade comes from issue, the issue row is already gone by the time atq's BEFORE DELETE fires; agent stays alive. 2. Make migration 072 online-safe: only ADD COLUMN updated_at TIMESTAMPTZ (nullable, no default → metadata-only ALTER, no row rewrite) and a separate ALTER for SET DEFAULT now() (also metadata-only). No bulk UPDATE on the hot task_usage table. The rollup window function's dirty_keys CTE handles legacy NULL rows via an OR branch, supported by partial index idx_task_usage_created_at_legacy. 3. Refresh stale documentation in cmd/backfill_task_usage_daily/main.go header to describe the current recompute/replace semantics, idempotent re-runnability, and the actual migration numbering (072..077). Tests: - TestRollupTaskUsageDaily_InvalidationOnReassign: verifies usage moves between runtime buckets after ReassignTasksToRuntime-style update. - TestRollupTaskUsageDaily_InvalidationOnIssueDelete: verifies daily bucket is cleared after issue delete cascades through atq → task_usage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: multica-agent <github@multica.ai> * fix(server): close dirty-queue race + move legacy partial index to its own concurrent migration Round-3 review feedback on PR #2256: 1. Blocker: dirty-queue invalidations could be silently lost under concurrency. ON CONFLICT DO NOTHING let a late trigger see the row already enqueued, no-op, and then the rollup drain (WHERE enqueued_at < p_to) would delete the original row — losing the late invalidation. Switched all three trigger enqueue paths to ON CONFLICT DO UPDATE SET enqueued_at = GREATEST(existing, EXCLUDED.enqueued_at), so any invalidation arriving during a rollup tick keeps enqueued_at > p_to (p_to = now() - 5min) and survives the post-tick drain. 2. High: idx_task_usage_created_at_legacy (partial index on hot task_usage table) was being created in the regular 077 migration without CONCURRENTLY. Moved to new migration 078 with CREATE INDEX CONCURRENTLY, matching the pattern of 074/075. 077's down migration leaves the index alone (it is owned by 078). 3. Minor: gofmt -w on runtime_rollup_test.go and backfill_task_usage_daily/main.go (tabs were lost in the original heredoc append). PR description rewritten to describe the current recompute/replace + dirty queue + feature flag design and the 072..078 migration ordering. Tests still green: TestRollupTaskUsageDaily_* (including both new invalidation regressions), TestGetRuntimeUsage_*, TestWorkspaceUsage_*. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: multica-agent <github@multica.ai> * fix(server): unify workspace_id source via agent in rollup window function Round-4 review feedback (J) on PR #2256: M1 (must-fix): The dirty queue triggers resolved workspace_id via `agent.workspace_id`, but the window function's `dirty_from_updates` discovery and `recomputed` recompute join used `issue.workspace_id`. There is no schema-level FK guaranteeing `agent.workspace_id == issue.workspace_id`. Any divergence (future cross-workspace task scenarios, data repairs, migration bugs) would cause: - dirty queue rows with workspace_id from agent - recompute join filtering by workspace_id from issue - 0 matches in recompute → bucket erroneously hits the deleted_empty branch and the daily row is silently dropped - dirty_from_updates path attributing usage to the wrong workspace Replaced both CTEs to JOIN agent (not issue) so trigger / discovery / recompute share one workspace_id source. Comment in 077 explains the constraint. N1: Refreshed two stale references in cmd/backfill_task_usage_daily/main.go (header now says "072..078"; stampWatermark warning now mentions migration 073, where the rollup state table is actually introduced). Test: New TestRollupTaskUsageDaily_WorkspaceMismatch constructs an atq with agent.workspace_id != issue.workspace_id, asserts the bucket lands under agent's workspace (not issue's), and re-asserts after a runtime reassign in the foreign workspace. Acts as a canary if the schema invariant changes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: multica-agent <github@multica.ai> --------- Co-authored-by: Eve <eve@multica.ai> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: multica-agent <github@multica.ai> Co-authored-by: Devv <devv@Devvs-Mac-mini.local>
228 lines
9.3 KiB
PL/PgSQL
228 lines
9.3 KiB
PL/PgSQL
-- Daily rollup table for `task_usage`. Background: the dashboard query
|
||
-- ListRuntimeUsage runs `SUM() GROUP BY DATE(created_at), provider, model`
|
||
-- against the raw event stream and is called once per runtime row on the
|
||
-- runtimes list (plus once per detail page load), so it dominates DB load
|
||
-- as event volume grows. We materialise the day-bucketed aggregate here
|
||
-- so reads scan O(days × providers × models) rows instead of O(events).
|
||
--
|
||
-- All query dimensions are denormalised into the table so reads never
|
||
-- need to join `agent_task_queue`. The PK doubles as the upsert key for
|
||
-- the rollup worker.
|
||
CREATE TABLE task_usage_daily (
|
||
bucket_date DATE NOT NULL,
|
||
workspace_id UUID NOT NULL,
|
||
runtime_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,
|
||
event_count BIGINT NOT NULL DEFAULT 0,
|
||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||
PRIMARY KEY (bucket_date, workspace_id, runtime_id, provider, model)
|
||
);
|
||
|
||
-- Primary read path: runtime detail page + runtimes-list cost cell, both
|
||
-- filter by runtime_id and order by date DESC. bucket_date DESC in the
|
||
-- index lets the query avoid an extra sort.
|
||
CREATE INDEX idx_task_usage_daily_runtime_date
|
||
ON task_usage_daily (runtime_id, bucket_date DESC);
|
||
|
||
-- Workspace-wide aggregations hit this index instead of fanning out per
|
||
-- runtime.
|
||
CREATE INDEX idx_task_usage_daily_workspace_date
|
||
ON task_usage_daily (workspace_id, bucket_date DESC);
|
||
|
||
-- Single-row state table tracking how far the rollup worker has consumed.
|
||
CREATE TABLE task_usage_rollup_state (
|
||
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
||
watermark_at TIMESTAMPTZ NOT NULL DEFAULT '1970-01-01 00:00:00+00',
|
||
last_run_started_at TIMESTAMPTZ,
|
||
last_run_finished_at TIMESTAMPTZ,
|
||
last_run_rows BIGINT NOT NULL DEFAULT 0,
|
||
last_error TEXT
|
||
);
|
||
INSERT INTO task_usage_rollup_state (id) VALUES (1) ON CONFLICT DO NOTHING;
|
||
|
||
-- Window-based aggregation primitive. Used by both the cron-driven
|
||
-- watermark advancer and the offline backfill command, so they stay
|
||
-- byte-identical in their semantics. Returns the number of output rows
|
||
-- touched.
|
||
--
|
||
-- IDEMPOTENCY CONTRACT (this is the important bit):
|
||
-- For every (bucket_date, workspace_id, runtime_id, provider, model)
|
||
-- key that has at least one task_usage row whose `updated_at` falls in
|
||
-- [p_from, p_to), this function REPLACES the corresponding daily row
|
||
-- with the SUM of *all* task_usage rows for that key (regardless of
|
||
-- their updated_at). It does NOT add a delta.
|
||
--
|
||
-- Consequences:
|
||
-- * Replaying the same window is safe — the row is rebuilt from raw
|
||
-- each time, so the result converges.
|
||
-- * Two callers (cron + backfill) processing overlapping windows is
|
||
-- safe — both write the same value.
|
||
-- * `UpsertTaskUsage` corrections that overwrite token counts are
|
||
-- captured: the corrected row's updated_at gets bumped, the next
|
||
-- window picks up its bucket key, and the bucket is recomputed
|
||
-- from current truth.
|
||
--
|
||
-- Cost: the recompute reads ALL task_usage rows for each dirty bucket,
|
||
-- not just the windowed slice. In steady state only "today" buckets are
|
||
-- dirty (a handful of keys per active runtime), so this stays cheap.
|
||
-- During backfill the entire history's bucket keys become dirty once;
|
||
-- the backfill walks history in monthly slices to bound the working
|
||
-- set per call.
|
||
CREATE OR REPLACE FUNCTION rollup_task_usage_daily_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_keys AS (
|
||
SELECT DISTINCT
|
||
DATE(tu.created_at) AS bucket_date,
|
||
i.workspace_id AS workspace_id,
|
||
atq.runtime_id AS runtime_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 issue i ON i.id = atq.issue_id
|
||
WHERE atq.runtime_id IS NOT NULL
|
||
AND (
|
||
-- Steady state: rows updated within the watermark window.
|
||
-- Hits idx_task_usage_updated_at directly.
|
||
(tu.updated_at >= p_from AND tu.updated_at < p_to)
|
||
-- Legacy rows from before migration 072 (updated_at IS NULL)
|
||
-- — discoverable via created_at + the partial index added
|
||
-- in 077. Steady-state windows after backfill never include
|
||
-- historical dates, so this branch is a no-op once the
|
||
-- backfill has swept history.
|
||
OR (tu.updated_at IS NULL
|
||
AND tu.created_at >= p_from
|
||
AND tu.created_at < p_to)
|
||
)
|
||
),
|
||
recomputed AS (
|
||
SELECT
|
||
dk.bucket_date,
|
||
dk.workspace_id,
|
||
dk.runtime_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,
|
||
COUNT(*)::bigint AS event_count
|
||
FROM dirty_keys dk
|
||
JOIN agent_task_queue atq ON atq.runtime_id = dk.runtime_id
|
||
JOIN issue i ON i.id = atq.issue_id
|
||
AND i.workspace_id = dk.workspace_id
|
||
JOIN task_usage tu ON tu.task_id = atq.id
|
||
AND tu.provider = dk.provider
|
||
AND tu.model = dk.model
|
||
AND DATE(tu.created_at) = dk.bucket_date
|
||
GROUP BY 1, 2, 3, 4, 5
|
||
)
|
||
INSERT INTO task_usage_daily AS d (
|
||
bucket_date, workspace_id, runtime_id, provider, model,
|
||
input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
|
||
event_count
|
||
)
|
||
SELECT
|
||
bucket_date, workspace_id, runtime_id, provider, model,
|
||
input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
|
||
event_count
|
||
FROM recomputed
|
||
ON CONFLICT (bucket_date, workspace_id, runtime_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,
|
||
event_count = EXCLUDED.event_count,
|
||
updated_at = now();
|
||
|
||
GET DIAGNOSTICS v_rows = ROW_COUNT;
|
||
RETURN v_rows;
|
||
END;
|
||
$$;
|
||
|
||
-- Cron entry point. Advances the watermark by one window each call.
|
||
--
|
||
-- Invariants:
|
||
-- * `pg_try_advisory_lock(4242)` serialises overlapping ticks.
|
||
-- * The window upper bound is `now() - 5 minutes`. The lag exists
|
||
-- because `task_usage` rows are written from a separate transaction;
|
||
-- a row with updated_at = T can become visible to this snapshot at
|
||
-- some t > T. 5 minutes is a generous bound on that visibility delay
|
||
-- and keeps the dashboard "today" bucket at most ~10 min stale
|
||
-- (5 min lag + 5 min cron period).
|
||
-- * On error we record `last_error` and re-raise; the watermark is NOT
|
||
-- advanced because the UPDATE that advances it only runs after the
|
||
-- upsert succeeds.
|
||
-- * SAFE TO RUN CONCURRENTLY WITH BACKFILL: the window primitive is
|
||
-- idempotent (see contract above), so even if cron fires while the
|
||
-- offline backfill is also walking history, the worst case is some
|
||
-- bucket gets written twice with the same value.
|
||
CREATE OR REPLACE FUNCTION rollup_task_usage_daily()
|
||
RETURNS BIGINT
|
||
LANGUAGE plpgsql
|
||
AS $$
|
||
DECLARE
|
||
v_lock_ok BOOLEAN;
|
||
v_from TIMESTAMPTZ;
|
||
v_to TIMESTAMPTZ;
|
||
v_rows BIGINT := 0;
|
||
BEGIN
|
||
SELECT pg_try_advisory_lock(4242) INTO v_lock_ok;
|
||
IF NOT v_lock_ok THEN
|
||
RETURN 0;
|
||
END IF;
|
||
|
||
BEGIN
|
||
UPDATE task_usage_rollup_state
|
||
SET last_run_started_at = now(),
|
||
last_error = NULL
|
||
WHERE id = 1
|
||
RETURNING watermark_at INTO v_from;
|
||
|
||
v_to := now() - INTERVAL '5 minutes';
|
||
|
||
IF v_from < v_to THEN
|
||
v_rows := rollup_task_usage_daily_window(v_from, v_to);
|
||
|
||
UPDATE task_usage_rollup_state
|
||
SET watermark_at = v_to,
|
||
last_run_finished_at = now(),
|
||
last_run_rows = v_rows
|
||
WHERE id = 1;
|
||
ELSE
|
||
UPDATE task_usage_rollup_state
|
||
SET last_run_finished_at = now(),
|
||
last_run_rows = 0
|
||
WHERE id = 1;
|
||
END IF;
|
||
|
||
PERFORM pg_advisory_unlock(4242);
|
||
RETURN v_rows;
|
||
EXCEPTION WHEN OTHERS THEN
|
||
UPDATE task_usage_rollup_state
|
||
SET last_error = SQLERRM,
|
||
last_run_finished_at = now()
|
||
WHERE id = 1;
|
||
PERFORM pg_advisory_unlock(4242);
|
||
RAISE;
|
||
END;
|
||
END;
|
||
$$;
|