Author SHA1 Message Date
inference-bot bbd8115058 manifest: pin to 20261202-ca336a3
ci/woodpecker/push/woodpecker Pipeline failed
2026-12-02 15:33:05 +00:00
inference-bot ca336a3115 credits: only charge spend incurred while credits were available (#12 follow-up)
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.
2026-12-02 15:32:34 +00:00
inference-admin 122824fd99 manifest: pin to 20261128-1191bcd
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-28 14:04:22 +00:00
inference-admin 1191bcd521 spend: name the unattributed slice of own spend for posterity
own_all_time_spend already includes SpendLogs rows that join to no team alias,
but the remainder was unnamed, so every reader had to notice it by subtraction.
coop_spend_totals() now reports own_unattributed_spend and both payloads
(/admin/overview totals and admin/money-series totals) carry it: the gateway's
own overhead, historically the master-key audio keepalive pings (~$3.21 over
16,894 rows before the 2026-11-28 key split).

History is labelled, never rewritten: LiteLLM_SpendLogs is the system of record
and the portal keeps read-only access, so no team_id is backfilled.
2026-11-28 14:03:47 +00:00
inference-bot aba53eabb5 manifest: pin to 20261127-fb6af42
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-28 02:42:36 +00:00
inference-bot fb6af42bbf allowance: keep reset dates on the join day after LiteLLM resets
ci/woodpecker/push/woodpecker Pipeline was canceled
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.
2026-11-28 02:41:48 +00:00
inference-bot 6124d05ffd manifest: pin to 20261127-d10b36e
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 22:05:49 +00:00
inference-bot d10b36ed34 credits: an adjustment below the drawn amount must not eat the next pack
ci/woodpecker/push/woodpecker Pipeline was canceled
credits_drawn could exceed credit_balance after an admin set/correction (or a
negative adjustment), so a later pack was only partly usable: available =
max(0, purchased - drawn) swallowed the difference. Cap credits_drawn at the
row's balance on every add_credits movement; ledger history is unchanged.
Tests cover reduction-then-repurchase.
2026-11-27 22:05:19 +00:00
inference-bot 066a6fc2cf manifest: pin to 20261127-a70dd6a
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 22:04:22 +00:00
inference-bot a70dd6ab4c guests: only UNSPENT credit carries into membership
ci/woodpecker/push/woodpecker Pipeline was canceled
A guest has no monthly cycle, so nothing ever drew their spend against the $2
pack. Conversion kept the full credit_balance, handing back credits already
used — guest-access.md promises only the unspent credit carries over.

record_guest_conversion_draw() writes the consumed part as a negative ledger
row (reference guest-convert-draw:<email>) and bumps credits_drawn, capped by
the row's credit and idempotent on replay. Tests cover draw, replay, cap, and
the resulting remaining figure.
2026-11-27 22:03:43 +00:00
inference-bot cfb767dd4f manifest: pin to 20261127-18a4447
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 21:59:21 +00:00
inference-bot 18a4447aa2 usage: handle an uncapped team in /broker/usage
ci/woodpecker/push/woodpecker Pipeline was canceled
An operator account has team max_budget NULL (no cap). broker_get_usage only
assigned balance when max_budget was not None, so the DB path left 'balance'
unbound and the HTTP fallback read the same name before assignment — a 500 for
exactly the accounts the uncapped policy created. Initialise balance from the
member's allowance + credits still available, mark the response uncapped when
the team row has no cap, and keep the dashboard arithmetic defined.
2026-11-27 21:58:34 +00:00
inference-bot dc53b27ad2 manifest: pin to 20261127-3e01f72
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 21:35:52 +00:00
inference-bot 3e01f727c2 credits: defer a clawback cap that would fall under recorded spend
ci/woodpecker/push/woodpecker Pipeline was canceled
Applying the draw mid-cycle used to push max_budget below the member's
already-recorded spend, so LiteLLM refused every call until their next reset
(weeks for some anchors). The draw is still recorded immediately — books are
correct — but the cap is only pushed once the member's spend has room for it,
which happens right after LiteLLM's reset. The tick retries every 10 minutes,
so the cap lands at the first tick after the boundary; deferred members are
reported in close_credit_cycles().deferred.

tests/test_credit_cycle_close.py covers draw-recorded/cap-deferred and the
cap landing after spend resets, with no second draw.
2026-11-27 21:35:02 +00:00
inference-bot 1070fc5dd0 manifest: pin to 20261127-0296f8d
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 21:23:58 +00:00
inference-bot 0296f8d066 credits: infer anchor days for org-backed members
ci/woodpecker/push/woodpecker Pipeline was canceled
The allowance reconcile skips rows with org_slug (dues are paid by an OC
Organization, not an individual order), so org members never got an anchor_day
and close_credit_cycles skipped them forever — their packs regenerated monthly,
the same defect as #12.

- fetch_org_join_days(): paginated OC members walk, ORGANIZATION accounts only,
  slug -> membership createdAt.
- reconcile_org_anchors(): for every active org-backed row with anchor_day NULL,
  set anchor = org join day clamped to 1..28 and pin the team reset to its next
  occurrence. Only NULL rows are touched (idempotent); an org with no OC record is
  reported, never guessed, and keeps being reported until resolved.
- Runs in /admin/sweep and immediately in the org-member webhook path.

tests/test_org_anchors.py: anchor math incl. clamp, reset pin, idempotence,
unresolved reporting.
2026-11-27 21:23:24 +00:00
inference-bot 3d326ed428 manifest: pin to 20261127-97f0d6c
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 21:20:30 +00:00
inference-bot 97f0d6c3f1 credits: uncapped operator accounts; no cap for info@
ci/woodpecker/push/woodpecker Pipeline was canceled
Operator/infrastructure accounts are a collective expense, not members: applying
the $15 + credits cap to them cuts the co-op's own tooling off mid-task.

- UNCAPPED_EMAILS (defaults to OPERATOR_EMAILS) is cleared in
  sync_team_budget_from_balance via litellm_clear_team_budget: max_budget = NULL
  on the team row (unlimited), written directly because /team/update drops
  budget_reset_at.
- sync_team_budget_from_balance returns None for an uncapped account; admin
  responses report team_budget: null rather than a computed figure.
2026-11-27 21:19:52 +00:00
inference-bot 237b695087 manifest: pin to 20261127-fe89890
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 20:42:13 +00:00
inference-bot fe898905b4 credits: close each cycle so a pack cannot be spent twice (#12)
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.
2026-11-27 20:29:12 +00:00
inference-bot bcdc0416e2 manifest: pin to 20261127-0e53c33
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 18:04:29 +00:00
inference-bot 0e53c330e1 tests: FX verdict at the 1.0975 fallback pin
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-27 18:04:00 +00:00
inference-bot 9ab8156da2 fx: baseline the spot check at the written fallback pin, not a stale 1.16
ci/woodpecker/push/woodpecker Pipeline failed
The sweep compared the ECB rate to a hardcoded 1.16 and emailed info@ with
"-5.39%" plus advice to "re-convert" — obsolete since fx_sync.py converts at
boot. The steady breach also froze the alert marker, so a later, real move
could never mail.

- Default baseline 1.0975 (the gateway's FX_FALLBACK_USD pin, ECB 2026-11-26);
  runtime value set via FX_POLICY_EUR_USD.
- Email now says live billing is unaffected by conversion and points at the
  stale artifacts (config fallback, ops pricing tables, fx_state.json).
2026-11-27 17:58:01 +00:00
inference-bot a3bfc56b77 manifest: pin to 20261124-c174cba
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-24 19:50:16 +00:00
inference-bot c174cba5ce Merge pull request 'membership events: durable lapse/reactivation log' (#11) from feat/membership-events into main
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-24 19:49:10 +00:00
10 changed files with 1281 additions and 37 deletions

No files matched your search

+5 -1
View File
@@ -25,11 +25,15 @@
"metrics_snapshot": {
"schedule": "15 3 * * *",
"command": "/app/code/metrics_snapshot.py"
},
"credit_cycle_close": {
"schedule": "*/10 * * * *",
"command": "/app/code/credit_cycle_close.sh"
}
}
},
"manifestVersion": 2,
"website": "https://inference.coop",
"contactEmail": "info@inference.coop",
"dockerImage": "registry.inference.coop/code/member-portal:20261123-419b1f4"
"dockerImage": "registry.inference.coop/code/member-portal:20261202-ca336a3"
}
+2 -1
View File
@@ -10,8 +10,9 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY app/ ./app/
COPY sweep.sh /app/code/sweep.sh
COPY service_sync.sh /app/code/service_sync.sh
COPY credit_cycle_close.sh /app/code/credit_cycle_close.sh
COPY metrics_snapshot.py /app/code/metrics_snapshot.py
RUN chmod +x /app/code/sweep.sh /app/code/service_sync.sh /app/code/metrics_snapshot.py
RUN chmod +x /app/code/sweep.sh /app/code/service_sync.sh /app/code/credit_cycle_close.sh /app/code/metrics_snapshot.py
# Run as root (the base image default). Cloudron's sandboxing (read-only
# rootfs, AppArmor, dropped capabilities) still applies to root inside the
+698 -31
View File
@@ -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()
@@ -1685,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()
@@ -1693,16 +1725,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 +1749,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 +1764,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),
}
@@ -3699,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).
@@ -3745,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)
@@ -4199,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).
@@ -4227,26 +4343,336 @@ 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 + 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; 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")
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 credit_available_at_start(email: str, when: datetime) -> float:
"""Credit balance the member already had when a cycle began.
The ledger is the full history (purchases positive, draws negative), so its
running sum is the spendable balance at any timestamp. A pack bought while
the previous cycle was open is available at the next boundary.
"""
conn = get_db()
try:
row = conn.execute(
"SELECT COALESCE(SUM(delta), 0) FROM credit_ledger "
"WHERE email = ? AND created_at < ?",
(email, when.strftime("%Y-%m-%d %H:%M:%S")),
).fetchone()
finally:
conn.close()
return float(row[0] or 0.0)
def first_credit_available(email: str, start: datetime, end: datetime) -> datetime | None:
"""First moment inside [start, end) when the member's credit balance is > 0.
Returns `start` when credits were already available at the boundary, None
when the cycle never had credits, and the purchase timestamp when a pack
arrived mid-cycle.
"""
running = credit_available_at_start(email, start)
if running > 0:
return start
conn = get_db()
try:
rows = conn.execute(
"SELECT created_at, delta FROM credit_ledger "
"WHERE email = ? AND created_at >= ? AND created_at < ? "
"ORDER BY created_at, id",
(email, start.strftime("%Y-%m-%d %H:%M:%S"),
end.strftime("%Y-%m-%d %H:%M:%S")),
).fetchall()
finally:
conn.close()
for created_at, delta in rows:
running += float(delta or 0.0)
if running > 0:
try:
return datetime.fromisoformat(created_at).replace(tzinfo=timezone.utc)
except ValueError:
return None
return None
def credit_eligible_overage(email: str, team_id: str, cycle_start: datetime,
cycle_end: datetime, allowance: float,
total_spend: float | None = None) -> float | None:
"""The part of a cycle's overage that credits could actually have covered.
Spend before the pack existed is not credit spend. With credits available
from the boundary, the whole overage is eligible. Otherwise split the cycle
at the first grant: allowance is consumed first, then credits cover the
spend after that point. Returns None when SpendLogs cannot be read.
"""
if total_spend is None:
total_spend = cycle_spend_from_ledger(team_id, cycle_start, cycle_end)
if total_spend is None:
return None
available_from_start = credit_available_at_start(email, cycle_start)
if available_from_start > 0:
return round(max(0.0, total_spend - allowance), 6)
grant_at = first_credit_available(email, cycle_start, cycle_end)
if grant_at is None:
return 0.0
if grant_at <= cycle_start:
return round(max(0.0, total_spend - allowance), 6)
spend_before = cycle_spend_from_ledger(team_id, cycle_start, grant_at)
if spend_before is None:
return None
spend_after = max(0.0, total_spend - spend_before)
allowance_left = max(0.0, allowance - spend_before)
return round(max(0.0, spend_after - allowance_left), 6)
def apply_cycle_draw(email: str, cycle_key: str, spend: float, allowance: float,
eligible: float | None = None) -> float:
"""Draw a closed cycle's credit overage from a member's pack (idempotent).
The overage is `max(0, spend − allowance)` — or the caller's
`credit-eligible` figure when credits arrived mid-cycle — 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))
overage = max(0.0, spend - allowance) if eligible is None else eligible
draw = round(min(max(0.0, overage), 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, "
f"${overage:.2f} credit-eligible)",
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] = []
deferred: 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))
eligible = credit_eligible_overage(email, team_id, cycle_start,
cycle_end, allowance, spend)
if eligible is None:
errors.append(f"{email}/{cycle_key}: eligibility read failed")
break
draw = round(min(eligible, available), 6)
if draw > 0:
drawn = apply_cycle_draw(email, cycle_key, spend, allowance,
eligible=eligible)
if drawn > 0:
closed += 1
drawn_total += drawn
details.append({"email": email, "cycle": cycle_key,
"spend": round(spend, 2),
"eligible": round(eligible, 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:
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 {
"status": "ok" if not errors else "partial",
"considered": len(rows),
"closed": closed,
"credits_drawn": round(drawn_total, 2),
"skipped": skipped,
"deferred": deferred,
"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.
@@ -5027,6 +5453,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) — "
@@ -5708,6 +6141,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 +6149,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):
@@ -5922,6 +6369,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)."""
@@ -5971,7 +6427,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 +6520,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 +6535,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 +6570,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,
@@ -6225,11 +6682,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")
},
},
}
@@ -6485,6 +6946,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")
@@ -6501,7 +6967,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)
@@ -6510,10 +6976,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,
}
@@ -6647,6 +7116,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": {
@@ -7376,15 +7846,23 @@ 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
# 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"]
@@ -7429,10 +7907,11 @@ 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,
"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),
@@ -7458,7 +7937,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
@@ -7512,10 +7995,11 @@ 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,
"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),
@@ -10405,7 +10889,160 @@ async def derive_member_sources() -> dict:
return {"checked": len(stale), "flipped": flipped}
FX_POLICY_EUR_USD = float(os.environ.get("FX_POLICY_EUR_USD", "1.16") or 1.16)
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)
@@ -10418,7 +11055,7 @@ def _fx_verdict(rate: float, policy: float = FX_POLICY_EUR_USD,
async def fx_spot_check(send: bool = True) -> dict:
"""Daily spot check of EUR/USD against the pricing FX (1.16). Alerts, never reprices.
"""Daily spot check of the ECB EUR/USD rate against the written fallback pin.
Source: ECB daily reference rate. An alert is sent to info@ only when the drift
first crosses FX_ALERT_PCT; staying over the line does not mail every day. When
@@ -10452,12 +11089,17 @@ async def fx_spot_check(send: bool = True) -> dict:
direction = "above" if verdict["drift_pct"] > 0 else "below"
verdict["notified"] = bool(send_email(
ADMIN_INVITER_EMAIL,
f"EUR/USD {verdict['drift_pct']:+.1f}% {direction} the pricing FX",
f"The ECB rate is {verdict['rate']} USD per EUR; our pricing policy is "
f"{verdict['policy']}. Drift: {verdict['drift_pct']:+.1f}%.\n\n"
"No prices were changed automatically. Decide whether to re-convert "
"GreenPT/Regolo EUR list prices at the new rate (scripts/check_eur_fx.py "
"in code/litellm guards the conversion).\n"))
f"EUR/USD {verdict['drift_pct']:+.1f}% {direction} the fallback pin",
f"The ECB rate is {verdict['rate']} USD per EUR; the written fallback "
f"pin is {verdict['policy']}. Drift: {verdict['drift_pct']:+.1f}%.\n\n"
"Live billing is not affected: the gateway re-converts GreenPT/Regolo "
"EUR list prices at the ECB daily rate on every boot (fx_sync.py). "
"Drift means the COMMITTED figures are stale — regenerate the USD "
"fallback in code/litellm/config.yaml (scripts/check_eur_fx.py guards "
"it), refresh the USD columns in ops-docs/provider-pricing/, keep "
"FX_FALLBACK_USD and this portal's FX_POLICY_EUR_USD in step, and "
"confirm /app/data/fx_state.json in the gateway carries a fresh feed "
"date.\n"))
conn = get_db()
try:
@@ -10501,6 +11143,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
@@ -10526,6 +11186,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
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# Credit cycle close — run by the Cloudron scheduler addon every 10 minutes.
#
# Calls the portal's own /admin/credit-cycle-close endpoint (localhost), which
# walks each active member's completed allowance cycles and draws the credits
# those cycles spent (issue #12: a monthly reset used to restore every credit
# pack, because nothing ever recorded what usage consumed).
#
# Idempotent: each closed cycle is keyed by the ledger reference
# `cycle-close:<email>:<cycle>`, so an overlapping tick or a restart never
# charges a cycle twice. Cheap: one SELECT when nobody has credits.
#
# The ADMIN_TOKEN env var is shared with the main app (scheduler runs in the
# same launch environment), so we use it to authenticate. Admin auth is a
# header, never a URL token.
set -e
if [ -z "$ADMIN_TOKEN" ]; then
echo "credit-cycle-close: ADMIN_TOKEN is not set; aborting" >&2
exit 1
fi
python3 - "$ADMIN_TOKEN" <<'PY'
import sys, urllib.request, urllib.error
token = sys.argv[1]
url = "http://127.0.0.1:8000/admin/credit-cycle-close"
req = urllib.request.Request(url, method="POST", data=b"", headers={
"Content-Type": "application/json",
"X-Admin-Token": token,
})
try:
with urllib.request.urlopen(req, timeout=300) as resp:
print("credit-cycle-close:", resp.read().decode())
except urllib.error.HTTPError as e:
print(f"credit-cycle-close: HTTP {e.code}: {e.read().decode()}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"credit-cycle-close: request failed: {e}", file=sys.stderr)
sys.exit(1)
PY
+4
View File
@@ -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),
+208
View File
@@ -0,0 +1,208 @@
#!/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")
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env python3
"""Regression tests: a cycle draw may only charge spend credits could cover.
A pack bought mid-cycle must not be charged for spend incurred before it
existed. Reproduces the consensus_polo100 case: $27.81 spent before the $10
pack arrived, then $0.62 after it; the eligible draw is $0.62, not $10.
"""
import os
import sys
import tempfile
from datetime import datetime, timezone
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="creditelig-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}")
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 = m.get_db()
m._ensure_allowance_tables(conn) # adds anchor_day
for email, purchased, anchor in [
("midcycle@example.com", 10.0, 15),
("carried@example.com", 50.0, 15),
("none@example.com", 0.0, 15),
("partial@example.com", 20.0, 15)]:
conn.execute(
"INSERT INTO members (email, key_token, active, account_type, balance, "
"credit_balance, credits_drawn, anchor_day) VALUES (?, '', 1, 'member', 15.0, ?, 0, ?)",
(email, purchased, anchor))
# Pack bought inside the cycle, after the allowance had already been overspent.
conn.execute(
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
"VALUES ('midcycle@example.com', 10.0, 'pack', 'pack-mid', '2026-11-12 13:05:26')")
# Pack held from before the cycle.
conn.execute(
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
"VALUES ('carried@example.com', 50.0, 'pack', 'pack-carry', '2026-09-20 10:00:00')")
# Pack arrives when only part of the allowance has been used.
conn.execute(
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
"VALUES ('partial@example.com', 20.0, 'pack', 'pack-part', '2026-10-20 12:00:00')")
conn.commit()
conn.close()
CS = datetime(2026, 10, 15, tzinfo=timezone.utc)
CE = datetime(2026, 11, 15, tzinfo=timezone.utc)
# Spend windows for the mid-cycle member: 27.81376 before the pack, 0.624698 after.
def fake_spend(team_id, start, end):
if team_id == "t-mid":
if end.day == 12 and end.month == 11:
return 27.81376
if start == CS and end == CE:
return 28.438458
if team_id == "t-partial" and start == CS and end == datetime(2026, 10, 20, 12, tzinfo=timezone.utc):
return 5.0
return None
m.cycle_spend_from_ledger = fake_spend
# mid-cycle pack: only spend after the pack is eligible
got = m.credit_eligible_overage("midcycle@example.com", "t-mid", CS, CE, 15.0, 28.438458)
check_near("mid-cycle pack is not charged for earlier spend", got, 0.624698)
# pack carried in: whole overage is eligible
got = m.credit_eligible_overage("carried@example.com", "t-carry", CS, CE, 15.0, 28.438458)
check_near("credits at cycle start cover the whole overage", got, 13.438458)
# no credits: nothing eligible
got = m.credit_eligible_overage("none@example.com", "t-none", CS, CE, 15.0, 28.438458)
check_near("no credits means no eligible draw", got, 0.0)
# partial allowance left: overage above what remains is eligible
got = m.credit_eligible_overage("partial@example.com", "t-partial", CS, CE, 15.0, 20.0)
check_near("allowance is consumed before credits", got, 5.0)
# the eligible figure drives the draw, and the replay still draws nothing
drawn = m.apply_cycle_draw("midcycle@example.com", "2026-10-15", 28.438458, 15.0, eligible=0.624698)
check_near("draw uses the credit-eligible overage", drawn, 0.624698)
check_near("credits_drawn records only that amount", m.get_credits_drawn("midcycle@example.com"), 0.624698)
check_near("purchased total is unchanged", m.get_credit_balance("midcycle@example.com"), 10.0)
check_near("replay draws nothing",
m.apply_cycle_draw("midcycle@example.com", "2026-10-15", 28.438458, 15.0, eligible=0.624698), 0.0)
print()
if failures:
print(f"{failures} FAILURE(S)")
sys.exit(1)
print("all checks passed")
+4 -4
View File
@@ -1,8 +1,8 @@
import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m
v=m._fx_verdict(1.16); assert v["alert"] is False, v
v=m._fx_verdict(1.20); assert v["alert"] is True and v["drift_pct"] > 0, v
v=m._fx_verdict(1.10); assert v["alert"] is True and v["drift_pct"] < 0, v
v=m._fx_verdict(1.157); assert v["alert"] is False, v # 0.26% drift
v=m._fx_verdict(1.0975); assert v["alert"] is False, v
v=m._fx_verdict(1.13); assert v["alert"] is True and v["drift_pct"] > 0, v
v=m._fx_verdict(1.07); assert v["alert"] is True and v["drift_pct"] < 0, v
v=m._fx_verdict(1.0995); assert v["alert"] is False, v # 0.18% drift
print("FX VERDICT OK: thresholds and signs behave")
+86
View File
@@ -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")
+114
View File
@@ -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")