From fb6af42bbfa8ef0dfeaa8fd3c7e495eba358537f Mon Sep 17 00:00:00 2001 From: Inferencebot Date: Sat, 28 Nov 2026 02:41:48 +0000 Subject: [PATCH] allowance: keep reset dates on the join day after LiteLLM resets LiteLLM's reset job treats budget_duration '30d' as 'monthly on the 1st' and rewrites budget_reset_at to the next month's first day after every reset. The dues reconcile repins only members whose payment it verified; manual and org-backed rows are skipped, so their renewal drifts to the calendar month. pin_member_reset_dates() pins every active non-guest row from its anchor day, writing only when the stored date differs; it runs in /admin/sweep. Observed live: 27 members showed 2026-12-01 instead of their join-day date after the Nov 28 reset; 26 were anchor-day 28. --- app/main.py | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/app/main.py b/app/main.py index cfbb7fa..9948caf 100644 --- a/app/main.py +++ b/app/main.py @@ -10824,6 +10824,64 @@ async def fetch_org_join_days() -> dict[str, datetime]: 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. @@ -10989,6 +11047,15 @@ async def admin_sweep(request: Request): 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