credits: close each cycle so a pack cannot be spent twice (#12)
ci/woodpecker/push/woodpecker Pipeline failed
ci/woodpecker/push/woodpecker Pipeline failed
LiteLLM zeroes a team's `spend` at budget_reset_at but leaves max_budget
alone, and nothing in the portal ever reduced credit_balance. So every
monthly reset restored every credit pack already spent: a $15 member who
bought $50 and used all $65 got $65 again the next month.
Fix — record the draw when a cycle closes:
- new `members.credits_drawn` (credits consumed in CLOSED cycles);
credit_balance stays the lifetime purchased total so the "bought all-time"
display never changes meaning.
- `compute_max_budget` caps at allowance + credits STILL AVAILABLE
(purchased − drawn). Spend inside the current cycle still does not shrink
the cap, so a credit add keeps raising it 1:1.
- `apply_cycle_draw` writes a NEGATIVE credit_ledger row per closed cycle,
deduped on reference `cycle-close:<email>:<cycle>`; the cycle's spend is
summed from LiteLLM_SpendLogs over the exact anchor-day window.
- `close_credit_cycles` runs every 10 min via the new Cloudron scheduler task
(credit_cycle_close.sh) and again as a catch-up inside /admin/sweep.
- CREDIT_CLOSE_FROM (default 2026-11-28) stops it charging cycles that
started before the fix: credits already regranted are forgiven rather than
clawed back mid-cycle.
- /admin/credits/{email} now reports credits_drawn.
Tests: tests/test_credit_cycle_close.py covers the cap arithmetic, the
issue's worked example, draw idempotence and the available-credit cap.
This commit is contained in:
1 parent
bcdc0416e2
commit
fe898905b4
5 files changed
+465
-18
No files matched your search
+2
-1
@@ -10,8 +10,9 @@ RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY app/ ./app/
|
||||
COPY sweep.sh /app/code/sweep.sh
|
||||
COPY service_sync.sh /app/code/service_sync.sh
|
||||
COPY credit_cycle_close.sh /app/code/credit_cycle_close.sh
|
||||
COPY metrics_snapshot.py /app/code/metrics_snapshot.py
|
||||
RUN chmod +x /app/code/sweep.sh /app/code/service_sync.sh /app/code/metrics_snapshot.py
|
||||
RUN chmod +x /app/code/sweep.sh /app/code/service_sync.sh /app/code/credit_cycle_close.sh /app/code/metrics_snapshot.py
|
||||
|
||||
# Run as root (the base image default). Cloudron's sandboxing (read-only
|
||||
# rootfs, AppArmor, dropped capabilities) still applies to root inside the
|
||||
|
||||
Reference in new issue
Block a user