fix(credits): make the monthly refill a floor, not an assignment

Merged
SW
3mo ago
+136-8

Implements the third defect in recoupable/chat#1960. Row 5 of that issue's PR matrix. Independent of the auto-recharge PRs; no shared files.

checkAndResetCredits.ts L54-60 writes remaining_credits: isPro ? PRO_CREDITS : DEFAULT_CREDITS unconditionally once a monthly refill is due. A "refill" that lowers a balance is not a refill: any account holding more than its plan total, from a top-up or an admin grant, is cut on its next balance read. And because the refill is lazy and read-triggered, the loss fires on a GET — reading a balance is what destroys it, and nothing records that it happened.

Measured on prod 2026-08-17:

accounts with a credits row1,714
holding more than 333 (free plan total)119
holding >333 with a reset already pending50
holding >333 with a reset due inside 30 days117
holding more than 9,999 (pro plan total)4

What changes

-  const refilled = await updateCreditsUsage({
-    account_id: accountId,
-    updates: {
-      remaining_credits: isPro ? PRO_CREDITS : DEFAULT_CREDITS,
-      timestamp: new Date().toISOString(),
-    },
-  });
+  const planTotal = isPro ? PRO_CREDITS : DEFAULT_CREDITS;
+  const remaining = creditsUsage.remaining_credits ?? 0;
+
+  const updates: Partial<Pick<CreditsUsage, "remaining_credits" | "timestamp">> = {
+    timestamp: new Date().toISOString(),
+  };
+  if (remaining < planTotal) updates.remaining_credits = planTotal;
+
+  const refilled = await updateCreditsUsage({ account_id: accountId, updates });

Two decisions worth flagging, because the issue's Fix text asks for something slightly self-contradictory:

The timestamp always advances, so the write is not skipped. The issue says to "skip the updateCreditsUsage call entirely when remaining_credits >= planTotal" and to "still bump timestamp in that branch". Those cannot both hold — and the issue's own reasoning says why the timestamp must win: without it the account re-evaluates as refill-due on every subsequent read, forever. So the write stays; what is skipped is the remaining_credits field, not the call. The issue's Done-when ("credits_usage.timestamp advances in all three cases") agrees.

remaining_credits is omitted rather than written as max(remaining, planTotal). Both satisfy the floor rule, but writing back a value read moments earlier would resurrect credits a concurrent deduction had spent in between. Omitting the field leaves the column alone and closes that window instead of preserving it.

No grant provenance is needed. chat#1948 deferred this fix on the grounds that protecting a grant "would mean teaching checkAndResetCredits about grant provenance", and said to revisit if a granted account were ever found reset in the wild. It does not need provenance: a refill that never reduces protects a granted balance automatically, without the read path knowing where the balance came from. That is why the fix is much smaller than #1948 assumed, and there is a test asserting exactly it.

Verification

TDD, red before green. Added a describe("the refill is a floor, not an assignment") block with six cases, then ran it: RED, 4 failed / 9 passed (the four asserting the update payload for at-or-above-total balances). Implemented, then GREEN, 13 passed.

CaseBalancePlan totalExpected updateResult
below the total, free100333{ remaining_credits: 333, timestamp }✅
above the total, free9,999333{ timestamp } only, balance stays 9,999✅
exactly at the total333333{ timestamp } only✅
above the total, pro25,0009,999{ timestamp } only, balance stays 25,000✅
admin grant on a free account9,999333no remaining_credits in the update, balance stays 9,999✅
newly-subscribed refill trigger12,0009,999{ timestamp } only, balance stays 12,000✅

The seven pre-existing tests, including both original refill-to-plan-total cases, still pass unmodified.

Full runs:

CheckResult
vitest run lib/credits lib/admins app/api/accounts44 files / 257 tests passed
eslint lib/creditsclean
tsc --noEmit202 errors, identical to baseline, zero in either file this PR touches

Not yet done: the issue's live Done-when checks — seed an account at 9,999 on the free plan with a month-old timestamp on preview and read it back, and after deploy confirm none of the 50 at-risk prod accounts lose credits. Flagging rather than implying it.

Merge order

Independent of the auto-recharge PRs and can land at any point. Two things depend on it:

  • docs#300 documents the floor rule and should merge after this reaches prod, not before.
  • The follow-on PR retiring getGrantExpiresAt is only correct once this has shipped (row 6 of chat#1960).

Summary by cubic

Stops monthly refills from cutting balances by making the refill a floor instead of an assignment. Previously a due refill set remaining_credits to the plan total; now it only raises balances below the total and always advances timestamp.

  • In checkAndResetCredits: compute the plan total; on a due refill write timestamp and only set remaining_credits when below the total. Balances at or above the total are left unchanged.
  • Omits remaining_credits instead of writing back max(remaining, planTotal) to avoid resurrecting credits in concurrent-deduction races.
  • Tests cover below/at/above totals, free vs. pro, admin grant, and newly-subscribed refills; existing tests remain green.

Rollout

  • No migration. Verify that balances above plan totals do not decrease on read.