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
+263
-17
@@ -1278,6 +1278,12 @@ def get_db() -> sqlite3.Connection:
|
||||
# exhausted within a cycle.
|
||||
if "credit_balance" not in cols:
|
||||
conn.execute("ALTER TABLE members ADD COLUMN credit_balance REAL NOT NULL DEFAULT 0")
|
||||
# Migration: credits_drawn — credits consumed in CLOSED cycles (issue #12).
|
||||
# `credit_balance` is the lifetime purchased total (display: "bought $X
|
||||
# all-time"); the spendable remainder is credit_balance − credits_drawn.
|
||||
# Kept separate so the member-facing all-time figure never changes meaning.
|
||||
if "credits_drawn" not in cols:
|
||||
conn.execute("ALTER TABLE members ADD COLUMN credits_drawn REAL NOT NULL DEFAULT 0")
|
||||
# Migration: org_slug — for ORGANIZATION-backed memberships. OC orgs never
|
||||
# expose an email to our integration, so the org's designated contact is
|
||||
# linked manually (POST /admin/org-link): org_slug holds the OC org slug
|
||||
@@ -1551,6 +1557,23 @@ def get_credit_balance(email: str) -> float:
|
||||
return 0.0
|
||||
|
||||
|
||||
def get_credits_drawn(email: str) -> float:
|
||||
"""Credits already consumed in CLOSED cycles (USD, default 0).
|
||||
|
||||
`credit_balance` stays the lifetime purchased total; this counter is what
|
||||
makes the spendable remainder (`credit_balance − credits_drawn`) shrink as
|
||||
packs are used, instead of every monthly reset restoring them (issue #12).
|
||||
"""
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT credits_drawn FROM members WHERE email = ?", (email,)
|
||||
).fetchone()
|
||||
conn.close()
|
||||
if row and row[0] is not None:
|
||||
return float(row[0])
|
||||
return 0.0
|
||||
|
||||
|
||||
def get_member_account_type(email: str) -> str:
|
||||
"""Return the row's account type: 'member' (default) or 'guest'."""
|
||||
conn = get_db()
|
||||
@@ -1693,16 +1716,22 @@ def add_credits(email: str, delta: float, reason: str, reference: str | None = N
|
||||
return float(row[0]) if row and row[0] is not None else 0.0
|
||||
|
||||
|
||||
def compute_max_budget(allowance: float, credit_balance: float, team_spend: float | None) -> dict:
|
||||
def compute_max_budget(allowance: float, credit_balance: float, team_spend: float | None,
|
||||
credits_drawn: float = 0.0) -> dict:
|
||||
"""Compute the effective LiteLLM max_budget from the two buckets.
|
||||
|
||||
Model: the member has a monthly ALLOWANCE (renews on each membership
|
||||
payment) plus a credit balance that adds spendable headroom ON TOP of the
|
||||
allowance. The total spendable cap is simply `allowance + credit_balance`
|
||||
allowance. The total spendable cap is `allowance + credits still available`
|
||||
— credits never shrink the allowance; they extend it.
|
||||
|
||||
`credit_balance` is the TOTAL purchased (the ledger's lifetime sum); the
|
||||
amount still available this cycle is `credit_balance - credits_used`.
|
||||
`credit_balance` is the TOTAL PURCHASED (the ledger's lifetime sum of
|
||||
grants); `credits_drawn` is the cumulative amount already consumed in
|
||||
CLOSED cycles. Credits used in the CURRENT cycle are NOT subtracted from
|
||||
the cap (that inversion bug made every credit add look inert); they are
|
||||
derived for display and only become a draw when the cycle closes
|
||||
(`close_credit_cycles`, issue #12). Without `credits_drawn`, a monthly
|
||||
spend reset hands back every credit already spent.
|
||||
|
||||
`team_spend` is the member's spend so far this cycle (from LiteLLM). It is
|
||||
used only to split the spend between allowance vs credits for display, NOT
|
||||
@@ -1711,13 +1740,14 @@ def compute_max_budget(allowance: float, credit_balance: float, team_spend: floa
|
||||
Returns {"max_budget", "allowance_used", "credits_used", "credits_remaining"}
|
||||
for dashboards.
|
||||
"""
|
||||
max_budget = allowance + credit_balance
|
||||
available = max(0.0, credit_balance - max(0.0, credits_drawn))
|
||||
max_budget = allowance + available
|
||||
if team_spend is None:
|
||||
return {
|
||||
"max_budget": max_budget,
|
||||
"allowance_used": 0.0,
|
||||
"credits_used": 0.0,
|
||||
"credits_remaining": credit_balance,
|
||||
"credits_remaining": available,
|
||||
}
|
||||
allowance_used = min(max(team_spend, 0.0), allowance)
|
||||
credits_used = max(0.0, team_spend - allowance)
|
||||
@@ -1725,7 +1755,7 @@ def compute_max_budget(allowance: float, credit_balance: float, team_spend: floa
|
||||
"max_budget": max_budget,
|
||||
"allowance_used": allowance_used,
|
||||
"credits_used": credits_used,
|
||||
"credits_remaining": max(0.0, credit_balance - credits_used),
|
||||
"credits_remaining": max(0.0, available - credits_used),
|
||||
}
|
||||
|
||||
|
||||
@@ -4230,23 +4260,216 @@ def next_reset_from_now() -> datetime:
|
||||
async def sync_team_budget_from_balance(email: str) -> float:
|
||||
"""Apply the member's effective budget to their LiteLLM team.
|
||||
|
||||
Effective budget = monthly allowance + remaining non-expiring credits
|
||||
(credits drawn only after the allowance is exhausted this cycle). Reads
|
||||
the member's live spend from LiteLLM to determine how much credit has
|
||||
already been consumed in the current cycle. Returns the applied budget.
|
||||
Effective budget = monthly allowance + credits still available
|
||||
(credits drawn only after the allowance is exhausted; credits consumed in
|
||||
CLOSED cycles are deducted by `close_credit_cycles`). Reads the member's
|
||||
live spend from LiteLLM to split this cycle's spend for display only.
|
||||
Returns the applied budget.
|
||||
"""
|
||||
balance = get_member_balance(email)
|
||||
credits = get_credit_balance(email)
|
||||
drawn = get_credits_drawn(email)
|
||||
team_id = await litellm_get_or_create_team(email, balance)
|
||||
|
||||
# Live spend this cycle (DB path preferred; LiteLLM computes the reset).
|
||||
team = get_team_budget_from_db(team_id) or {}
|
||||
team_spend = team.get("spend")
|
||||
eff = compute_max_budget(balance, credits, team_spend)
|
||||
eff = compute_max_budget(balance, credits, team_spend, drawn)
|
||||
await litellm_update_team_budget(team_id, eff["max_budget"])
|
||||
return eff["max_budget"]
|
||||
|
||||
|
||||
# --- Credit cycle close (issue #12) ---------------------------------------- #
|
||||
# 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 handed a member back ALL purchased credits, including the ones
|
||||
# they had already spent. Closing each completed cycle — recording what it drew
|
||||
# and bumping `credits_drawn` — is what makes a pack last.
|
||||
#
|
||||
# CREDIT_CLOSE_FROM is deliberately a POLICY date, not "everything since
|
||||
# launch": credits consumed under the old code were already regranted, and
|
||||
# clawing them back mid-cycle would cut members' caps for our bug. Cycles that
|
||||
# START before this date are skipped; every cycle from here on is charged.
|
||||
CREDIT_CLOSE_FROM = os.environ.get("CREDIT_CLOSE_FROM", "2026-11-28")
|
||||
# Wait out LiteLLM's own reset job before reading a closed window.
|
||||
CREDIT_CLOSE_GRACE_MIN = float(os.environ.get("CREDIT_CLOSE_GRACE_MIN", "15"))
|
||||
# How many completed cycles back to reconcile (downtime catch-up); idempotent.
|
||||
CREDIT_CLOSE_MAX_CYCLES = int(os.environ.get("CREDIT_CLOSE_MAX_CYCLES", "12"))
|
||||
|
||||
|
||||
def _prev_month(dt: datetime) -> datetime:
|
||||
"""Same day-of-month one month earlier (anchor days are clamped to 1..28)."""
|
||||
y, m = (dt.year, dt.month - 1) if dt.month > 1 else (dt.year - 1, 12)
|
||||
return dt.replace(year=y, month=m)
|
||||
|
||||
|
||||
def cycle_spend_from_ledger(team_id: str, start: datetime, end: datetime) -> float | None:
|
||||
"""Sum a team's spend over [start, end) straight from LiteLLM's SpendLogs.
|
||||
|
||||
Returns None when the ledger is unreachable (never 0.0): "no spend" and
|
||||
"could not look" must not print as the same thing, or a failed read would
|
||||
close a cycle at $0 and forgive the draw.
|
||||
"""
|
||||
if not litellm_db_ready():
|
||||
return None
|
||||
conn = _pg_connect()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
'SELECT COALESCE(SUM(spend), 0) FROM "LiteLLM_SpendLogs" '
|
||||
'WHERE team_id = %s AND "startTime" >= %s AND "startTime" < %s',
|
||||
(team_id, start, end),
|
||||
)
|
||||
return round(float(cur.fetchone()[0] or 0.0), 6)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def apply_cycle_draw(email: str, cycle_key: str, spend: float, allowance: float) -> float:
|
||||
"""Draw a closed cycle's credit overage from a member's pack (idempotent).
|
||||
|
||||
The overage is `max(0, spend − allowance)`, capped by the credits still
|
||||
available. Records a NEGATIVE ledger row and bumps `credits_drawn` in one
|
||||
transaction; the reference `cycle-close:<email>:<cycle>` is the dedupe key,
|
||||
so a repeat call for the same cycle applies nothing. Returns the amount
|
||||
drawn (0.0 when nothing was owed or the draw already happened).
|
||||
"""
|
||||
ref = f"cycle-close:{email}:{cycle_key}"
|
||||
if credit_reference_exists(ref):
|
||||
return 0.0
|
||||
purchased = get_credit_balance(email)
|
||||
available = max(0.0, purchased - get_credits_drawn(email))
|
||||
draw = round(min(max(0.0, spend - allowance), available), 6)
|
||||
if draw <= 0:
|
||||
return 0.0
|
||||
conn = get_db()
|
||||
try:
|
||||
conn.execute(
|
||||
"INSERT INTO credit_ledger (email, delta, reason, reference) "
|
||||
"VALUES (?, ?, ?, ?)",
|
||||
(email, -draw,
|
||||
f"credits used in cycle {cycle_key} "
|
||||
f"(${spend:.2f} spend, ${allowance:.2f} allowance)",
|
||||
ref),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE members SET credits_drawn = "
|
||||
"COALESCE(credits_drawn, 0) + ? WHERE email = ?",
|
||||
(draw, email),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return draw
|
||||
|
||||
|
||||
async def close_credit_cycles() -> dict:
|
||||
"""Close every completed allowance cycle: record the credits it drew.
|
||||
|
||||
For each ACTIVE member with purchased credits, walk completed cycles
|
||||
(newest first, at most CREDIT_CLOSE_MAX_CYCLES), sum the cycle's spend from
|
||||
SpendLogs, and draw `max(0, spend − allowance)` from their pack:
|
||||
* a NEGATIVE credit_ledger row (reference `cycle-close:<email>:<cycle>`),
|
||||
* `members.credits_drawn += drawn`,
|
||||
* the team cap re-synced to allowance + credits still available.
|
||||
Idempotent: the ledger reference is the dedupe key, so a re-run, a restart
|
||||
or an overlapping scheduler tick never charges a cycle twice.
|
||||
"""
|
||||
now = datetime.now(timezone.utc)
|
||||
try:
|
||||
floor = datetime.fromisoformat(CREDIT_CLOSE_FROM).replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
floor = datetime(2026, 11, 28, tzinfo=timezone.utc)
|
||||
logger.warning("close_credit_cycles: bad CREDIT_CLOSE_FROM %r; using %s",
|
||||
CREDIT_CLOSE_FROM, floor.date())
|
||||
|
||||
conn = get_db()
|
||||
rows = conn.execute(
|
||||
"SELECT email, anchor_day, balance, credit_balance, credits_drawn "
|
||||
"FROM members WHERE active = 1 AND account_type = 'member' "
|
||||
"AND COALESCE(credit_balance, 0) > 0"
|
||||
).fetchall()
|
||||
conn.close()
|
||||
|
||||
closed = 0
|
||||
drawn_total = 0.0
|
||||
skipped = 0
|
||||
errors: list[str] = []
|
||||
details: list[dict] = []
|
||||
|
||||
for email, anchor_day, balance, credit_balance, credits_drawn in rows:
|
||||
if not anchor_day:
|
||||
skipped += 1 # no cycle boundary can be derived
|
||||
continue
|
||||
allowance = float(balance) if balance is not None else MEMBER_BUDGET
|
||||
purchased = float(credit_balance or 0.0)
|
||||
anchor = _clamp_anchor_day(anchor_day)
|
||||
cur_start = cycle_start_for_anchor_day(anchor, now)
|
||||
if (now - cur_start).total_seconds() < CREDIT_CLOSE_GRACE_MIN * 60:
|
||||
skipped += 1 # LiteLLM may not have reset yet
|
||||
continue
|
||||
|
||||
try:
|
||||
team_id = await litellm_team_id_for_email(email)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"{email}: team lookup failed: {str(exc)[:120]}")
|
||||
continue
|
||||
if not team_id:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
cycle_end = cur_start
|
||||
for _ in range(max(1, CREDIT_CLOSE_MAX_CYCLES)):
|
||||
cycle_start = _prev_month(cycle_end)
|
||||
if cycle_start < floor:
|
||||
break
|
||||
cycle_key = cycle_start.date().isoformat()
|
||||
ref = f"cycle-close:{email}:{cycle_key}"
|
||||
|
||||
if credit_reference_exists(ref):
|
||||
cycle_end = cycle_start # already charged; walk further back
|
||||
continue
|
||||
|
||||
try:
|
||||
spend = cycle_spend_from_ledger(team_id, cycle_start, cycle_end)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"{email}/{cycle_key}: spend read failed: {str(exc)[:120]}")
|
||||
break
|
||||
if spend is None:
|
||||
errors.append(f"{email}/{cycle_key}: spend ledger unreachable")
|
||||
break
|
||||
|
||||
available = max(0.0, purchased - get_credits_drawn(email))
|
||||
overage = max(0.0, spend - allowance)
|
||||
draw = round(min(overage, available), 6)
|
||||
if draw > 0:
|
||||
drawn = apply_cycle_draw(email, cycle_key, spend, allowance)
|
||||
if drawn > 0:
|
||||
closed += 1
|
||||
drawn_total += drawn
|
||||
details.append({"email": email, "cycle": cycle_key,
|
||||
"spend": round(spend, 2), "drawn": round(drawn, 2)})
|
||||
try:
|
||||
applied = await sync_team_budget_from_balance(email)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors.append(f"{email}: cap sync failed: {str(exc)[:120]}")
|
||||
else:
|
||||
details[-1]["team_budget"] = applied
|
||||
cycle_end = cycle_start
|
||||
|
||||
if errors:
|
||||
logger.warning("close_credit_cycles: %d error(s): %s", len(errors), "; ".join(errors[:5]))
|
||||
return {
|
||||
"status": "ok" if not errors else "partial",
|
||||
"considered": len(rows),
|
||||
"closed": closed,
|
||||
"credits_drawn": round(drawn_total, 2),
|
||||
"skipped": skipped,
|
||||
"errors": errors,
|
||||
"details": details,
|
||||
}
|
||||
|
||||
|
||||
async def litellm_create_key(email: str, budget: float, team_id: str) -> str:
|
||||
"""Create a fresh LiteLLM virtual key under the member's team.
|
||||
|
||||
@@ -5708,6 +5931,7 @@ async def admin_credit_ledger(email: str, request: Request):
|
||||
return {
|
||||
"email": email,
|
||||
"credit_balance": get_credit_balance(email),
|
||||
"credits_drawn": get_credits_drawn(email),
|
||||
"ledger": [
|
||||
{"delta": r[0], "reason": r[1], "reference": r[2], "created_at": r[3]}
|
||||
for r in rows
|
||||
@@ -5715,6 +5939,19 @@ async def admin_credit_ledger(email: str, request: Request):
|
||||
}
|
||||
|
||||
|
||||
@app.post("/admin/credit-cycle-close")
|
||||
@limiter.limit("20/minute")
|
||||
async def admin_credit_cycle_close(request: Request):
|
||||
"""Close completed allowance cycles: draw the credits each one spent.
|
||||
|
||||
Idempotent — a re-run never charges a cycle twice (the ledger reference
|
||||
`cycle-close:<email>:<cycle>` is the dedupe key). The Cloudron scheduler
|
||||
invokes this every 10 minutes via credit_cycle_close.sh; issue #12.
|
||||
"""
|
||||
_verify_admin_token(request)
|
||||
return await close_credit_cycles()
|
||||
|
||||
|
||||
@app.get("/admin/held-credits")
|
||||
@limiter.limit("30/minute")
|
||||
async def admin_held_credits(request: Request):
|
||||
@@ -5971,7 +6208,7 @@ async def admin_overview(request: Request):
|
||||
rows = conn.execute(
|
||||
"SELECT email, active, balance, cloudron_user_id, org_slug, matrix_mxid, "
|
||||
"matrix_mxid_changed_at, account_type, oc_email, guest_expires_at, "
|
||||
"dues_amount, dues_frequency, dues_updated_at FROM members ORDER BY email"
|
||||
"dues_amount, dues_frequency, dues_updated_at, credits_drawn FROM members ORDER BY email"
|
||||
).fetchall()
|
||||
# Guest inviter/expiry from the guests ledger (latest row per recipient) —
|
||||
# the abuse-protection context the panel shows on the guest pill, plus the
|
||||
@@ -6064,7 +6301,7 @@ async def admin_overview(request: Request):
|
||||
operator_all_time = 0.0
|
||||
guest_spend = 0.0
|
||||
guest_all_time = 0.0
|
||||
for email, active, balance, user_id, org_slug, matrix_mxid, mxid_changed_at, acct_type, oc_email, guest_exp, dues_amount, dues_freq, dues_updated in rows:
|
||||
for email, active, balance, user_id, org_slug, matrix_mxid, mxid_changed_at, acct_type, oc_email, guest_exp, dues_amount, dues_freq, dues_updated, credits_drawn in rows:
|
||||
team = teams.get(f"member:{email}", {})
|
||||
spend = float(team.get("spend") or 0.0)
|
||||
member_all_time = float(all_time_spend.get(f"member:{email}", 0.0))
|
||||
@@ -6079,6 +6316,7 @@ async def admin_overview(request: Request):
|
||||
float(balance) if balance is not None else MEMBER_BUDGET,
|
||||
credits,
|
||||
spend,
|
||||
float(credits_drawn or 0.0),
|
||||
)
|
||||
mstate, mstate_reason = member_membership_state(email, bool(active))
|
||||
if ((acct_type or "member") == "guest" and active
|
||||
@@ -6113,7 +6351,7 @@ async def admin_overview(request: Request):
|
||||
"matrix_mxid_changed_at": mxid_changed_at or None,
|
||||
"balance": float(balance) if balance is not None else MEMBER_BUDGET,
|
||||
"credit_balance": credits,
|
||||
"credits_remaining": max(0.0, credits - eff["credits_used"]),
|
||||
"credits_remaining": eff["credits_remaining"],
|
||||
"allowance_used": eff["allowance_used"],
|
||||
"credits_used": eff["credits_used"],
|
||||
"spend": spend,
|
||||
@@ -7376,6 +7614,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
|
||||
|
||||
allowance = get_member_balance(email)
|
||||
credits = get_credit_balance(email)
|
||||
credits_drawn = get_credits_drawn(email)
|
||||
spend = 0.0
|
||||
reset_at = None
|
||||
|
||||
@@ -7432,7 +7671,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
|
||||
"balance": balance,
|
||||
"allowance": allowance,
|
||||
"credits": credits,
|
||||
"credits_remaining": max(0.0, credits - max(0.0, spend - allowance)),
|
||||
"credits_remaining": max(0.0, credits - credits_drawn - max(0.0, spend - allowance)),
|
||||
"spend": spend,
|
||||
"all_time_spend": round(all_time_spend, 2),
|
||||
"remaining": max(balance - spend, 0.0),
|
||||
@@ -7515,7 +7754,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
|
||||
"balance": balance,
|
||||
"allowance": allowance,
|
||||
"credits": credits,
|
||||
"credits_remaining": max(0.0, credits - max(0.0, spend - allowance)),
|
||||
"credits_remaining": max(0.0, credits - credits_drawn - max(0.0, spend - allowance)),
|
||||
"spend": spend,
|
||||
"all_time_spend": all_time_spend,
|
||||
"remaining": max(balance - spend, 0.0),
|
||||
@@ -10531,6 +10770,13 @@ async def admin_sweep(request: Request):
|
||||
except Exception as exc: # noqa: BLE001
|
||||
result["held_credits"] = {"error": str(exc)[:200]}
|
||||
|
||||
# Credit cycle close (issue #12): the frequent scheduler task is the primary
|
||||
# path; this is the catch-up, and the ledger reference makes it idempotent.
|
||||
try:
|
||||
result["credit_cycle_close"] = await close_credit_cycles()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
result["credit_cycle_close"] = {"error": str(exc)[:200]}
|
||||
|
||||
try:
|
||||
result["member_sources"] = await derive_member_sources()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
|
||||
Reference in new issue
Block a user