feat(database): add get_credit_spend_digest aggregation RPC

Merged
AR
4mo ago
+84-0

Adds get_credit_spend_digest(p_since timestamptz, p_limit int default 10) — a single-query aggregation over usage_events that returns the top-N accounts by total credits spent over a time window, each with turn count, token totals, main-vs-subagent split, and a per-model cents breakdown, enriched with account name + most-recent email. Empty window returns []. Powers the credit-spend visibility digest cron (chat#1767).

Test plan

  • select get_credit_spend_digest(now() - interval '7 days', 10); against a DB with usage_events data — confirm ranked array (highest total_cents first), correct per-account by_model / token / split fields, and [] for an empty window.

Summary by cubic

Add get_credit_spend_digest(p_since timestamptz, p_limit int = 10) to aggregate usage_events and return the top-N accounts by credits spent over a time window. Powers the credit-spend visibility digest cron (chat#1767). Also trims the function header comment for clarity.

  • New Features

    • Single-query RPC returning a ranked jsonb array (highest total_cents first); empty window returns [].
    • Includes per-account totals (turns, tokens, tool_calls, main/subagent, per-model with NULL -> unknown) plus account name and most-recent email.
  • Bug Fixes

    • Restrict execution to service_role only (drop SECURITY DEFINER, revoke PUBLIC) and clamp p_limit to [1, 1000] with default 10.