Monthly credit reset also restores all credit packs ever used (!) #12

Open
opened 2026-11-27 20:03:35 +00:00 by bo · 4 comments

By example:

  • Member buys $15/month membership
  • Member buys $50 credit pack
  • Member uses all $65 of their credits
  • The next monthly reset, Member is given $65 of new allowance instead of $15

In the code, nothing ever subtracts the used credits from credit_balance, so they all get restored each month.

[Claude details below]


Where

  • compute_max_budget (app/main.py): max_budget = allowance + credit_balance, and "credits used" is derived only from the current cycle's team spend.
  • credit_balance only changes on purchases, admin adjustments, shortfall credits and guest returns (add_credits, direct UPDATEs). No code path records credits consumed by usage, despite the credit_ledger comment ("spends drawn against credits").
  • LiteLLM v1.108.3 ResetBudgetJob._reset_budget_common sets spend = 0 at budget_reset_at (budget_rollover is not enabled in code/litellm) and leaves max_budget unchanged.

Present since credits shipped (63acea2); 052a109 changed the within-cycle cap but not this.

Reproduce

Offline (no gateway needed). From a checkout of main:

DB_PATH=$(mktemp -d)/p.db python3 -c '
from app.main import compute_max_budget as cap
print("cycle 1, $25 spent:", cap(15, 20, 25))
print("after reset:       ", cap(15, 20, 0))'
cycle 1, $25 spent: {'max_budget': 35, 'allowance_used': 15, 'credits_used': 10, 'credits_remaining': 10}
after reset:        {'max_budget': 35, 'allowance_used': 0, 'credits_used': 0.0, 'credits_remaining': 20.0}

The member used $10 of their $20, yet after the reset credits_remaining is $20 and the cap is still $35. Since credit_balance is never reduced, these are exactly the inputs the portal uses after a real reset.

