ci/woodpecker/push/woodpecker Pipeline was canceled
close_credit_cycles drew max(0, cycle_spend - allowance) capped by the pack's current balance, so a pack bought mid-cycle was charged for spend that predated it. Split the cycle at the first grant: allowance is consumed first, then credits cover only the spend after they became available. apply_cycle_draw takes the eligible figure; the ledger reason records it. Correction rows for the six over-drawn clawback cycles are separate.
209 lines
8.8 KiB
Python
209 lines
8.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Regression tests for credit cycle close (issue #12).
|
|
|
|
Runnable:
|
|
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_credit_cycle_close.py
|
|
* from the repo root, on a host that has the app's dependencies
|
|
|
|
WHY THIS EXISTS
|
|
LiteLLM zeroes a team's `spend` at budget_reset_at and leaves max_budget
|
|
alone, and nothing ever reduced `credit_balance`. Result: a member who bought
|
|
a $50 pack and spent it got the $50 back at the next monthly reset — the
|
|
allowance returned to $65 instead of $15, forever. Covered here:
|
|
- the cap is allowance + credits STILL AVAILABLE (drawn in closed cycles)
|
|
- spend inside the CURRENT cycle never shrinks the cap (the inversion bug)
|
|
- closing a cycle draws the overage once, and a replay draws nothing
|
|
- a draw is capped by the credits actually available
|
|
- the issue's worked example end-to-end
|
|
"""
|
|
import os
|
|
import sqlite3
|
|
import sys
|
|
import tempfile
|
|
from datetime import datetime, timezone
|
|
|
|
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="creditclose-test-"), "members.db")
|
|
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
|
|
|
|
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
|
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
|
|
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
|
|
sys.path.insert(0, _cand)
|
|
break
|
|
|
|
from app.main import ( # noqa: E402
|
|
_prev_month, add_credits, apply_cycle_draw, compute_max_budget,
|
|
cycle_start_for_anchor_day, get_credit_balance, get_credits_drawn, get_db,
|
|
)
|
|
|
|
failures = 0
|
|
|
|
|
|
def check(name, got, want):
|
|
global failures
|
|
ok = got == want
|
|
if not ok:
|
|
failures += 1
|
|
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
|
|
if not ok:
|
|
print(f" got {got!r}\n want {want!r}")
|
|
|
|
|
|
def close(a, b):
|
|
return round(float(a), 6) == round(float(b), 6)
|
|
|
|
|
|
def check_near(name, got, want):
|
|
global failures
|
|
ok = close(got, want)
|
|
if not ok:
|
|
failures += 1
|
|
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
|
|
if not ok:
|
|
print(f" got {got!r}\n want {want!r}")
|
|
|
|
|
|
# --- cycle boundary math ---------------------------------------------------
|
|
check("_prev_month steps back across a year boundary",
|
|
_prev_month(datetime(2026, 1, 1, tzinfo=timezone.utc)).isoformat(),
|
|
datetime(2025, 12, 1, tzinfo=timezone.utc).isoformat())
|
|
check("cycle_start_for_anchor_day is the last occurrence at/before now",
|
|
cycle_start_for_anchor_day(28, datetime(2026, 11, 27, 12, tzinfo=timezone.utc)).isoformat(),
|
|
datetime(2026, 10, 28, tzinfo=timezone.utc).isoformat())
|
|
|
|
# --- cap arithmetic --------------------------------------------------------
|
|
# allowance $15 + $50 pack, nothing drawn, fresh cycle
|
|
eff = compute_max_budget(15, 50, 0.0, 0.0)
|
|
check_near("fresh cycle cap = allowance + pack", eff["max_budget"], 65.0)
|
|
check_near("fresh cycle credits remaining = pack", eff["credits_remaining"], 50.0)
|
|
|
|
# mid-cycle spend NEVER shrinks the cap (the inversion bug)
|
|
mid = compute_max_budget(15, 50, 40.0, 0.0)
|
|
check_near("mid-cycle cap unchanged as credits burn", mid["max_budget"], 65.0)
|
|
check_near("mid-cycle credits used derived from spend", mid["credits_used"], 25.0)
|
|
check_near("mid-cycle credits remaining = pack - used", mid["credits_remaining"], 25.0)
|
|
|
|
# after the cycle closes with $50 drawn
|
|
after = compute_max_budget(15, 50, 0.0, 50.0)
|
|
check_near("after close cap = allowance only (pack spent)", after["max_budget"], 15.0)
|
|
check_near("after close credits remaining = 0", after["credits_remaining"], 0.0)
|
|
|
|
# every dollar of purchased credit raises the cap by a dollar
|
|
check_near("credit add raises the cap 1:1",
|
|
compute_max_budget(15, 70, 0.0, 50.0)["max_budget"], 35.0)
|
|
check_near("drawn beyond purchased never goes negative",
|
|
compute_max_budget(15, 50, 0.0, 80.0)["max_budget"], 15.0)
|
|
|
|
# --- a real (temporary) DB: apply_cycle_draw ---------------------------------
|
|
conn = get_db() # runs schema + migrations
|
|
conn.execute(
|
|
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
|
|
"VALUES ('pack@example.com', '', 1, 'member', 15.0, 50.0)"
|
|
)
|
|
conn.commit()
|
|
conn.close()
|
|
|
|
drawn = apply_cycle_draw("pack@example.com", "2026-10-28", spend=65.0, allowance=15.0)
|
|
check_near("cycle draws the overage ($65 spend - $15 allowance)", drawn, 50.0)
|
|
check_near("credits_drawn recorded", get_credits_drawn("pack@example.com"), 50.0)
|
|
check_near("credit_balance still says total purchased", get_credit_balance("pack@example.com"), 50.0)
|
|
|
|
# replay of the same cycle draws nothing
|
|
again = apply_cycle_draw("pack@example.com", "2026-10-28", spend=65.0, allowance=15.0)
|
|
check_near("replaying a closed cycle draws nothing", again, 0.0)
|
|
check_near("credits_drawn unchanged by the replay", get_credits_drawn("pack@example.com"), 50.0)
|
|
rows = sqlite3.connect(_TEST_DB).execute(
|
|
"SELECT COUNT(*) FROM credit_ledger WHERE reference = ?",
|
|
("cycle-close:pack@example.com:2026-10-28",)).fetchone()[0]
|
|
check("exactly ONE ledger row for the cycle", rows, 1)
|
|
|
|
# the issue's reproduction: after the reset the cap is the allowance, not $65
|
|
after = compute_max_budget(15, get_credit_balance("pack@example.com"), 0.0,
|
|
get_credits_drawn("pack@example.com"))
|
|
check_near("issue #12: next cycle cap is $15, not $65", after["max_budget"], 15.0)
|
|
|
|
# a draw cannot exceed what is left
|
|
conn = get_db()
|
|
conn.execute(
|
|
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
|
|
"VALUES ('small@example.com', '', 1, 'member', 15.0, 10.0)"
|
|
)
|
|
conn.commit()
|
|
conn.close()
|
|
apply_cycle_draw("small@example.com", "2026-10-01", spend=100.0, allowance=15.0)
|
|
check_near("draw capped by credits available", get_credits_drawn("small@example.com"), 10.0)
|
|
check_near("cap after capped draw = allowance",
|
|
compute_max_budget(15, 10, 0.0, 10.0)["max_budget"], 15.0)
|
|
|
|
# spend under the allowance owes nothing
|
|
conn = get_db()
|
|
conn.execute(
|
|
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
|
|
"VALUES ('under@example.com', '', 1, 'member', 15.0, 20.0)"
|
|
)
|
|
conn.commit()
|
|
conn.close()
|
|
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.execute(
|
|
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
|
|
"VALUES ('defer@example.com', 20.0, 'pack (test)', 'test-pack', '2026-10-01 00:00:00')")
|
|
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)
|
|
|
|
# --- lowering a pack below what was drawn must not swallow NEW credits ----
|
|
add_credits("small@example.com", -10.0, reason="admin correction (test)")
|
|
check_near("drawn follows the pack down when it is reduced", get_credits_drawn("small@example.com"), 0.0)
|
|
check_near("balance reduced to zero", get_credit_balance("small@example.com"), 0.0)
|
|
add_credits("small@example.com", 5.0, reason="new pack (test)")
|
|
check_near("a new pack is fully available after the correction",
|
|
compute_max_budget(15, get_credit_balance("small@example.com"), 0.0,
|
|
get_credits_drawn("small@example.com"))["credits_remaining"], 5.0)
|
|
|
|
print()
|
|
if failures:
|
|
print(f"{failures} FAILURE(S)")
|
|
sys.exit(1)
|
|
print("all checks passed")
|