diff --git a/app/main.py b/app/main.py index c784b61..b4e3335 100644 --- a/app/main.py +++ b/app/main.py @@ -4424,6 +4424,7 @@ async def close_credit_cycles() -> dict: skipped = 0 errors: list[str] = [] details: list[dict] = [] + deferred: list[dict] = [] for email, anchor_day, balance, credit_balance, credits_drawn in rows: if not anchor_day: @@ -4477,14 +4478,32 @@ async def close_credit_cycles() -> dict: 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 + # Re-sync the cap only when it will not put the member under their + # ALREADY-RECORDED spend. A clawback applied mid-cycle would otherwise + # leave max_budget < spend and LiteLLM refuses every call until the + # next reset — weeks for some anchors. The draw is still recorded now; + # the cap falls at the first tick after their spend resets. + if (email or "").strip().lower() in UNCAPPED_EMAILS: + continue + try: + team = get_team_budget_from_db(team_id) or {} + spend_now = team.get("spend") + cur_cap = team.get("max_budget") + eff = compute_max_budget(allowance, purchased, spend_now, + get_credits_drawn(email)) + if cur_cap is not None and abs(cur_cap - eff["max_budget"]) <= 1e-9: + continue + if spend_now is None or spend_now <= eff["max_budget"] + 1e-9: + await litellm_update_team_budget(team_id, eff["max_budget"]) + details.append({"email": email, "cap_applied": eff["max_budget"]}) + else: + deferred.append({"email": email, "cap": eff["max_budget"], + "spend_now": round(float(spend_now), 2)}) + except Exception as exc: # noqa: BLE001 + errors.append(f"{email}: cap sync failed: {str(exc)[:120]}") + if errors: logger.warning("close_credit_cycles: %d error(s): %s", len(errors), "; ".join(errors[:5])) return { @@ -4493,6 +4512,7 @@ async def close_credit_cycles() -> dict: "closed": closed, "credits_drawn": round(drawn_total, 2), "skipped": skipped, + "deferred": deferred, "errors": errors, "details": details, } diff --git a/tests/test_credit_cycle_close.py b/tests/test_credit_cycle_close.py index 4940448..e89574f 100644 --- a/tests/test_credit_cycle_close.py +++ b/tests/test_credit_cycle_close.py @@ -147,6 +147,48 @@ check_near("no overage, no draw", apply_cycle_draw("under@example.com", "2026-10-01", spend=9.0, allowance=15.0), 0.0) check_near("balance untouched", get_credits_drawn("under@example.com"), 0.0) +# --- a clawback that would land under recorded spend is DEFERRED ------------ +import asyncio # noqa: E402 +import app.main as m # noqa: E402 + +now = m.datetime.now(m.timezone.utc) +anchor = now.day if now.day <= 28 else 28 +conn = get_db() +m._ensure_allowance_tables(conn) # adds anchor_day +conn.execute( + "INSERT INTO members (email, key_token, active, account_type, balance, credit_balance, anchor_day) " + "VALUES ('defer@example.com', '', 1, 'member', 15.0, 20.0, ?)", (anchor,)) +conn.commit() +conn.close() + +state = {"spend": 40.0, "cap": 35.0} +applied = [] + +async def fake_team(email): + return "team:defer" if email == "defer@example.com" else None + +async def fake_update(team_id, budget): + applied.append(budget) + state["cap"] = budget + +m.litellm_team_id_for_email = fake_team +m.litellm_update_team_budget = fake_update +m.get_team_budget_from_db = lambda tid: {"spend": state["spend"], "max_budget": state["cap"], + "budget_reset_at": None} +m.cycle_spend_from_ledger = lambda tid, a, b: 40.0 +m.CREDIT_CLOSE_FROM = "2026-01-01" + +r1 = asyncio.run(m.close_credit_cycles()) +check_near("draw recorded even while the cap is deferred", get_credits_drawn("defer@example.com"), 20.0) +check("cap NOT lowered under recorded spend", + any(d["email"] == "defer@example.com" for d in r1["deferred"]), True) +check("no cap push while spend > new cap", applied, []) + +state["spend"] = 0.0 # what LiteLLM does at the member's reset +r2 = asyncio.run(m.close_credit_cycles()) +check("cap applied once spend resets", applied, [15.0]) +check("no second draw on the same cycle", r2["credits_drawn"], 0.0) + print() if failures: print(f"{failures} FAILURE(S)")