Live, on a test account (costs a few cents). Use a small allowance so it takes little real spend. All /admin/* calls need X-Admin-Token.

  1. POST /admin/set-balance {"email": "<test>", "balance": 0.10}: allowance $0.10.
  2. POST /admin/set-credits {"email": "<test>", "add": 0.20, "reason": "test credits (will revert)"}: cap is now $0.30.
  3. Spend about $0.15 through the gateway with the test member's key. GET /admin/overview shows credits_used ≈ 0.05 and credits_remaining ≈ 0.15 for the member.
  4. Force a reset: UPDATE "LiteLLM_TeamTable" SET budget_reset_at = now() - interval '1 minute' WHERE team_alias = 'member:<test>'; then wait for LiteLLM's reset job (about 10 minutes).
  5. GET /admin/credits/<test> and GET /admin/overview.

Expected: credit_balance 0.15, a negative ledger row for the $0.05 used, team max_budget 0.25.
Actual: credit_balance 0.20, no draw row, credits_remaining 0.20, team max_budget 0.30.

Cleanup: set-balance back to 15, and set-credits {"add": -0.20, "reason": "revert test credits"} (paired reversal, per ops-docs/maintenance/ledger-test-rows.md).

Impact

Every member who has bought credit packs and used them past their allowance regains those credits at each reset. The co-op ends up giving away inference it paid providers for, and the dashboard's credit figures don't match the ledger. There's no member-facing error, so it won't show up as a complaint.

Suggested fix

Close each cycle: when a reset zeroes a member's spend, subtract max(0, cycle_spend - allowance) from credit_balance with a ledger row, then re-sync the cap.

By example: * Member buys $15/month membership * Member buys $50 credit pack * Member uses all $65 of their credits * The next monthly reset, Member is given **$65 of new allowance instead of $15** In the code, nothing ever subtracts the used credits from `credit_balance`, so they all get restored each month. **[Claude details below]** -------- ## Where - `compute_max_budget` (`app/main.py`): `max_budget = allowance + credit_balance`, and "credits used" is derived only from the **current** cycle's team spend. - `credit_balance` only changes on purchases, admin adjustments, shortfall credits and guest returns (`add_credits`, direct `UPDATE`s). No code path records credits consumed by usage, despite the `credit_ledger` comment ("spends drawn against credits"). - LiteLLM v1.108.3 `ResetBudgetJob._reset_budget_common` sets `spend = 0` at `budget_reset_at` (`budget_rollover` is not enabled in `code/litellm`) and leaves `max_budget` unchanged. Present since credits shipped (`63acea2`); `052a109` changed the within-cycle cap but not this. ## Reproduce **Offline (no gateway needed).** From a checkout of `main`: ```sh DB_PATH=$(mktemp -d)/p.db python3 -c ' from app.main import compute_max_budget as cap print("cycle 1, $25 spent:", cap(15, 20, 25)) print("after reset: ", cap(15, 20, 0))' ``` ``` cycle 1, $25 spent: {'max_budget': 35, 'allowance_used': 15, 'credits_used': 10, 'credits_remaining': 10} after reset: {'max_budget': 35, 'allowance_used': 0, 'credits_used': 0.0, 'credits_remaining': 20.0} ``` The member used $10 of their $20, yet after the reset `credits_remaining` is $20 and the cap is still $35. Since `credit_balance` is never reduced, these are exactly the inputs the portal uses after a real reset. **Live, on a test account (costs a few cents).** Use a small allowance so it takes little real spend. All `/admin/*` calls need `X-Admin-Token`. 1. `POST /admin/set-balance` `{"email": "<test>", "balance": 0.10}`: allowance $0.10. 2. `POST /admin/set-credits` `{"email": "<test>", "add": 0.20, "reason": "test credits (will revert)"}`: cap is now $0.30. 3. Spend about $0.15 through the gateway with the test member's key. `GET /admin/overview` shows `credits_used ≈ 0.05` and `credits_remaining ≈ 0.15` for the member. 4. Force a reset: `UPDATE "LiteLLM_TeamTable" SET budget_reset_at = now() - interval '1 minute' WHERE team_alias = 'member:<test>';` then wait for LiteLLM's reset job (about 10 minutes). 5. `GET /admin/credits/<test>` and `GET /admin/overview`. **Expected:** `credit_balance` 0.15, a negative ledger row for the $0.05 used, team `max_budget` 0.25. **Actual:** `credit_balance` 0.20, no draw row, `credits_remaining` 0.20, team `max_budget` 0.30. Cleanup: `set-balance` back to `15`, and `set-credits` `{"add": -0.20, "reason": "revert test credits"}` (paired reversal, per `ops-docs/maintenance/ledger-test-rows.md`). ## Impact Every member who has bought credit packs and used them past their allowance regains those credits at each reset. The co-op ends up giving away inference it paid providers for, and the dashboard's credit figures don't match the ledger. There's no member-facing error, so it won't show up as a complaint. ## Suggested fix Close each cycle: when a reset zeroes a member's spend, subtract `max(0, cycle_spend - allowance)` from `credit_balance` with a ledger row, then re-sync the cap.
Owner

Confirmed on the deployed image — your offline repro reproduces exactly (cap(15,20,25) → 35/10 used/10 left, then cap(15,20,0) → 35/0/20). Nothing writes a draw row, and no reset step re-derives the cap.

Live exposure (read-only, today): 38 active members hold $986 of purchased credits; 15 of them are past their $15 allowance this cycle by $454.74 — the amount that would have come back at their next resets. Guests hold $30 across 15 accounts but have no reset (budget_reset_at NULL), so they are not affected.

Fix is up as a draft PR: !13 (fix/credit-cycle-close). Approach:

  • members.credits_drawn records credits consumed in CLOSED cycles; credit_balance stays "total purchased" so the members' all-time figure keeps its meaning.
  • Cap = allowance + max(0, purchased − drawn). Current-cycle spend still does not shrink the cap (no inversion bug).
  • Cycle spend is summed from LiteLLM_SpendLogs over the exact anchor-day window, so there is no snapshot job and no race with LiteLLM's reset. The draw is a negative ledger row deduped on cycle-close:<email>:<cycle>.
  • Runs every 10 min from a new Cloudron scheduler task (credit_cycle_close.sh), plus a sweep catch-up.

Policy encoded, needs your call: CREDIT_CLOSE_FROM defaults to 2026-11-28, so cycles that started before the fix are forgiven — we don't claw back credits already regranted under the old code. Charging starts with each member's next full cycle. Two accounts holding credits have no anchor_day (one operator account, one org-backed account) and cannot be closed automatically; the operator account's credits behave as a collective expense until an anchor is set.

Not deployed: this changes member-visible caps and the money posture, so it needs your go-ahead before build + cloudron update.

Confirmed on the deployed image — your offline repro reproduces exactly (`cap(15,20,25)` → 35/10 used/10 left, then `cap(15,20,0)` → 35/0/20). Nothing writes a draw row, and no reset step re-derives the cap. **Live exposure (read-only, today):** 38 active members hold $986 of purchased credits; 15 of them are past their $15 allowance this cycle by **$454.74** — the amount that would have come back at their next resets. Guests hold $30 across 15 accounts but have no reset (`budget_reset_at` NULL), so they are not affected. **Fix is up as a draft PR:** !13 (`fix/credit-cycle-close`). Approach: - `members.credits_drawn` records credits consumed in CLOSED cycles; `credit_balance` stays "total purchased" so the members' all-time figure keeps its meaning. - Cap = `allowance + max(0, purchased − drawn)`. Current-cycle spend still does not shrink the cap (no inversion bug). - Cycle spend is summed from `LiteLLM_SpendLogs` over the exact anchor-day window, so there is no snapshot job and no race with LiteLLM's reset. The draw is a negative ledger row deduped on `cycle-close:<email>:<cycle>`. - Runs every 10 min from a new Cloudron scheduler task (`credit_cycle_close.sh`), plus a sweep catch-up. **Policy encoded, needs your call:** `CREDIT_CLOSE_FROM` defaults to 2026-11-28, so cycles that started before the fix are *forgiven* — we don't claw back credits already regranted under the old code. Charging starts with each member's next full cycle. Two accounts holding credits have no `anchor_day` (one operator account, one org-backed account) and cannot be closed automatically; the operator account's credits behave as a collective expense until an anchor is set. Not deployed: this changes member-visible caps and the money posture, so it needs your go-ahead before build + `cloudron update`.
Owner

Deployed: code/member-portal:20261127-fe89890 (manifest pinned, cloudron update), app running + healthy, live app/main.py and credit_cycle_close.sh hashes equal the repo, scheduler now lists credit_cycle_close.

Verified in the deployed image:

  • schema migration applied (members.credits_drawn present)
  • POST /admin/credit-cycle-close → {"status":"ok","considered":38,"closed":0,"credits_drawn":0.0,"skipped":2} (no cycles are past the CREDIT_CLOSE_FROM floor yet; the 2 skipped are the anchor-less operator accounts)
  • the 10-minute scheduler tick fired at 20:51 UTC and logged the same result
  • full draw path exercised against a COPY of the live DB with seeded spend: cycle closed, -25.00 ledger row at cycle-close:probe@example.invalid:2026-10-27, credits_drawn 25 per cycle, a replay drew 0, cap fell from 65 to 15, credit_balance unchanged at 50
  • /admin/overview and /broker/usage serve the new credits_remaining unchanged (drawn is 0 for everyone today)

Production draw proof comes at each member's first post-fix cycle boundary (earliest 2026-12-28 for anchor-day-28 members). Leaving this open until a real cycle-close: row exists.

Deployed: `code/member-portal:20261127-fe89890` (manifest pinned, `cloudron update`), app running + healthy, live `app/main.py` and `credit_cycle_close.sh` hashes equal the repo, scheduler now lists `credit_cycle_close`. Verified in the deployed image: - schema migration applied (`members.credits_drawn` present) - `POST /admin/credit-cycle-close` → `{"status":"ok","considered":38,"closed":0,"credits_drawn":0.0,"skipped":2}` (no cycles are past the `CREDIT_CLOSE_FROM` floor yet; the 2 skipped are the anchor-less operator accounts) - the 10-minute scheduler tick fired at 20:51 UTC and logged the same result - full draw path exercised against a COPY of the live DB with seeded spend: cycle closed, `-25.00` ledger row at `cycle-close:probe@example.invalid:2026-10-27`, `credits_drawn` 25 per cycle, a replay drew 0, cap fell from 65 to 15, `credit_balance` unchanged at 50 - `/admin/overview` and `/broker/usage` serve the new `credits_remaining` unchanged (drawn is 0 for everyone today) Production draw proof comes at each member's first post-fix cycle boundary (earliest 2026-12-28 for anchor-day-28 members). Leaving this open until a real `cycle-close:` row exists.
Owner

Full clawback applied on the operator's go-ahead: CREDIT_CLOSE_FROM=2026-09-28 (credits launch), deployed 20261127-3e01f72.

  • Drawn now: $78.90 across 8 members — 8 cycle-close: ledger rows, credits_drawn sum matches. No member-level figures are listed here.
  • Uncollectable: $9.20 across 2 members who consumed past what they had bought — clamped at zero, no debt, no negative row.
  • Deferred caps: 2. Their draw is recorded but the cap stays until their reset zeroes spend; a cap pushed under recorded spend would block every call until then. New deferral logic in the same deploy; unit tests cover draw-recorded/cap-deferred/cap-applied-after-reset.
  • Idempotent: a second run closed 0 and drew $0; ledger stays at 8 rows / $78.90.
  • Emails: 8 personalised correction notices plus 3 heads-up notices for the largest boundary draws (cycles closing Nov 28). All sends returned success.

Correction to my earlier estimate: $251/$415 were post-boundary simulations that counted cycles that had not yet reset. Those are normal closes under the fix, not recovered over-grants. The actual clawback of already-restored credits is $78.90; the remainder is ordinary charging from here.

Full clawback applied on the operator's go-ahead: `CREDIT_CLOSE_FROM=2026-09-28` (credits launch), deployed `20261127-3e01f72`. - **Drawn now: $78.90 across 8 members** — 8 `cycle-close:` ledger rows, `credits_drawn` sum matches. No member-level figures are listed here. - **Uncollectable: $9.20** across 2 members who consumed past what they had bought — clamped at zero, no debt, no negative row. - **Deferred caps: 2.** Their draw is recorded but the cap stays until their reset zeroes spend; a cap pushed under recorded spend would block every call until then. New deferral logic in the same deploy; unit tests cover draw-recorded/cap-deferred/cap-applied-after-reset. - **Idempotent:** a second run closed 0 and drew $0; ledger stays at 8 rows / $78.90. - **Emails:** 8 personalised correction notices plus 3 heads-up notices for the largest boundary draws (cycles closing Nov 28). All sends returned success. Correction to my earlier estimate: $251/$415 were post-boundary simulations that counted cycles that had not yet reset. Those are normal closes under the fix, not recovered over-grants. The actual clawback of already-restored credits is $78.90; the remainder is ordinary charging from here.
Owner

Outcome — fixed, clawed back, and communicated.

Deployed: code/member-portal:20261127-3e01f72 (manifest pinned, cloudron update, running + healthy, live app/main.py hash matches the repo). Credit cycles now close every 10 minutes and draw credits used above the $15 allowance.

Clawback applied (CREDIT_CLOSE_FROM=2026-09-28, credits launch): $78.90 across 8 members, recorded as negative credit_ledger rows keyed cycle-close:<email>:<cycle> with credits_drawn updated. No member-level figures are listed here.

$9.20 uncollectable (2 members consumed past what they had purchased): clamped at zero, no debt, no negative balance.

Caps: 6 applied immediately; 2 deferred until their reset zeroes recorded spend — pushing a cap under current spend would refuse every call until then. The draw is already on the books.

Emails: 11 sent from info@inference.coop, all successful — 8 personalised correction notices and 3 heads-up notices for members whose cycles close at the next boundary with the largest draws.

Idempotency verified: a second run closed 0 cycles and drew $0; ledger remains 8 rows / $78.90.

Correction to the earlier estimate: the $251/$415 figures counted cycles that had not yet reset. Those are normal closes under the fix, not recovered over-grants; the actual clawback of already-restored credits is $78.90.

Remaining monitoring is the scheduled job itself: each cycle closes at the member's anchor day, and deferred caps land at the first tick after that member's reset.

**Outcome — fixed, clawed back, and communicated.** **Deployed:** `code/member-portal:20261127-3e01f72` (manifest pinned, `cloudron update`, running + healthy, live `app/main.py` hash matches the repo). Credit cycles now close every 10 minutes and draw credits used above the $15 allowance. **Clawback applied** (`CREDIT_CLOSE_FROM=2026-09-28`, credits launch): **$78.90 across 8 members**, recorded as negative `credit_ledger` rows keyed `cycle-close:<email>:<cycle>` with `credits_drawn` updated. No member-level figures are listed here. **$9.20 uncollectable** (2 members consumed past what they had purchased): clamped at zero, no debt, no negative balance. **Caps:** 6 applied immediately; 2 deferred until their reset zeroes recorded spend — pushing a cap under current spend would refuse every call until then. The draw is already on the books. **Emails:** 11 sent from info@inference.coop, all successful — 8 personalised correction notices and 3 heads-up notices for members whose cycles close at the next boundary with the largest draws. **Idempotency verified:** a second run closed 0 cycles and drew $0; ledger remains 8 rows / $78.90. **Correction to the earlier estimate:** the $251/$415 figures counted cycles that had not yet reset. Those are normal closes under the fix, not recovered over-grants; the actual clawback of already-restored credits is $78.90. Remaining monitoring is the scheduled job itself: each cycle closes at the member's anchor day, and deferred caps land at the first tick after that member's reset.
Sign in to join this conversation.
No labels
2 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: code/member-portal#12