Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
122824fd99 | ||
|
|
1191bcd521 | ||
|
|
aba53eabb5 | ||
|
|
fb6af42bbf | ||
|
|
6124d05ffd | ||
|
|
d10b36ed34 | ||
|
|
066a6fc2cf | ||
|
|
a70dd6ab4c | ||
|
|
cfb767dd4f | ||
|
|
18a4447aa2 | ||
|
|
dc53b27ad2 | ||
|
|
3e01f727c2 | ||
|
|
1070fc5dd0 | ||
|
|
0296f8d066 | ||
|
|
3d326ed428 | ||
|
|
97f0d6c3f1 | ||
|
|
237b695087 |
No files matched your search
@@ -35,5 +35,5 @@
|
||||
"manifestVersion": 2,
|
||||
"website": "https://inference.coop",
|
||||
"contactEmail": "info@inference.coop",
|
||||
"dockerImage": "registry.inference.coop/code/member-portal:20261127-0e53c33"
|
||||
"dockerImage": "registry.inference.coop/code/member-portal:20261128-1191bcd"
|
||||
}
|
||||
+335
-11
@@ -1708,6 +1708,15 @@ def add_credits(email: str, delta: float, reason: str, reference: str | None = N
|
||||
"INSERT INTO credit_ledger (email, delta, reason, reference) VALUES (?, ?, ?, ?)",
|
||||
(email, delta, reason, reference),
|
||||
)
|
||||
# Keep `credits_drawn <= credit_balance`. An adjustment that lowers the pack
|
||||
# below what was already drawn must not swallow FUTURE credits: a new pack
|
||||
# adds headroom, while consumption beyond the reduced pack is simply
|
||||
# unbacked. The ledger history itself is never rewritten.
|
||||
conn.execute(
|
||||
"UPDATE members SET credits_drawn = MIN(COALESCE(credits_drawn, 0), "
|
||||
"MAX(0, COALESCE(credit_balance, 0))) WHERE email = ?",
|
||||
(email,),
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT credit_balance FROM members WHERE email = ?", (email,)
|
||||
).fetchone()
|
||||
@@ -3729,6 +3738,42 @@ async def provision_guest_member(
|
||||
return user_id
|
||||
|
||||
|
||||
def record_guest_conversion_draw(email: str, spend: float) -> float:
|
||||
"""Record guest usage consumed before conversion; only the unspent part carries.
|
||||
|
||||
A guest has no monthly cycle, so nothing ever drew their spend against the
|
||||
$2 pack. Converting without this would hand back credits already used
|
||||
(guest-access.md promises only the UNSPENT credit carries over). The draw
|
||||
is capped by the row's current credit and deduped on a ledger reference.
|
||||
Returns the amount recorded (0.0 when nothing owed or already recorded).
|
||||
"""
|
||||
purchased = get_credit_balance(email)
|
||||
used = round(min(max(0.0, float(spend or 0.0)), purchased), 6)
|
||||
if used <= 0:
|
||||
return 0.0
|
||||
ref = f"guest-convert-draw:{email}"
|
||||
if credit_reference_exists(ref):
|
||||
return 0.0
|
||||
conn = get_db()
|
||||
try:
|
||||
conn.execute(
|
||||
"INSERT INTO credit_ledger (email, delta, reason, reference) "
|
||||
"VALUES (?, ?, ?, ?)",
|
||||
(email, -used,
|
||||
"guest credit used before conversion — only unspent credit carries over",
|
||||
ref),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE members SET credits_drawn = COALESCE(credits_drawn, 0) + ? "
|
||||
"WHERE email = ?",
|
||||
(used, email),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return used
|
||||
|
||||
|
||||
async def convert_guest_to_member(email: str, name: str, slug: str = "") -> str:
|
||||
"""Convert a GUEST account into a full member (the automatic transition).
|
||||
|
||||
@@ -3775,6 +3820,24 @@ async def convert_guest_to_member(email: str, name: str, slug: str = "") -> str:
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
# Guest usage has already consumed part of the $2; only the UNSPENT credit
|
||||
# may carry into membership (guest-access.md). record_guest_conversion_draw
|
||||
# writes the consumed part as a draw so it cannot be spent twice.
|
||||
try:
|
||||
guest_spend = None
|
||||
team_id = await litellm_team_id_for_email(email)
|
||||
if team_id:
|
||||
team = get_team_budget_from_db(team_id)
|
||||
if team:
|
||||
guest_spend = float(team.get("spend") or 0.0)
|
||||
if guest_spend is not None:
|
||||
used = record_guest_conversion_draw(email, guest_spend)
|
||||
if used > 0:
|
||||
logger.info("Guest convert: %.2f of guest credit already used for %s; "
|
||||
"the rest carries over", used, email)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("Guest convert: guest-draw accounting failed for %s: %s", email, e)
|
||||
|
||||
# 3. Lift the LiteLLM cap to allowance + credits and pin the reset to
|
||||
# their anchor day, exactly as the webhook does for any member.
|
||||
await sync_team_budget_from_balance(email)
|
||||
@@ -4229,6 +4292,29 @@ async def litellm_update_team_budget(team_id: str, budget: float) -> None:
|
||||
r.raise_for_status()
|
||||
|
||||
|
||||
async def litellm_clear_team_budget(team_id: str) -> None:
|
||||
"""Remove a team's spend cap (max_budget = NULL = unlimited).
|
||||
|
||||
Operator/infrastructure accounts are collective expenses, not members:
|
||||
applying the $15/credits cap to them would cut off the co-op's own tooling
|
||||
mid-task. Written straight to the team row because /team/update also
|
||||
silently drops budget_reset_at (an uncapped team needs no reset).
|
||||
"""
|
||||
def _write() -> None:
|
||||
conn = _pg_connect()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
'UPDATE "LiteLLM_TeamTable" SET max_budget = NULL WHERE team_id = %s',
|
||||
(team_id,),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
await asyncio.get_event_loop().run_in_executor(None, _write)
|
||||
|
||||
|
||||
async def litellm_pin_reset_date(team_id: str, reset_at: datetime) -> None:
|
||||
"""Pin a team's allowance reset to an exact moment (next OC payment date).
|
||||
|
||||
@@ -4257,20 +4343,25 @@ def next_reset_from_now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0) + timedelta(days=30)
|
||||
|
||||
|
||||
async def sync_team_budget_from_balance(email: str) -> float:
|
||||
async def sync_team_budget_from_balance(email: str) -> float | None:
|
||||
"""Apply the member's effective budget to their LiteLLM team.
|
||||
|
||||
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.
|
||||
Returns the applied budget; None for uncapped operator accounts, whose team
|
||||
cap is cleared rather than computed.
|
||||
"""
|
||||
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)
|
||||
|
||||
if (email or "").strip().lower() in UNCAPPED_EMAILS:
|
||||
await litellm_clear_team_budget(team_id)
|
||||
return None
|
||||
|
||||
# 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")
|
||||
@@ -4396,6 +4487,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:
|
||||
@@ -4449,13 +4541,31 @@ async def close_credit_cycles() -> dict:
|
||||
drawn_total += drawn
|
||||
details.append({"email": email, "cycle": cycle_key,
|
||||
"spend": round(spend, 2), "drawn": round(drawn, 2)})
|
||||
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:
|
||||
applied = await sync_team_budget_from_balance(email)
|
||||
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]}")
|
||||
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]))
|
||||
@@ -4465,6 +4575,7 @@ async def close_credit_cycles() -> dict:
|
||||
"closed": closed,
|
||||
"credits_drawn": round(drawn_total, 2),
|
||||
"skipped": skipped,
|
||||
"deferred": deferred,
|
||||
"errors": errors,
|
||||
"details": details,
|
||||
}
|
||||
@@ -5250,6 +5361,13 @@ async def _process_opencollective_webhook(request: Request, token: str):
|
||||
except Exception as e:
|
||||
logger.warning("Webhook: org re-provision failed for %s: %s",
|
||||
org_email, e)
|
||||
# Org rows are skipped by the allowance reconcile, so nothing
|
||||
# else would give this member an anchor day; infer it now
|
||||
# rather than waiting for the next sweep.
|
||||
try:
|
||||
await reconcile_org_anchors()
|
||||
except Exception as e:
|
||||
logger.warning("Webhook: org anchor pass failed: %s", e)
|
||||
else:
|
||||
logger.warning(
|
||||
"Webhook: Membership payment from ORGANIZATION %s (%s) — "
|
||||
@@ -6159,6 +6277,15 @@ OPERATOR_EMAILS = {
|
||||
if e.strip()
|
||||
}
|
||||
|
||||
# Accounts that hold NO LiteLLM spend cap: the co-op's own infrastructure, whose
|
||||
# usage is a collective expense and must not be cut off mid-task. Default: the
|
||||
# operator accounts; UNCAPPED_EMAILS adds (or replaces) via env.
|
||||
UNCAPPED_EMAILS = (
|
||||
{e.strip().lower() for e in os.environ["UNCAPPED_EMAILS"].split(",") if e.strip()}
|
||||
if os.environ.get("UNCAPPED_EMAILS")
|
||||
else set(OPERATOR_EMAILS)
|
||||
)
|
||||
|
||||
|
||||
def _membership_events_for_overview(conn: sqlite3.Connection) -> tuple[list[dict], dict[str, dict]]:
|
||||
"""Return (newest-first event log, latest deactivation per member email)."""
|
||||
@@ -6463,11 +6590,15 @@ async def admin_overview(request: Request):
|
||||
"operator_all_time_spend": round(operator_all_time, 2),
|
||||
# The co-op's spend, the ONE definition both apps show (see
|
||||
# coop_spend_totals). spend_all_time spans members AND the co-op's
|
||||
# own accounts; own_all_time_spend is the breakout.
|
||||
# own accounts; own_all_time_spend is the breakout, and
|
||||
# own_unattributed_spend names the part of it that joins to no team
|
||||
# alias (gateway overhead — historically the master-key keepalive
|
||||
# pings, kept as history rather than rewritten).
|
||||
**{
|
||||
k: v
|
||||
for k, v in _coop_spend_totals_safe().items()
|
||||
if k in ("spend_all_time", "own_all_time_spend")
|
||||
if k in ("spend_all_time", "own_all_time_spend",
|
||||
"own_unattributed_spend")
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -6723,6 +6854,11 @@ def coop_spend_totals() -> dict:
|
||||
as litellm_spend_by_day(), so the cards and the money chart agree.
|
||||
own = the co-op's own use: every team that is not a member team, plus rows
|
||||
with no team at all (nothing here is a member's usage).
|
||||
unattributed = the part of own that joins to NO team alias (empty alias).
|
||||
Named so it is auditable rather than a silent remainder: historically
|
||||
the audio keepalive pings on the master key, ~$3.21 over 16,894 rows
|
||||
before the key split on 2026-11-28. Never rewritten in LiteLLM's
|
||||
tables — that table is the system of record and is read-only here.
|
||||
"""
|
||||
if not litellm_db_ready():
|
||||
raise RuntimeError("LiteLLM DB credentials not configured")
|
||||
@@ -6739,7 +6875,7 @@ def coop_spend_totals() -> dict:
|
||||
rows = cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
member = own = 0.0
|
||||
member = own = unattributed = 0.0
|
||||
aliases = 0
|
||||
for alias, spend in rows:
|
||||
val = float(spend or 0.0)
|
||||
@@ -6748,10 +6884,13 @@ def coop_spend_totals() -> dict:
|
||||
member += val
|
||||
else:
|
||||
own += val
|
||||
if not str(alias or "").strip():
|
||||
unattributed += val
|
||||
return {
|
||||
"spend_all_time": round(member + own, 2),
|
||||
"member_all_time_spend": round(member, 2),
|
||||
"own_all_time_spend": round(own, 2),
|
||||
"own_unattributed_spend": round(unattributed, 2),
|
||||
"aliases": aliases,
|
||||
}
|
||||
|
||||
@@ -6885,6 +7024,7 @@ async def _compute_money_payload() -> dict:
|
||||
# The member-owned vs co-op's-own split of that same all-time spend,
|
||||
# from the one shared definition.
|
||||
"own_all_time_spend": (_coop_split := _coop_spend_totals_safe()).get("own_all_time_spend"),
|
||||
"own_unattributed_spend": _coop_split.get("own_unattributed_spend"),
|
||||
"member_all_time_spend": _coop_split.get("member_all_time_spend"),
|
||||
},
|
||||
"sources": {
|
||||
@@ -7617,13 +7757,20 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
|
||||
credits_drawn = get_credits_drawn(email)
|
||||
spend = 0.0
|
||||
reset_at = None
|
||||
# Default: the member's own allowance + credits still available. An
|
||||
# uncapped operator account has no team max_budget (NULL); keep this figure
|
||||
# for the dashboard's arithmetic and say plainly that there is no cap.
|
||||
balance = allowance + max(0.0, credits - credits_drawn)
|
||||
uncapped = False
|
||||
|
||||
# Fast path: direct Postgres reads.
|
||||
if litellm_db_ready():
|
||||
try:
|
||||
team = get_team_budget_from_db(team_id)
|
||||
if team:
|
||||
if team["max_budget"] is not None:
|
||||
if team["max_budget"] is None:
|
||||
uncapped = True
|
||||
else:
|
||||
balance = float(team["max_budget"])
|
||||
spend = float(team["spend"] or 0.0)
|
||||
reset_at = team["budget_reset_at"]
|
||||
@@ -7668,6 +7815,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
|
||||
return {
|
||||
"email": email,
|
||||
"guest": is_guest_account(email),
|
||||
"uncapped": uncapped,
|
||||
"balance": balance,
|
||||
"allowance": allowance,
|
||||
"credits": credits,
|
||||
@@ -7697,7 +7845,11 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
|
||||
r.raise_for_status()
|
||||
for t in r.json():
|
||||
if t.get("team_id") == team_id:
|
||||
balance = float(t.get("max_budget") or balance)
|
||||
mb = t.get("max_budget")
|
||||
if mb is None:
|
||||
uncapped = True
|
||||
else:
|
||||
balance = float(mb)
|
||||
spend = float(t.get("spend") or 0.0)
|
||||
reset_at = t.get("budget_reset_at")
|
||||
break
|
||||
@@ -7751,6 +7903,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
|
||||
return {
|
||||
"email": email,
|
||||
"guest": is_guest_account(email),
|
||||
"uncapped": uncapped,
|
||||
"balance": balance,
|
||||
"allowance": allowance,
|
||||
"credits": credits,
|
||||
@@ -10644,6 +10797,159 @@ async def derive_member_sources() -> dict:
|
||||
return {"checked": len(stale), "flipped": flipped}
|
||||
|
||||
|
||||
async def fetch_org_join_days() -> dict[str, datetime]:
|
||||
"""org slug -> the date that ORGANIZATION joined the collective on OC.
|
||||
|
||||
Organizations never expose an email, so fetch_member_index() drops them and
|
||||
the allowance reconcile skips org-backed rows. That is how an org member ends
|
||||
up with no `anchor_day` — and a credit cycle that can never close.
|
||||
"""
|
||||
if not OC_PERSONAL_TOKEN:
|
||||
raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch organization members")
|
||||
out: dict[str, datetime] = {}
|
||||
offset = 0
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
for _ in range(20): # same 100/page cap as the individual walk
|
||||
query = (
|
||||
'{ collective(slug: "%s") { members(limit: 100, offset: %d) { totalCount '
|
||||
"nodes { role createdAt tier { name } account { slug type } } } } }"
|
||||
% (OC_COLLECTIVE_SLUG, offset)
|
||||
)
|
||||
r = await _oc_graphql_post(
|
||||
client, {"query": query}, {"Personal-Token": OC_PERSONAL_TOKEN},
|
||||
)
|
||||
if r.status_code != 200:
|
||||
raise RuntimeError(f"OC organization fetch failed: HTTP {r.status_code}")
|
||||
members = ((r.json().get("data") or {}).get("collective") or {}).get("members") or {}
|
||||
total = members.get("totalCount") or 0
|
||||
nodes = members.get("nodes") or []
|
||||
for n in nodes:
|
||||
acct = n.get("account") or {}
|
||||
slug = (acct.get("slug") or "").strip().lower()
|
||||
if not slug or (acct.get("type") or "").upper() != "ORGANIZATION":
|
||||
continue
|
||||
joined = _parse_oc_dt(n.get("createdAt"))
|
||||
if joined and slug not in out:
|
||||
out[slug] = joined # the join date never moves; first sight wins
|
||||
offset += len(nodes)
|
||||
if not nodes or offset >= total:
|
||||
return out
|
||||
raise RuntimeError("OC organization pagination exceeded 20 pages")
|
||||
|
||||
|
||||
async def pin_member_reset_dates() -> dict:
|
||||
"""Keep every active member's allowance reset on their join day.
|
||||
|
||||
LiteLLM's reset job special-cases budget_duration "30d" as "monthly on the
|
||||
1st": after a reset it rewrites budget_reset_at to the first of the next
|
||||
month, so the NEXT renewal would land on the calendar month instead of the
|
||||
member's join day. The dues reconcile repins only members whose payment it
|
||||
verified; manual and org-backed rows are skipped, so the drift can stick.
|
||||
Pin every active non-guest row from its anchor day; write only when the
|
||||
stored date differs, so this is cheap and idempotent.
|
||||
"""
|
||||
conn = get_db()
|
||||
rows = conn.execute(
|
||||
"SELECT email, anchor_day FROM members WHERE active = 1 "
|
||||
"AND account_type != 'guest' AND anchor_day IS NOT NULL"
|
||||
).fetchall()
|
||||
conn.close()
|
||||
if not rows:
|
||||
return {"checked": 0, "pinned": 0, "changes": []}
|
||||
anchors = {email: _clamp_anchor_day(anchor) for email, anchor in rows}
|
||||
|
||||
try:
|
||||
pg = _pg_connect()
|
||||
try:
|
||||
with pg.cursor() as cur:
|
||||
cur.execute(
|
||||
'SELECT team_alias, team_id, budget_reset_at '
|
||||
'FROM "LiteLLM_TeamTable" WHERE team_alias LIKE %s',
|
||||
("member:%",),
|
||||
)
|
||||
teams = cur.fetchall()
|
||||
finally:
|
||||
pg.close()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("pin_member_reset_dates: team read failed: %s", exc)
|
||||
return {"checked": len(rows), "pinned": 0, "changes": [],
|
||||
"error": str(exc)[:200]}
|
||||
|
||||
changes = []
|
||||
for alias, team_id, reset_at in teams:
|
||||
email = (alias or "")[7:]
|
||||
anchor = anchors.get(email)
|
||||
if not anchor:
|
||||
continue
|
||||
expected = next_reset_for_anchor_day(anchor)
|
||||
if reset_at is not None and reset_at.date() == expected.date():
|
||||
continue
|
||||
try:
|
||||
await litellm_pin_reset_date(team_id, expected)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("pin_member_reset_dates: pin failed for %s: %s", email, exc)
|
||||
continue
|
||||
changes.append({"email": email, "anchor_day": anchor,
|
||||
"from": str(reset_at)[:10] if reset_at else None,
|
||||
"to": expected.date().isoformat()})
|
||||
return {"checked": len(rows), "pinned": len(changes), "changes": changes}
|
||||
|
||||
|
||||
async def reconcile_org_anchors() -> dict:
|
||||
"""Give every org-backed member an anchor day from the ORG's OC join date.
|
||||
|
||||
The allowance reconcile SKIPS rows with `org_slug` (dues are paid by an
|
||||
Organization, not by an individual order), so nothing ever set an anchor day
|
||||
for them and `close_credit_cycles` skipped them forever — their credit packs
|
||||
regenerated every month like everyone else's did before issue #12.
|
||||
|
||||
Anchor = day-of-month of the organization's OC membership `createdAt`,
|
||||
clamped to 1..28; the team reset is pinned to its next occurrence. Idempotent:
|
||||
only rows whose `anchor_day` is NULL are touched. An org with no membership
|
||||
record on OC is REPORTED, never guessed — a wrong anchor moves a member's
|
||||
billing boundary.
|
||||
"""
|
||||
conn = get_db()
|
||||
rows = conn.execute(
|
||||
"SELECT email, org_slug FROM members "
|
||||
"WHERE org_slug IS NOT NULL AND TRIM(org_slug) != '' AND anchor_day IS NULL"
|
||||
).fetchall()
|
||||
conn.close()
|
||||
if not rows:
|
||||
return {"checked": 0, "anchored": [], "unresolved": []}
|
||||
|
||||
try:
|
||||
joins = await fetch_org_join_days()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("reconcile_org_anchors: org fetch failed: %s", exc)
|
||||
return {"checked": len(rows), "anchored": [], "unresolved": [],
|
||||
"error": str(exc)[:200]}
|
||||
|
||||
anchored: list[dict] = []
|
||||
unresolved: list[dict] = []
|
||||
for email, org_slug in rows:
|
||||
joined = joins.get((org_slug or "").strip().lower())
|
||||
if not joined:
|
||||
unresolved.append({"email": email, "org_slug": org_slug})
|
||||
continue
|
||||
anchor = _clamp_anchor_day(joined.day)
|
||||
conn = get_db()
|
||||
try:
|
||||
conn.execute("UPDATE members SET anchor_day = ? WHERE email = ?", (anchor, email))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
try:
|
||||
team_id = await litellm_team_id_for_email(email)
|
||||
if team_id:
|
||||
await litellm_pin_reset_date(team_id, next_reset_for_anchor_day(anchor))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("reconcile_org_anchors: reset pin failed for %s: %s", email, exc)
|
||||
anchored.append({"email": email, "org_slug": org_slug, "anchor_day": anchor,
|
||||
"org_joined": joined.date().isoformat()})
|
||||
return {"checked": len(rows), "anchored": anchored, "unresolved": unresolved}
|
||||
|
||||
|
||||
FX_POLICY_EUR_USD = float(os.environ.get("FX_POLICY_EUR_USD", "1.0975") or 1.0975)
|
||||
FX_ALERT_PCT = float(os.environ.get("FX_ALERT_PCT", "2.0") or 2.0)
|
||||
|
||||
@@ -10745,6 +11051,24 @@ async def admin_sweep(request: Request):
|
||||
except Exception as exc: # noqa: BLE001
|
||||
result["allowances"] = {"error": str(exc)[:200]}
|
||||
|
||||
# Org-backed members get no anchor day from the allowance reconcile (it skips
|
||||
# them); infer it from the organization's OC membership date so their credit
|
||||
# cycles can close. Idempotent, and reports orgs with no OC record rather than
|
||||
# guessing a boundary. Wrapped so it can never break reconciliation.
|
||||
try:
|
||||
result["org_anchors"] = await reconcile_org_anchors()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
result["org_anchors"] = {"error": str(exc)[:200]}
|
||||
|
||||
# LiteLLM rewrites budget_reset_at to the 1st of the next month whenever a
|
||||
# "30d" team resets, so any row the dues reconcile skips (manual, org-backed)
|
||||
# would drift off its join day. Pin every active member's reset from its
|
||||
# anchor day; idempotent and writes only on a mismatch.
|
||||
try:
|
||||
result["reset_dates"] = await pin_member_reset_dates()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
result["reset_dates"] = {"error": str(exc)[:200]}
|
||||
|
||||
# Allowance-shortfall credits: OC's billing-day alignment truncates some paid
|
||||
# cycles. Rides the same sweep so a new member is compensated automatically;
|
||||
# credits are idempotent on the OC charge reference. Wrapped so it can never
|
||||
|
||||
@@ -77,6 +77,10 @@ try:
|
||||
f"member side is the member: teams ($10.005 + $5.005 -> 15.01, got {t['member_all_time_spend']})")
|
||||
check(t["own_all_time_spend"] == 2.59,
|
||||
f"own side is everything else: agents, sandboxes, unattributed (got {t['own_all_time_spend']})")
|
||||
check(t["own_unattributed_spend"] == 1.07,
|
||||
f"rows that join to no team alias are named, not left as a silent remainder (got {t['own_unattributed_spend']})")
|
||||
check(t["own_unattributed_spend"] <= t["own_all_time_spend"],
|
||||
"unattributed is a part of own, never added on top of the total")
|
||||
check(t["spend_all_time"] == round(t["member_all_time_spend"] + t["own_all_time_spend"], 2),
|
||||
"total == member + own, so no dollar is counted twice or dropped")
|
||||
check(t["spend_all_time"] == round(sum(r[1] for r in ROWS), 2),
|
||||
|
||||
@@ -32,8 +32,8 @@ for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
|
||||
break
|
||||
|
||||
from app.main import ( # noqa: E402
|
||||
_prev_month, apply_cycle_draw, compute_max_budget, cycle_start_for_anchor_day,
|
||||
get_credit_balance, get_credits_drawn, get_db,
|
||||
_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
|
||||
@@ -147,6 +147,57 @@ 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)
|
||||
|
||||
# --- 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)")
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regression tests: guest conversion carries only UNSPENT credit.
|
||||
|
||||
Runnable:
|
||||
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_guest_conversion_draw.py
|
||||
* from the repo root, on a host that has the app's dependencies
|
||||
|
||||
WHY THIS EXISTS
|
||||
A guest has no monthly cycle, so nothing ever drew their spend against the
|
||||
$2 pack. Converting a guest kept the full $2 credit_balance, handing back
|
||||
credits already used — while guest-access.md promises only the UNSPENT
|
||||
credit carries over. record_guest_conversion_draw() records the consumed
|
||||
part as a draw, deduped on a ledger reference.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="guestdraw-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
|
||||
compute_max_budget, get_credit_balance, get_credits_drawn, get_db,
|
||||
record_guest_conversion_draw,
|
||||
)
|
||||
|
||||
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 check_near(name, got, want):
|
||||
global failures
|
||||
ok = round(float(got), 6) == round(float(want), 6)
|
||||
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}")
|
||||
|
||||
|
||||
conn = get_db()
|
||||
conn.execute(
|
||||
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
|
||||
"VALUES ('g1@example.com', '', 1, 'guest', 0.0, 2.0)")
|
||||
conn.execute(
|
||||
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
|
||||
"VALUES ('g2@example.com', '', 1, 'guest', 0.0, 2.0)")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
used = record_guest_conversion_draw("g1@example.com", 1.9)
|
||||
check_near("consumed guest spend is drawn", used, 1.9)
|
||||
check_near("credits_drawn records it", get_credits_drawn("g1@example.com"), 1.9)
|
||||
check_near("credit_balance stays the purchased total", get_credit_balance("g1@example.com"), 2.0)
|
||||
check_near("only the unspent credit is available",
|
||||
compute_max_budget(15, 2, 0.0, get_credits_drawn("g1@example.com"))["credits_remaining"], 0.1)
|
||||
|
||||
check_near("a replay draws nothing", record_guest_conversion_draw("g1@example.com", 1.9), 0.0)
|
||||
check_near("credits_drawn unchanged by replay", get_credits_drawn("g1@example.com"), 1.9)
|
||||
|
||||
check_near("spend above the pack is capped", record_guest_conversion_draw("g2@example.com", 5.0), 2.0)
|
||||
check_near("pack fully drawn", get_credits_drawn("g2@example.com"), 2.0)
|
||||
check_near("no credit left", compute_max_budget(15, 2, 0.0, 2.0)["credits_remaining"], 0.0)
|
||||
|
||||
check_near("zero spend draws nothing", record_guest_conversion_draw("g1@example.com", 0.0), 0.0)
|
||||
|
||||
print()
|
||||
if failures:
|
||||
print(f"{failures} FAILURE(S)")
|
||||
sys.exit(1)
|
||||
print("all checks passed")
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regression tests for org-backed anchor days.
|
||||
|
||||
Runnable:
|
||||
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_org_anchors.py
|
||||
* from the repo root, on a host that has the app's dependencies
|
||||
|
||||
WHY THIS EXISTS
|
||||
The allowance reconcile SKIPS rows with `org_slug` (dues are paid by an OC
|
||||
Organization, not an individual order), so org-backed members never got an
|
||||
`anchor_day` — and close_credit_cycles skipped them forever, restoring their
|
||||
credit packs every month. The fix infers the anchor from the ORGANIZATION's
|
||||
OC membership createdAt. Covered:
|
||||
- anchor = org join day, clamped to 28
|
||||
- the team reset is pinned to the next occurrence
|
||||
- idempotent: a second pass touches nothing
|
||||
- an org with no OC membership record is reported, never guessed
|
||||
"""
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import datetime, timezone
|
||||
|
||||
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="organchor-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
|
||||
|
||||
import app.main as m # noqa: E402
|
||||
|
||||
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}")
|
||||
|
||||
|
||||
pins = []
|
||||
|
||||
|
||||
async def fake_org_joins():
|
||||
return {
|
||||
"cosmos": datetime(2026, 10, 15, 23, 52, tzinfo=timezone.utc),
|
||||
"late": datetime(2026, 1, 31, 12, 0, tzinfo=timezone.utc),
|
||||
}
|
||||
|
||||
|
||||
async def fake_team_id(email):
|
||||
return f"team:{email}"
|
||||
|
||||
|
||||
async def fake_pin(team_id, reset_at):
|
||||
pins.append((team_id, reset_at.isoformat()))
|
||||
|
||||
|
||||
m.fetch_org_join_days = fake_org_joins
|
||||
m.litellm_team_id_for_email = fake_team_id
|
||||
m.litellm_pin_reset_date = fake_pin
|
||||
|
||||
conn = m.get_db()
|
||||
m._ensure_allowance_tables(conn) # creates allowance_log and adds anchor_day
|
||||
conn.execute(
|
||||
"INSERT INTO members (email, key_token, active, account_type, org_slug) "
|
||||
"VALUES ('tech@cosmos.coop', '', 1, 'member', 'cosmos')")
|
||||
conn.execute(
|
||||
"INSERT INTO members (email, key_token, active, account_type, org_slug) "
|
||||
"VALUES ('ops@late.org', '', 1, 'member', 'late')")
|
||||
conn.execute(
|
||||
"INSERT INTO members (email, key_token, active, account_type, org_slug) "
|
||||
"VALUES ('x@unknown.org', '', 1, 'member', 'unknown-org')")
|
||||
conn.execute(
|
||||
"INSERT INTO members (email, key_token, active, account_type, org_slug, anchor_day) "
|
||||
"VALUES ('already@set.org', '', 1, 'member', 'cosmos', 7)")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
first = asyncio.run(m.reconcile_org_anchors())
|
||||
anchors = {r["email"]: r["anchor_day"] for r in first["anchored"]}
|
||||
check("org join day 15 -> anchor 15", anchors.get("tech@cosmos.coop"), 15)
|
||||
check("org join day 31 -> clamped to 28", anchors.get("ops@late.org"), 28)
|
||||
check("an org with no OC record is reported, not guessed",
|
||||
[u["email"] for u in first["unresolved"]], ["x@unknown.org"])
|
||||
check("an already-anchored row is untouched", "already@set.org" not in anchors, True)
|
||||
|
||||
reset = dict((t, r) for t, r in pins)
|
||||
check("reset pinned to the next occurrence of the anchor day (Dec 15)",
|
||||
reset.get("team:tech@cosmos.coop", "")[:10], "2026-12-15")
|
||||
|
||||
second = asyncio.run(m.reconcile_org_anchors())
|
||||
check("second pass leaves only the unresolved org to report", second["checked"], 1)
|
||||
check("second pass writes no anchors", second["anchored"], [])
|
||||
check("the unresolved org is reported again, not silently dropped",
|
||||
[u["email"] for u in second["unresolved"]], ["x@unknown.org"])
|
||||
|
||||
row = m.get_db().execute(
|
||||
"SELECT anchor_day FROM members WHERE email = 'tech@cosmos.coop'").fetchone()
|
||||
check("anchor persisted", row[0], 15)
|
||||
|
||||
print()
|
||||
if failures:
|
||||
print(f"{failures} FAILURE(S)")
|
||||
sys.exit(1)
|
||||
print("all checks passed")
|
||||
Reference in new issue
Block a user