Files
loki/drizzle/0054_outgoing_bedlam.sql
776d12b625 feat(ai-budget): enforce the ration, and bill it from the provider's own count (#304)
#303 shipped the fair-share policy with nothing calling it. This wires it in, so
the free daily pool is actually divided instead of merely divisible.

  ai_spend            one row per (user, UTC day). A rollup, not an event log:
                      the only questions asked are "what has this user spent
                      today" and "how many drew today", both on the hot path of
                      every turn. UTC because the vendors reset on UTC midnight;
                      bucketing on local midnight would hand out a share against
                      a budget that had not refilled.
  dayCapacityTokens() sums the daily budget of every KEYED provider. A vendor
                      whose key is absent contributes nothing, however generous
                      its tier — counting it would ration users against tokens
                      that cannot be reached.
  askLoki             gates the WHOLE turn once, before any provider is called.
                      Gating per path would burn the budget on two fallbacks and
                      still say no.

BILLED FROM REALITY, NOT FROM A GUESS. `llm.ts` now reads the provider's own
`usage.total_tokens` and `loop.ts` sums it across every round AND the repair
pass. Charging only the final call would under-count the expensive turns by the
most — precisely the ones worth rationing. Admission still uses an estimate
because it must decide before anything is spent, and it is deliberately on the
high side: under-estimating admits turns the pool cannot cover, which produces
the late-day wall this whole mechanism exists to prevent.

Booked on paths that are easy to forget: a turn that produced no usable text
(the tokens were spent anyway), a repair pass that was discarded (same), and the
degraded Groq fallback (it draws on the same pool, so a user degraded onto it
would otherwise spend the shared day for free).

THE GATE FAILS OPEN. If the ledger cannot be read, the turn is admitted.
Rationing is a nicety; a database hiccup becoming "Loki is down" is not a trade
anyone would choose. This fleet has already lost a day to a guard that turned a
QUESTION into a fatal step, so the test asserting it is the one that matters
most here.

The two refusals keep their distinct meanings all the way out to the user:
`paced` carries a retry and explains WHY there is a wait ("so everyone gets a
turn" is a reason a person accepts; an unexplained refusal reads as breakage),
`share-spent` carries none and says when it resets. Offering a retry that cannot
succeed today is the "try again shortly" lie in another costume.

Migration is additive only — CREATE TABLE + FK + index, no destructive
statements. The unique (user, day) index is load-bearing: without it two
concurrent turns both read zero, both insert, and that user gets two rows and
twice the share. The increment happens inside the database.

Tests: 10 for the gate (fail-open, capacity SSOT, both refusals, a newcomer
admitted at any hour), on injectable seams so they need no database — the
behaviour worth proving is exactly what a DB-dependent test would not cover.

tsc clean · eslint 0 errors · 85/85 unit files · 150 home tests · design ok ·
desktop ok.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 14:20:08 +00:00

12 lines
614 B
SQL

CREATE TABLE "ai_spend" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" uuid NOT NULL,
"day" date NOT NULL,
"tokens" integer DEFAULT 0 NOT NULL,
"turns" integer DEFAULT 0 NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "uq_ai_spend_user_day" UNIQUE("user_id","day")
);
--> statement-breakpoint
ALTER TABLE "ai_spend" ADD CONSTRAINT "ai_spend_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "idx_ai_spend_day" ON "ai_spend" USING btree ("day");