feat(database): add get_credit_spend_digest aggregation RPC
Merged
AR
4mo ago+84+84+01234567890123456789-0-0-0123456789
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 withusage_eventsdata — confirm ranked array (highesttotal_centsfirst), correct per-accountby_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
jsonbarray (highesttotal_centsfirst); 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.
- Single-query RPC returning a ranked
-
Bug Fixes
- Restrict execution to
service_roleonly (drop SECURITY DEFINER, revoke PUBLIC) and clampp_limitto [1, 1000] with default 10.
- Restrict execution to