Author SHA1 Message Date
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
inference-bot b3de608170 membership events: durable lapse/reactivation log
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-24 19:41:00 +00:00
inference-admin f1ba9d7313 manifest: pin to 20261123-419b1f4
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-23 14:27:14 +00:00
inference-admin 419b1f4322 matrix sync: skip a member's remaining rooms after a transport error
ci/woodpecker/push/woodpecker Pipeline was canceled
An unreachable remote homeserver hangs every invite POST to that member until
the client timeout (8 rooms x 30s), which outlived the 5-minute service-sync
tick and starved every member queued behind it. Raise a member-scoped
_TransportError instead of returning False, skip that member's remaining rooms
for this pass, and report transport_skipped in the result. Invites stay
idempotent, so the next pass retries.

Test: a timed-out member is attempted once, not once per room.
2026-11-23 14:26:03 +00:00
inference-bot d190aa7762 manifest: pin to 20261123-db0c09e
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-23 03:36:33 +00:00
inference-bot db0c09e85d orders: docstring matches the paginated read (no fixed window) 2026-11-23 03:36:33 +00:00
inference-bot 3ccaf0ec85 manifest: pin to 20261123-c60dc2c
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-23 03:34:55 +00:00
inference-bot c60dc2c482 orders: read every page, never a fixed 200-order window
The collective crossed 200 orders on 2026-11-23 (203). fetch_member_orders()
asked for orders(limit: 200) in one request, so the orders beyond the window —
the OLDEST ones, where long-standing members' recurring contributions live —
were absent from the sweep's read. Three paying members (ntnsndr,
elizabeth-barry1, guest-0f6d98ac) therefore read as "no recurring (monthly)
contribution on Open Collective" and were sent a payment reminder at 03:02 UTC
for contributions that were live and charged on 2 Nov.

fetch_oc_monthly_order_charges() had the same fixed window, hiding the oldest
orders' charge ladders from the shortfall credit pass.

Both now page by offset until OC's totalCount is covered, and a read that falls
short of totalCount RAISES instead of returning a short list: a short list is
the exact shape that reads as "nobody is paying".
2026-11-23 03:34:49 +00:00
9 changed files with 1181 additions and 89 deletions

No files matched your search

+5 -1
View File
@@ -25,11 +25,15 @@
"metrics_snapshot": { "metrics_snapshot": {
"schedule": "15 3 * * *", "schedule": "15 3 * * *",
"command": "/app/code/metrics_snapshot.py" "command": "/app/code/metrics_snapshot.py"
},
"credit_cycle_close": {
"schedule": "*/10 * * * *",
"command": "/app/code/credit_cycle_close.sh"
} }
} }
}, },
"manifestVersion": 2, "manifestVersion": 2,
"website": "https://inference.coop", "website": "https://inference.coop",
"contactEmail": "info@inference.coop", "contactEmail": "info@inference.coop",
"dockerImage": "registry.inference.coop/code/member-portal:20261121-b761136" "dockerImage": "registry.inference.coop/code/member-portal:20261127-0e53c33"
} }
+2 -1
View File
@@ -10,8 +10,9 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY app/ ./app/ COPY app/ ./app/
COPY sweep.sh /app/code/sweep.sh COPY sweep.sh /app/code/sweep.sh
COPY service_sync.sh /app/code/service_sync.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 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 # Run as root (the base image default). Cloudron's sandboxing (read-only
# rootfs, AppArmor, dropped capabilities) still applies to root inside the # rootfs, AppArmor, dropped capabilities) still applies to root inside the
+624 -81
View File
@@ -1035,6 +1035,116 @@ def _verify_admin_token(request: Request) -> None:
raise HTTPException(403, "Forbidden") raise HTTPException(403, "Forbidden")
def _backfill_membership_events(conn: sqlite3.Connection) -> None:
"""Give every already-inactive member a deactivation row (once).
The portal kept inactive members only as members.active = 0, so the two
members who lapsed before this table existed had no event record. This
backfill derives the best available reason from the allowance/reminder
trail and inserts ONE deactivated row per member. occurred_at stays NULL:
the exact lapse date is not recorded anywhere, and inventing one would make
the log lie. The portal_state marker keeps it to one pass.
"""
try:
done = conn.execute(
"SELECT value FROM portal_state WHERE key = 'membership_events_backfill_v1'"
).fetchone()
if done:
return
tables = {r[0] for r in conn.execute(
"SELECT name FROM sqlite_master WHERE type = 'table'"
).fetchall()}
rows = conn.execute(
"SELECT email, COALESCE(account_type, 'member'), welcome_sent_at "
"FROM members WHERE active = 0"
).fetchall()
for email, acct_type, welcome_sent_at in rows:
# Guests have their own ledger and are not members; never backfill
# a guest into the member log.
if (acct_type or "member") == "guest":
continue
if conn.execute(
"SELECT 1 FROM membership_events "
"WHERE email = ? AND event = 'deactivated' LIMIT 1",
(email,),
).fetchone():
continue
latest = reminded = None
if "allowance_log" in tables:
latest = conn.execute(
"SELECT decision, evidence, decided_at FROM allowance_log "
"WHERE email = ? ORDER BY decided_at DESC, id DESC LIMIT 1",
(email,),
).fetchone()
if "payment_reminders" in tables:
reminded = conn.execute(
"SELECT sent_at FROM payment_reminders WHERE email = ? "
"ORDER BY sent_at DESC LIMIT 1",
(email,),
).fetchone()
if latest:
decision, evidence, decided_at = latest
reason = (
f"Membership lapsed; last allowance decision '{decision}' "
f"({str(decided_at or '')[:10] or 'undated'}): {evidence or 'no evidence recorded'}"
)
detail = "Backfilled from allowance_log; exact deactivation date unknown."
elif reminded:
reason = (
"Membership lapsed after a payment reminder sent "
f"{str(reminded[0] or '')[:10]}; no later renewal recorded."
)
detail = "Backfilled from payment_reminders; exact deactivation date unknown."
else:
reason = (
"Membership lapsed; no allowance or reminder trail was recorded"
+ (f" (provisioned {str(welcome_sent_at)[:10]})" if welcome_sent_at else "")
+ "."
)
detail = "Backfilled from the inactive members row; cause and date unknown."
conn.execute(
"INSERT INTO membership_events "
"(email, account_type, event, reason, source, occurred_at, detail) "
"VALUES (?, ?, 'deactivated', ?, 'backfill', NULL, ?)",
(email, acct_type or "member", reason, detail),
)
conn.execute(
"INSERT OR REPLACE INTO portal_state (key, value) "
"VALUES ('membership_events_backfill_v1', datetime('now'))"
)
except sqlite3.OperationalError as e:
# A fresh/partial database may not yet have the trail tables. Leave the
# marker unset so a later pass retries once they exist.
logger.warning("membership events backfill skipped: %s", e)
def record_membership_event(
conn: sqlite3.Connection,
email: str,
event: str,
reason: str = "",
source: str = "",
account_type: str = "member",
occurred_at: str | None = None,
detail: str = "",
) -> None:
"""Append one membership transition to the durable log."""
conn.execute(
"INSERT INTO membership_events "
"(email, account_type, event, reason, source, occurred_at, detail) "
"VALUES (?, ?, ?, ?, ?, ?, ?)",
(
email,
account_type or "member",
event,
reason or "",
source or "",
occurred_at or datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"),
detail or "",
),
)
def get_db() -> sqlite3.Connection: def get_db() -> sqlite3.Connection:
conn = sqlite3.connect(DB_PATH) conn = sqlite3.connect(DB_PATH)
conn.execute( conn.execute(
@@ -1046,6 +1156,29 @@ def get_db() -> sqlite3.Connection:
"active INTEGER DEFAULT 1" "active INTEGER DEFAULT 1"
")" ")"
) )
# Membership events — the durable answer to "who was a member, and what
# happened to them". The members row keeps only the CURRENT flag (active
# 1/0); without this table a lapse left no record of WHEN or WHY, so a
# former member was indistinguishable from one who never paid. Every
# deactivation/reactivation transition writes one row; backfilled rows
# carry occurred_at NULL because the exact historical date is unknown.
conn.execute(
"CREATE TABLE IF NOT EXISTS membership_events ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"email TEXT NOT NULL, "
"account_type TEXT NOT NULL DEFAULT 'member', "
"event TEXT NOT NULL, "
"reason TEXT NOT NULL DEFAULT '', "
"source TEXT NOT NULL DEFAULT '', "
"occurred_at TEXT, "
"recorded_at TEXT NOT NULL DEFAULT (datetime('now')), "
"detail TEXT NOT NULL DEFAULT ''"
")"
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_membership_events_email "
"ON membership_events(email, id)"
)
# Daily metrics snapshot, written by /app/code/metrics_snapshot.py from the # Daily metrics snapshot, written by /app/code/metrics_snapshot.py from the
# scheduler and read by the admin panel + dashboard. Cumulative columns # scheduler and read by the admin panel + dashboard. Cumulative columns
# (members_*, newsletter_subs, matrix_space_members) are counts AS OF that # (members_*, newsletter_subs, matrix_space_members) are counts AS OF that
@@ -1145,6 +1278,12 @@ def get_db() -> sqlite3.Connection:
# exhausted within a cycle. # exhausted within a cycle.
if "credit_balance" not in cols: if "credit_balance" not in cols:
conn.execute("ALTER TABLE members ADD COLUMN credit_balance REAL NOT NULL DEFAULT 0") 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 # Migration: org_slug — for ORGANIZATION-backed memberships. OC orgs never
# expose an email to our integration, so the org's designated contact is # 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 # linked manually (POST /admin/org-link): org_slug holds the OC org slug
@@ -1368,6 +1507,10 @@ def get_db() -> sqlite3.Connection:
# CRITICAL log if PORTAL_KEK is unset — see the inline key-encryption module. # CRITICAL log if PORTAL_KEK is unset — see the inline key-encryption module.
migrate_plaintext_keys(conn) migrate_plaintext_keys(conn)
# One-time backfill for members who lapsed before the events table existed.
# Runs after portal_state exists; the marker inside keeps it to one pass.
_backfill_membership_events(conn)
# Commit the DML above — ALTER TABLE auto-commits, but the UPDATEs open an # Commit the DML above — ALTER TABLE auto-commits, but the UPDATEs open an
# implicit transaction that would otherwise roll back when get_db() closes. # implicit transaction that would otherwise roll back when get_db() closes.
conn.commit() conn.commit()
@@ -1414,6 +1557,23 @@ def get_credit_balance(email: str) -> float:
return 0.0 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: def get_member_account_type(email: str) -> str:
"""Return the row's account type: 'member' (default) or 'guest'.""" """Return the row's account type: 'member' (default) or 'guest'."""
conn = get_db() conn = get_db()
@@ -1556,16 +1716,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 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. """Compute the effective LiteLLM max_budget from the two buckets.
Model: the member has a monthly ALLOWANCE (renews on each membership Model: the member has a monthly ALLOWANCE (renews on each membership
payment) plus a credit balance that adds spendable headroom ON TOP of the 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. — credits never shrink the allowance; they extend it.
`credit_balance` is the TOTAL purchased (the ledger's lifetime sum); the `credit_balance` is the TOTAL PURCHASED (the ledger's lifetime sum of
amount still available this cycle is `credit_balance - credits_used`. 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 `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 used only to split the spend between allowance vs credits for display, NOT
@@ -1574,13 +1740,14 @@ def compute_max_budget(allowance: float, credit_balance: float, team_spend: floa
Returns {"max_budget", "allowance_used", "credits_used", "credits_remaining"} Returns {"max_budget", "allowance_used", "credits_used", "credits_remaining"}
for dashboards. 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: if team_spend is None:
return { return {
"max_budget": max_budget, "max_budget": max_budget,
"allowance_used": 0.0, "allowance_used": 0.0,
"credits_used": 0.0, "credits_used": 0.0,
"credits_remaining": credit_balance, "credits_remaining": available,
} }
allowance_used = min(max(team_spend, 0.0), allowance) allowance_used = min(max(team_spend, 0.0), allowance)
credits_used = max(0.0, team_spend - allowance) credits_used = max(0.0, team_spend - allowance)
@@ -1588,7 +1755,7 @@ def compute_max_budget(allowance: float, credit_balance: float, team_spend: floa
"max_budget": max_budget, "max_budget": max_budget,
"allowance_used": allowance_used, "allowance_used": allowance_used,
"credits_used": credits_used, "credits_used": credits_used,
"credits_remaining": max(0.0, credit_balance - credits_used), "credits_remaining": max(0.0, available - credits_used),
} }
@@ -2285,6 +2452,13 @@ async def sync_matrix_space() -> dict:
super().__init__(f"retry_after_ms={wait_ms}") super().__init__(f"retry_after_ms={wait_ms}")
self.wait_ms = wait_ms self.wait_ms = wait_ms
class _TransportError(Exception):
"""The invite POST itself never got an answer (timeout/reset)."""
def __init__(self, kind):
super().__init__(kind)
self.kind = kind
async def invite(mxid: str, room: str) -> bool: async def invite(mxid: str, room: str) -> bool:
try: try:
r = await client.post( r = await client.post(
@@ -2293,14 +2467,16 @@ async def sync_matrix_space() -> dict:
) )
except httpx.HTTPError as exc: except httpx.HTTPError as exc:
# A transport failure (read timeout, connection reset) belongs to # A transport failure (read timeout, connection reset) belongs to
# ONE member/room, not to the sync. Synapse federates some invites # ONE member, not to the sync. Synapse federates some invites and
# and can exceed the read timeout. Swallow it, log it, let the next # can exceed the read timeout. Raise a member-scoped error so the
# pass retry: raising here aborted the whole pass and silently # caller can skip this member's REMAINING rooms: a remote homeserver
# skipped every member after this one, which is how a new member # that cannot be reached hangs every room until the client timeout
# sat uninvited for a day. # (8 x 30s), which outlived the scheduled tick and starved every
# member queued behind it. Invites are idempotent; the next pass
# retries.
logger.warning("Matrix invite %s -> %s transport error: %s", logger.warning("Matrix invite %s -> %s transport error: %s",
mxid, room, type(exc).__name__) mxid, room, type(exc).__name__)
return False raise _TransportError(type(exc).__name__) from exc
if r.status_code == 200: if r.status_code == 200:
return True return True
if r.status_code == 429: if r.status_code == 429:
@@ -2319,6 +2495,7 @@ async def sync_matrix_space() -> dict:
rooms = member_invite_rooms() rooms = member_invite_rooms()
invited_count = 0 invited_count = 0
rate_limited = False rate_limited = False
transport_skipped = 0
async with httpx.AsyncClient(timeout=30) as client: async with httpx.AsyncClient(timeout=30) as client:
# Snapshot EVERY room's membership once, up front: who is joined and who # Snapshot EVERY room's membership once, up front: who is joined and who
@@ -2379,6 +2556,18 @@ async def sync_matrix_space() -> dict:
sent_any = True sent_any = True
if sent_any: if sent_any:
invited_count += 1 invited_count += 1
except _TransportError as exc:
# One member's federation timeout must not cost the pass their
# remaining rooms. An unreachable remote homeserver hangs EVERY
# room's invite until the client timeout, so retrying room by
# room burns the whole tick and the members queued behind this
# one never get invited. Skip this member and move on; invites
# are idempotent and the next pass retries.
transport_skipped += 1
logger.info(
"Matrix sync: %s transport error (%s); skipping their remaining "
"rooms this pass", mxid, exc.kind)
continue
except _RateLimited as exc: except _RateLimited as exc:
rate_limited = True rate_limited = True
logger.info( logger.info(
@@ -2466,7 +2655,8 @@ async def sync_matrix_space() -> dict:
local_mxid, room, type(exc).__name__) local_mxid, room, type(exc).__name__)
if retired: if retired:
logger.info("Matrix sync: retired %s local account(s)/invite(s)", retired) logger.info("Matrix sync: retired %s local account(s)/invite(s)", retired)
return {"invited": invited_count, "rate_limited": rate_limited} return {"invited": invited_count, "rate_limited": rate_limited,
"transport_skipped": transport_skipped}
async def matrix_member_mxids(client: httpx.AsyncClient): async def matrix_member_mxids(client: httpx.AsyncClient):
@@ -2795,6 +2985,12 @@ def store_member(email: str, key_token: str, cloudron_user_id: str, slug: str =
row = conn.execute("SELECT slug FROM members WHERE email = ?", (email,)).fetchone() row = conn.execute("SELECT slug FROM members WHERE email = ?", (email,)).fetchone()
if row and row[0]: if row and row[0]:
slug = row[0] slug = row[0]
# Reactivation is a transition worth keeping: a former member who returns
# gets active=1 here, and the log must show that alongside the lapse.
prior = conn.execute(
"SELECT active, COALESCE(account_type, 'member') FROM members WHERE email = ?",
(email,),
).fetchone()
# account_type: None (every normal path) preserves whatever the row holds — # account_type: None (every normal path) preserves whatever the row holds —
# re-provisioning a guest via the member pipeline must not un-guest it. Only # re-provisioning a guest via the member pipeline must not un-guest it. Only
# an explicit value (provision_guest_member passes 'guest') writes the column. # an explicit value (provision_guest_member passes 'guest') writes the column.
@@ -2807,6 +3003,12 @@ def store_member(email: str, key_token: str, cloudron_user_id: str, slug: str =
"ELSE COALESCE(members.account_type, 'member') END", "ELSE COALESCE(members.account_type, 'member') END",
(email, encrypt_key(key_token), cloudron_user_id, slug, account_type), (email, encrypt_key(key_token), cloudron_user_id, slug, account_type),
) )
if prior and not prior[0] and (prior[1] or "member") != "guest":
record_membership_event(
conn, email, "reactivated",
reason="Returned to active membership (provisioned again)",
source="provision", account_type=prior[1] or "member",
)
conn.commit() conn.commit()
conn.close() conn.close()
@@ -2859,13 +3061,25 @@ def get_member_by_slug(slug: str) -> dict | None:
return {"email": row[0], "key_token": decrypt_key(row[1]), "cloudron_user_id": row[2]} return {"email": row[0], "key_token": decrypt_key(row[1]), "cloudron_user_id": row[2]}
def deactivate_member(email: str) -> str | None: def deactivate_member(email: str, reason: str = "", source: str = "",
"""Mark member inactive and return their DECRYPTED key token (for deletion).""" detail: str = "") -> str | None:
"""Mark member inactive, log the transition, and return the DECRYPTED key.
The log row is written ONLY on the active → inactive transition, so an OC
re-delivery (or a second sweep pass) cannot append duplicate "deactivated"
events for one lapse.
"""
conn = get_db() conn = get_db()
row = conn.execute( row = conn.execute(
"SELECT key_token FROM members WHERE email = ?", (email,) "SELECT key_token, active, COALESCE(account_type, 'member') "
"FROM members WHERE email = ?", (email,)
).fetchone() ).fetchone()
conn.execute("UPDATE members SET active = 0 WHERE email = ?", (email,)) conn.execute("UPDATE members SET active = 0 WHERE email = ?", (email,))
if row and row[1]:
record_membership_event(
conn, email, "deactivated", reason=reason, source=source,
account_type=row[2], detail=detail,
)
conn.commit() conn.commit()
conn.close() conn.close()
return decrypt_key(row[0]) if row else None return decrypt_key(row[0]) if row else None
@@ -3739,7 +3953,12 @@ async def reconcile_guest_lifecycles() -> dict:
continue continue
if INACTIVE_GROUP_ID and user_id: if INACTIVE_GROUP_ID and user_id:
await cloudron_switch_group(user_id, INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,)) await cloudron_switch_group(user_id, INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,))
deactivate_member(email) deactivate_member(
email,
reason=f"Guest access ended ({reason})",
source="sweep-guest",
detail=f"guest lifecycle rule: {reason}",
)
await revoke_member_litellm_access(email) await revoke_member_litellm_access(email)
await listmonk_sync(email, subscribe=False) await listmonk_sync(email, subscribe=False)
conn = get_db() conn = get_db()
@@ -3888,7 +4107,12 @@ async def cancel_guest_account(email: str) -> dict:
# Deactivation, guest-lapse semantics: row inactive, group out of guests, # Deactivation, guest-lapse semantics: row inactive, group out of guests,
# gateway budget zeroed, newsletter off. # gateway budget zeroed, newsletter off.
deactivate_member(email) deactivate_member(
email,
reason="Guest cancelled by recipient",
source="guest-self-cancel",
detail="unspent guest credit returned to the co-op",
)
ended_group = GUESTS_ENDED_GROUP_ID or INACTIVE_GROUP_ID ended_group = GUESTS_ENDED_GROUP_ID or INACTIVE_GROUP_ID
if ended_group and user_id: if ended_group and user_id:
await cloudron_switch_group(user_id, ended_group, (GUESTS_GROUP_ID,)) await cloudron_switch_group(user_id, ended_group, (GUESTS_GROUP_ID,))
@@ -4036,23 +4260,216 @@ def next_reset_from_now() -> datetime:
async def sync_team_budget_from_balance(email: str) -> float: async def sync_team_budget_from_balance(email: str) -> float:
"""Apply the member's effective budget to their LiteLLM team. """Apply the member's effective budget to their LiteLLM team.
Effective budget = monthly allowance + remaining non-expiring credits Effective budget = monthly allowance + credits still available
(credits drawn only after the allowance is exhausted this cycle). Reads (credits drawn only after the allowance is exhausted; credits consumed in
the member's live spend from LiteLLM to determine how much credit has CLOSED cycles are deducted by `close_credit_cycles`). Reads the member's
already been consumed in the current cycle. Returns the applied budget. live spend from LiteLLM to split this cycle's spend for display only.
Returns the applied budget.
""" """
balance = get_member_balance(email) balance = get_member_balance(email)
credits = get_credit_balance(email) credits = get_credit_balance(email)
drawn = get_credits_drawn(email)
team_id = await litellm_get_or_create_team(email, balance) team_id = await litellm_get_or_create_team(email, balance)
# Live spend this cycle (DB path preferred; LiteLLM computes the reset). # Live spend this cycle (DB path preferred; LiteLLM computes the reset).
team = get_team_budget_from_db(team_id) or {} team = get_team_budget_from_db(team_id) or {}
team_spend = team.get("spend") 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"]) await litellm_update_team_budget(team_id, eff["max_budget"])
return 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 apply_cycle_draw(email: str, cycle_key: str, spend: float, allowance: float) -> float:
"""Draw a closed cycle's credit overage from a member's pack (idempotent).
The overage is `max(0, spend − allowance)`, 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))
draw = round(min(max(0.0, spend - allowance), 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)",
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] = []
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))
overage = max(0.0, spend - allowance)
draw = round(min(overage, available), 6)
if draw > 0:
drawn = apply_cycle_draw(email, cycle_key, spend, allowance)
if drawn > 0:
closed += 1
drawn_total += drawn
details.append({"email": email, "cycle": cycle_key,
"spend": round(spend, 2), "drawn": round(drawn, 2)})
try:
applied = await sync_team_budget_from_balance(email)
except Exception as exc: # noqa: BLE001
errors.append(f"{email}: cap sync failed: {str(exc)[:120]}")
else:
details[-1]["team_budget"] = applied
cycle_end = cycle_start
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,
"errors": errors,
"details": details,
}
async def litellm_create_key(email: str, budget: float, team_id: str) -> str: async def litellm_create_key(email: str, budget: float, team_id: str) -> str:
"""Create a fresh LiteLLM virtual key under the member's team. """Create a fresh LiteLLM virtual key under the member's team.
@@ -4891,7 +5308,12 @@ async def _process_opencollective_webhook(request: Request, token: str):
if INACTIVE_GROUP_ID and member.get("cloudron_user_id"): if INACTIVE_GROUP_ID and member.get("cloudron_user_id"):
await cloudron_switch_group(member["cloudron_user_id"], INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,)) await cloudron_switch_group(member["cloudron_user_id"], INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,))
# Mark inactive in our DB (key injector will refuse requests) # Mark inactive in our DB (key injector will refuse requests)
deactivate_member(member["email"]) deactivate_member(
member["email"],
reason=f"Open Collective membership deleted (slug {slug})",
source="webhook-opencollective",
detail="collective.member.deleted after OC live-roster re-check",
)
await revoke_member_litellm_access(member["email"]) await revoke_member_litellm_access(member["email"])
await listmonk_sync(member["email"], subscribe=False) await listmonk_sync(member["email"], subscribe=False)
await sync_loomio_memberships() await sync_loomio_memberships()
@@ -5509,6 +5931,7 @@ async def admin_credit_ledger(email: str, request: Request):
return { return {
"email": email, "email": email,
"credit_balance": get_credit_balance(email), "credit_balance": get_credit_balance(email),
"credits_drawn": get_credits_drawn(email),
"ledger": [ "ledger": [
{"delta": r[0], "reason": r[1], "reference": r[2], "created_at": r[3]} {"delta": r[0], "reason": r[1], "reference": r[2], "created_at": r[3]}
for r in rows for r in rows
@@ -5516,6 +5939,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") @app.get("/admin/held-credits")
@limiter.limit("30/minute") @limiter.limit("30/minute")
async def admin_held_credits(request: Request): async def admin_held_credits(request: Request):
@@ -5724,6 +6160,36 @@ 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)."""
events = [
{
"id": r[0], "email": r[1], "account_type": r[2], "event": r[3],
"reason": r[4] or "", "source": r[5] or "",
"occurred_at": r[6], "recorded_at": r[7], "detail": r[8] or "",
}
for r in conn.execute(
"SELECT id, email, account_type, event, reason, source, "
"occurred_at, recorded_at, detail FROM membership_events "
"ORDER BY (occurred_at IS NULL), "
" COALESCE(occurred_at, recorded_at) DESC, id DESC LIMIT 500"
).fetchall()
]
latest: dict[str, dict] = {}
for r in conn.execute(
"SELECT e.email, e.reason, e.source, e.occurred_at, e.recorded_at "
"FROM membership_events e "
"WHERE e.event = 'deactivated' AND e.account_type != 'guest' "
"AND e.id = (SELECT MAX(x.id) FROM membership_events x "
" WHERE x.email = e.email AND x.event = 'deactivated')"
).fetchall():
latest[(r[0] or "").strip().lower()] = {
"at": r[3], "recorded_at": r[4],
"reason": r[1] or "", "source": r[2] or "",
}
return events, latest
@app.get("/admin/overview") @app.get("/admin/overview")
@limiter.limit("30/minute") @limiter.limit("30/minute")
async def admin_overview(request: Request): async def admin_overview(request: Request):
@@ -5742,7 +6208,7 @@ async def admin_overview(request: Request):
rows = conn.execute( rows = conn.execute(
"SELECT email, active, balance, cloudron_user_id, org_slug, matrix_mxid, " "SELECT email, active, balance, cloudron_user_id, org_slug, matrix_mxid, "
"matrix_mxid_changed_at, account_type, oc_email, guest_expires_at, " "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() ).fetchall()
# Guest inviter/expiry from the guests ledger (latest row per recipient) — # Guest inviter/expiry from the guests ledger (latest row per recipient) —
# the abuse-protection context the panel shows on the guest pill, plus the # the abuse-protection context the panel shows on the guest pill, plus the
@@ -5757,6 +6223,15 @@ async def admin_overview(request: Request):
"sent": r[4]} "sent": r[4]}
except Exception as e: except Exception as e:
logger.warning("admin overview: guests ledger read failed: %s", e) logger.warning("admin overview: guests ledger read failed: %s", e)
# The durable membership log: newest first for the panel's Membership log.
# occurred_at is NULL for rows backfilled from a pre-existing inactive row;
# recorded_at is when the row was written, never a claim about when the
# lapse happened.
try:
membership_events, latest_deactivation = _membership_events_for_overview(conn)
except Exception as e:
logger.warning("admin overview: membership events read failed: %s", e)
membership_events, latest_deactivation = [], {}
conn.close() conn.close()
# Fetch Cloudron users once to map user_id → username + inviteAccepted. # Fetch Cloudron users once to map user_id → username + inviteAccepted.
@@ -5826,7 +6301,7 @@ async def admin_overview(request: Request):
operator_all_time = 0.0 operator_all_time = 0.0
guest_spend = 0.0 guest_spend = 0.0
guest_all_time = 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}", {}) team = teams.get(f"member:{email}", {})
spend = float(team.get("spend") or 0.0) spend = float(team.get("spend") or 0.0)
member_all_time = float(all_time_spend.get(f"member:{email}", 0.0)) member_all_time = float(all_time_spend.get(f"member:{email}", 0.0))
@@ -5841,6 +6316,7 @@ async def admin_overview(request: Request):
float(balance) if balance is not None else MEMBER_BUDGET, float(balance) if balance is not None else MEMBER_BUDGET,
credits, credits,
spend, spend,
float(credits_drawn or 0.0),
) )
mstate, mstate_reason = member_membership_state(email, bool(active)) mstate, mstate_reason = member_membership_state(email, bool(active))
if ((acct_type or "member") == "guest" and active if ((acct_type or "member") == "guest" and active
@@ -5859,6 +6335,7 @@ async def admin_overview(request: Request):
mstate_reason = (f"awaiting setup — invite sent {str(sent)[:10]}, " mstate_reason = (f"awaiting setup — invite sent {str(sent)[:10]}, "
"not yet accepted" if sent else "not yet accepted" if sent else
"awaiting setup — invitation not yet accepted") "awaiting setup — invitation not yet accepted")
dep = latest_deactivation.get((email or "").strip().lower())
entry = { entry = {
"email": email, "email": email,
"all_time_spend": round(member_all_time, 2), "all_time_spend": round(member_all_time, 2),
@@ -5874,7 +6351,7 @@ async def admin_overview(request: Request):
"matrix_mxid_changed_at": mxid_changed_at or None, "matrix_mxid_changed_at": mxid_changed_at or None,
"balance": float(balance) if balance is not None else MEMBER_BUDGET, "balance": float(balance) if balance is not None else MEMBER_BUDGET,
"credit_balance": credits, "credit_balance": credits,
"credits_remaining": max(0.0, credits - eff["credits_used"]), "credits_remaining": eff["credits_remaining"],
"allowance_used": eff["allowance_used"], "allowance_used": eff["allowance_used"],
"credits_used": eff["credits_used"], "credits_used": eff["credits_used"],
"spend": spend, "spend": spend,
@@ -5891,6 +6368,12 @@ async def admin_overview(request: Request):
"dues_frequency": dues_freq or None, "dues_frequency": dues_freq or None,
"dues_updated_at": dues_updated or None, "dues_updated_at": dues_updated or None,
"guest_expires_at": guest_exp or None, "guest_expires_at": guest_exp or None,
# Latest deactivation on record. at is NULL for a backfilled row —
# the panel must show "unknown", never the backfill's write time.
"deactivated_at": dep.get("at") if dep else None,
"deactivated_recorded_at": dep.get("recorded_at") if dep else None,
"deactivated_reason": dep.get("reason", "") if dep else "",
"deactivated_source": dep.get("source", "") if dep else "",
} }
if (acct_type or "member") == "guest": if (acct_type or "member") == "guest":
gi = guest_info.get(email) or {} gi = guest_info.get(email) or {}
@@ -5961,6 +6444,7 @@ async def admin_overview(request: Request):
"guests": guests, "guests": guests,
"admins": admins, "admins": admins,
"agents": agents, "agents": agents,
"membership_events": membership_events,
"totals": { "totals": {
"members": len(members), "members": len(members),
"active": sum(1 for m in members if m["active"]), "active": sum(1 for m in members if m["active"]),
@@ -7130,6 +7614,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
allowance = get_member_balance(email) allowance = get_member_balance(email)
credits = get_credit_balance(email) credits = get_credit_balance(email)
credits_drawn = get_credits_drawn(email)
spend = 0.0 spend = 0.0
reset_at = None reset_at = None
@@ -7186,7 +7671,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
"balance": balance, "balance": balance,
"allowance": allowance, "allowance": allowance,
"credits": credits, "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, "spend": spend,
"all_time_spend": round(all_time_spend, 2), "all_time_spend": round(all_time_spend, 2),
"remaining": max(balance - spend, 0.0), "remaining": max(balance - spend, 0.0),
@@ -7269,7 +7754,7 @@ async def broker_get_usage(email: str, days: int = 0) -> dict:
"balance": balance, "balance": balance,
"allowance": allowance, "allowance": allowance,
"credits": credits, "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, "spend": spend,
"all_time_spend": all_time_spend, "all_time_spend": all_time_spend,
"remaining": max(balance - spend, 0.0), "remaining": max(balance - spend, 0.0),
@@ -7815,7 +8300,12 @@ async def reconcile_memberships() -> dict:
try: try:
if INACTIVE_GROUP_ID and user_id: if INACTIVE_GROUP_ID and user_id:
await cloudron_switch_group(user_id, INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,)) await cloudron_switch_group(user_id, INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,))
deactivate_member(email) deactivate_member(
email,
reason="Membership lapsed: no longer on the live Open Collective member list",
source="sweep",
detail="reconcile_memberships: OC live roster checked; member absent",
)
await revoke_member_litellm_access(email) await revoke_member_litellm_access(email)
await listmonk_sync(email, subscribe=False) await listmonk_sync(email, subscribe=False)
deactivated_count += 1 deactivated_count += 1
@@ -8083,37 +8573,55 @@ def cycle_start_for_anchor_day(anchor_day: int, now: datetime | None = None) ->
async def fetch_member_orders() -> dict[str, list[dict]]: async def fetch_member_orders() -> dict[str, list[dict]]:
"""Every OC order for the collective, grouped by the payer's slug. """Every OC order for the collective, grouped by the payer's slug.
One query for the whole collective (orders(limit: 200)) rather than a call Paginated read for the whole collective (OC's own totalCount decides when
per member. Raises on failure so the caller can skip rather than mis-decide. to stop) rather than a fixed page or a call per member. Raises on failure —
including a PARTIAL read — so the caller can skip rather than mis-decide.
""" """
if not OC_PERSONAL_TOKEN: if not OC_PERSONAL_TOKEN:
raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch orders") raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch orders")
query = ( per_page = 100
'{ collective(slug: "%s") { orders(limit: 200) { totalCount nodes { ' max_pages = 20 # 2,000 orders — a runaway loop is worse than a short read
query_tpl = (
'{ collective(slug: "%s") { orders(limit: %d, offset: %d) { totalCount nodes { '
"frequency status createdAt lastChargedAt nextChargeDate " "frequency status createdAt lastChargedAt nextChargeDate "
"fromAccount { slug } amount { value currency } totalAmount { value currency } } } } }" "fromAccount { slug } amount { value currency } totalAmount { value currency } } } } }"
% OC_COLLECTIVE_SLUG
) )
async with httpx.AsyncClient(timeout=30.0) as client:
r = await client.post(
OC_GRAPHQL_URL,
headers={"Content-Type": "application/json",
"Authorization": f"Bearer {OC_PERSONAL_TOKEN}",
"Api-Version": "2022-01-01",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"},
json={"query": query},
)
if r.status_code != 200:
raise RuntimeError(f"OC order fetch failed: HTTP {r.status_code}")
body = r.json()
if body.get("errors"):
raise RuntimeError(f"OC order fetch errors: {str(body['errors'])[:200]}")
orders = (((body.get("data") or {}).get("collective") or {}).get("orders") or {})
by_slug: dict[str, list[dict]] = {} by_slug: dict[str, list[dict]] = {}
for o in orders.get("nodes") or []: seen = 0
slug = ((o.get("fromAccount") or {}).get("slug") or "").strip() total = None
if slug: async with httpx.AsyncClient(timeout=30.0) as client:
by_slug.setdefault(slug, []).append(o) for page in range(max_pages):
r = await client.post(
OC_GRAPHQL_URL,
headers={"Content-Type": "application/json",
"Authorization": f"Bearer {OC_PERSONAL_TOKEN}",
"Api-Version": "2022-01-01",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"},
json={"query": query_tpl % (OC_COLLECTIVE_SLUG, per_page, page * per_page)},
)
if r.status_code != 200:
raise RuntimeError(f"OC order fetch failed: HTTP {r.status_code}")
body = r.json()
if body.get("errors"):
raise RuntimeError(f"OC order fetch errors: {str(body['errors'])[:200]}")
orders = (((body.get("data") or {}).get("collective") or {}).get("orders") or {})
nodes = orders.get("nodes") or []
total = orders.get("totalCount") or 0
for o in nodes:
slug = ((o.get("fromAccount") or {}).get("slug") or "").strip()
if slug:
by_slug.setdefault(slug, []).append(o)
seen += len(nodes)
if len(nodes) < per_page or seen >= total:
break
# A read that fell short of OC's own total is PARTIAL, however it ended:
# a partial order list reads as "this member has no recurring
# contribution", which reminds (then deactivates) a paying member —
# so fail loudly instead of returning a shorter, wrong answer.
if total is not None and seen < total:
raise RuntimeError(
f"OC order fetch incomplete: read {seen} of {total} orders "
f"(page cap {max_pages})")
return by_slug return by_slug
@@ -8683,7 +9191,12 @@ async def reconcile_allowances(send: bool = False) -> dict:
).fetchone() ).fetchone()
if INACTIVE_GROUP_ID and urow and urow[0]: if INACTIVE_GROUP_ID and urow and urow[0]:
await cloudron_switch_group(urow[0], INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,)) await cloudron_switch_group(urow[0], INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,))
deactivate_member(email) deactivate_member(
email,
reason="Membership lapsed after the payment grace window",
source="allowance-reconcile",
detail=f"last reminder {str(reminded[0])[:10] if reminded[0] else '?'}; grace {int(PAYMENT_GRACE_DAYS)}d elapsed",
)
await revoke_member_litellm_access(email) await revoke_member_litellm_access(email)
await listmonk_sync(email, subscribe=False) await listmonk_sync(email, subscribe=False)
@@ -8882,27 +9395,45 @@ async def fetch_oc_monthly_order_charges() -> list[dict]:
""" """
if not OC_PERSONAL_TOKEN: if not OC_PERSONAL_TOKEN:
raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch order charges") raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch order charges")
query = ( # Paginate: a fixed limit silently dropped the OLDEST orders once the
'{ collective(slug: "%s") { orders(limit: 200) { totalCount nodes { ' # collective passed it, and an order missing from this read is a truncated
# cycle the shortfall pass can never see (or, worse, an order it misreads).
per_page = 100
max_pages = 20
query_tpl = (
'{ collective(slug: "%s") { orders(limit: %d, offset: %d) { totalCount nodes { '
"id frequency fromAccount { slug } " "id frequency fromAccount { slug } "
"transactions { publicId createdAt type kind isRefund } } } } }" "transactions { publicId createdAt type kind isRefund } } } } }"
% OC_COLLECTIVE_SLUG
) )
nodes: list[dict] = []
seen = 0
total = None
async with httpx.AsyncClient(timeout=30.0) as client: async with httpx.AsyncClient(timeout=30.0) as client:
r = await client.post( for page in range(max_pages):
OC_GRAPHQL_URL, r = await client.post(
headers={"Content-Type": "application/json", OC_GRAPHQL_URL,
"Authorization": f"Bearer {OC_PERSONAL_TOKEN}", headers={"Content-Type": "application/json",
"Api-Version": "2022-01-01", "Authorization": f"Bearer {OC_PERSONAL_TOKEN}",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"}, "Api-Version": "2022-01-01",
json={"query": query}, "User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"},
) json={"query": query_tpl % (OC_COLLECTIVE_SLUG, per_page, page * per_page)},
if r.status_code != 200: )
raise RuntimeError(f"OC order-charge fetch failed: HTTP {r.status_code}") if r.status_code != 200:
body = r.json() raise RuntimeError(f"OC order-charge fetch failed: HTTP {r.status_code}")
if body.get("errors"): body = r.json()
raise RuntimeError(f"OC order-charge fetch errors: {str(body['errors'])[:200]}") if body.get("errors"):
nodes = (((body.get("data") or {}).get("collective") or {}).get("orders") or {}).get("nodes") or [] raise RuntimeError(f"OC order-charge fetch errors: {str(body['errors'])[:200]}")
orders = (((body.get("data") or {}).get("collective") or {}).get("orders") or {})
page_nodes = orders.get("nodes") or []
total = orders.get("totalCount") or 0
nodes.extend(page_nodes)
seen += len(page_nodes)
if len(page_nodes) < per_page or seen >= total:
break
if total is not None and seen < total:
raise RuntimeError(
f"OC order-charge fetch incomplete: read {seen} of {total} orders "
f"(page cap {max_pages})")
out: list[dict] = [] out: list[dict] = []
for o in nodes: for o in nodes:
if (o.get("frequency") or "").upper() != "MONTHLY": if (o.get("frequency") or "").upper() != "MONTHLY":
@@ -10113,7 +10644,7 @@ async def derive_member_sources() -> dict:
return {"checked": len(stale), "flipped": flipped} return {"checked": len(stale), "flipped": flipped}
FX_POLICY_EUR_USD = float(os.environ.get("FX_POLICY_EUR_USD", "1.16") or 1.16) 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) FX_ALERT_PCT = float(os.environ.get("FX_ALERT_PCT", "2.0") or 2.0)
@@ -10126,7 +10657,7 @@ def _fx_verdict(rate: float, policy: float = FX_POLICY_EUR_USD,
async def fx_spot_check(send: bool = True) -> dict: 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 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 first crosses FX_ALERT_PCT; staying over the line does not mail every day. When
@@ -10160,12 +10691,17 @@ async def fx_spot_check(send: bool = True) -> dict:
direction = "above" if verdict["drift_pct"] > 0 else "below" direction = "above" if verdict["drift_pct"] > 0 else "below"
verdict["notified"] = bool(send_email( verdict["notified"] = bool(send_email(
ADMIN_INVITER_EMAIL, ADMIN_INVITER_EMAIL,
f"EUR/USD {verdict['drift_pct']:+.1f}% {direction} the pricing FX", f"EUR/USD {verdict['drift_pct']:+.1f}% {direction} the fallback pin",
f"The ECB rate is {verdict['rate']} USD per EUR; our pricing policy is " f"The ECB rate is {verdict['rate']} USD per EUR; the written fallback "
f"{verdict['policy']}. Drift: {verdict['drift_pct']:+.1f}%.\n\n" f"pin is {verdict['policy']}. Drift: {verdict['drift_pct']:+.1f}%.\n\n"
"No prices were changed automatically. Decide whether to re-convert " "Live billing is not affected: the gateway re-converts GreenPT/Regolo "
"GreenPT/Regolo EUR list prices at the new rate (scripts/check_eur_fx.py " "EUR list prices at the ECB daily rate on every boot (fx_sync.py). "
"in code/litellm guards the conversion).\n")) "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() conn = get_db()
try: try:
@@ -10234,6 +10770,13 @@ async def admin_sweep(request: Request):
except Exception as exc: # noqa: BLE001 except Exception as exc: # noqa: BLE001
result["held_credits"] = {"error": str(exc)[:200]} 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: try:
result["member_sources"] = await derive_member_sources() result["member_sources"] = await derive_member_sources()
except Exception as exc: # noqa: BLE001 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
+154
View File
@@ -0,0 +1,154 @@
#!/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, 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)
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 import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m import app.main as m
v=m._fx_verdict(1.16); assert v["alert"] is False, v v=m._fx_verdict(1.0975); 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.13); 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.07); 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.0995); assert v["alert"] is False, v # 0.18% drift
print("FX VERDICT OK: thresholds and signs behave") print("FX VERDICT OK: thresholds and signs behave")
+171
View File
@@ -0,0 +1,171 @@
#!/usr/bin/env python3
"""Membership events — the durable record of who lapsed and who returned.
WHY THIS EXISTS
Before this table, a lapse was only members.active = 0: no date, no reason,
no source. A former member was indistinguishable from someone who had never
paid, and a returning payer silently erased the fact that they had lapsed.
Every deactivation/reactivation transition now writes one row, and the admin
overview carries the log plus the latest deactivation per member.
The tests pin:
1. deactivate_member logs ONE row on the active -> inactive transition;
a repeated call (OC re-delivery / second sweep pass) does not duplicate.
2. store_member logs `reactivated` when it flips an inactive member back on.
3. backfill gives a pre-existing inactive member one row with occurred_at
NULL and a reason derived from allowance_log; it runs once.
4. the overview helper returns the newest-first log and maps the latest
deactivation to the member's email (None date for a backfilled row).
Runnable: python3 tests/test_membership_events.py (from the repo root)
"""
import base64
import os
import sys
import tempfile
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "events-fixture.db")
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m # noqa: E402
m.DB_PATH = os.environ["DB_PATH"]
FAILS = []
def check(cond, msg):
print((" ok " if cond else " FAIL ") + msg)
if not cond:
FAILS.append(msg)
def rows(q, args=()):
conn = m.get_db()
try:
return conn.execute(q, args).fetchall()
finally:
conn.close()
print("1. deactivation logs exactly one transition")
conn = m.get_db()
m._ensure_allowance_tables(conn)
conn.execute("DELETE FROM members")
conn.execute("DELETE FROM membership_events")
conn.execute("DELETE FROM portal_state")
conn.execute(
"INSERT INTO members (email, active, account_type) VALUES (?, 1, 'member')",
("lapse@example.org",),
)
conn.commit()
conn.close()
m.deactivate_member(
"lapse@example.org",
reason="Membership lapsed: no longer on the live Open Collective member list",
source="sweep",
)
ev = rows(
"SELECT email, event, reason, source, occurred_at, account_type "
"FROM membership_events WHERE email = ?",
("lapse@example.org",),
)
check(len(ev) == 1, "one deactivation row written")
check(ev[0][1] == "deactivated", "event is 'deactivated'")
check(ev[0][3] == "sweep", "source records the calling path")
check("Open Collective" in ev[0][2], "reason records why")
check(bool(ev[0][4]), "live transition carries occurred_at")
check(ev[0][5] == "member", "account_type is carried onto the event")
# A re-delivered webhook / second sweep pass must not append another lapse.
m.deactivate_member(
"lapse@example.org",
reason="duplicate delivery",
source="webhook-opencollective",
)
ev = rows(
"SELECT event FROM membership_events WHERE email = ?",
("lapse@example.org",),
)
check(len(ev) == 1, "a repeated deactivation writes no duplicate row")
print("2. a returning payer is logged as reactivated")
m.store_member("lapse@example.org", "sk-fixture", "uid-fixture")
ev = rows(
"SELECT event, source FROM membership_events WHERE email = ? ORDER BY id",
("lapse@example.org",),
)
check([r[0] for r in ev] == ["deactivated", "reactivated"],
"deactivated then reactivated, in order")
check(ev[-1][1] == "provision", "reactivation source is provisioning")
active = rows("SELECT active FROM members WHERE email = ?", ("lapse@example.org",))
check(active[0][0] == 1, "member is active again")
print("3. backfill gives a pre-existing inactive member a dated-unknown row")
conn = m.get_db()
conn.execute("DELETE FROM membership_events")
conn.execute("DELETE FROM portal_state")
conn.execute("DELETE FROM members")
conn.execute(
"INSERT INTO members (email, active, account_type, welcome_sent_at) "
"VALUES (?, 0, 'member', ?)",
("old@example.org", "2026-11-11 19:00:47"),
)
conn.execute(
"INSERT INTO allowance_log (email, cycle, decision, evidence, decided_at) "
"VALUES (?, ?, ?, ?, ?)",
("old@example.org", "2026-11-16", "in_grace",
"no recurring (monthly) contribution on Open Collective; reminder sent 2026-11-16 (grace 7d)",
"2026-11-18 11:02:37"),
)
conn.commit()
m._backfill_membership_events(conn)
conn.commit()
ev = conn.execute(
"SELECT event, reason, source, occurred_at, detail FROM membership_events "
"WHERE email = ?", ("old@example.org",),
).fetchall()
conn.close()
check(len(ev) == 1, "one backfilled row")
check(ev[0][0] == "deactivated" and ev[0][2] == "backfill",
"backfill event/source are explicit")
check(ev[0][3] is None, "backfilled occurred_at stays NULL (unknown date)")
check("in_grace" in ev[0][1] and "2026-11-18" in ev[0][1],
"backfill reason quotes the allowance decision and date")
check("exact" in ev[0][4].lower(), "detail says the exact date is unknown")
# Re-running the backfill must not duplicate the row (the marker gates it).
conn = m.get_db()
m._backfill_membership_events(conn)
conn.commit()
n = conn.execute(
"SELECT COUNT(*) FROM membership_events WHERE email = ?", ("old@example.org",),
).fetchone()[0]
conn.close()
check(n == 1, "backfill is idempotent")
print("4. the overview helper returns the log and the latest deactivation")
conn = m.get_db()
conn.execute(
"INSERT INTO membership_events (email, account_type, event, reason, source, occurred_at) "
"VALUES (?, 'member', 'reactivated', ?, 'provision', ?)",
("old@example.org", "Returned to active membership", "2026-11-24 12:00:00"),
)
conn.commit()
events, latest = m._membership_events_for_overview(conn)
conn.close()
check(len(events) == 2, "both events are in the log")
check(events[0]["event"] == "reactivated", "newest event sorts first")
check("old@example.org" in latest, "latest deactivation is keyed by email")
check(latest["old@example.org"]["at"] is None,
"backfilled latest deactivation reports an unknown date")
check(latest["old@example.org"]["source"] == "backfill",
"latest deactivation keeps its source")
print()
if FAILS:
print(f"FAILED: {len(FAILS)} check(s) red")
sys.exit(1)
print("all membership-event checks green")
+170
View File
@@ -0,0 +1,170 @@
#!/usr/bin/env python3
"""Regression test: the OC order reads must PAGE, not stop at a fixed limit.
WHY THIS EXISTS
fetch_member_orders() asked OC for `orders(limit: 200)` in ONE request. The
collective passed 200 orders on 2026-11-23 (203), and the orders beyond the
window are the OLDEST ones — exactly where a long-standing member's recurring
contribution lives. Those members read as "no recurring (monthly)
contribution on Open Collective", so the allowance sweep sent them a
payment reminder for a contribution that was LIVE and charged days earlier.
Three paying members (ntnsndr, elizabeth-barry1, guest-0f6d98ac) got that
wrong email at 03:02 UTC on 2026-11-23.
fetch_oc_monthly_order_charges() had the same fixed window; an order missing
from it is a truncated paid cycle the shortfall credit pass cannot see.
WHAT IS PINNED HERE
* every order is read across pages (203 orders -> two pages, oldest included),
* a member whose ONLY recurring order is the oldest one is still matched,
* an INCOMPLETE read (OC reports more than it served) raises instead of
returning a short list, because a short list reads as "nobody is paying",
* the charge ladder for the oldest monthly orders is read too.
Runnable from the repo root: python3 tests/test_order_pagination.py
"""
import os
import sys
import asyncio
import tempfile
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m # noqa: E402
m.DB_PATH = os.environ["DB_PATH"]
m.OC_PERSONAL_TOKEN = "test-token"
m.OC_COLLECTIVE_SLUG = "inference-cooperative"
# The three slugs whose live monthly orders were the OLDEST in production and
# therefore fell outside the fixed 200-order window.
OLDEST = ["ntnsndr", "elizabeth-barry1", "guest-0f6d98ac"]
TOTAL_ORDERS = 203
SERVED: dict[str, int | None] = {"n": None} # None = serve everything; an int = pretend truncation
REQUESTS = []
def make_nodes(n=TOTAL_ORDERS):
"""Newest-first list; the OLDEST three are our live monthly members."""
nodes = []
for i in range(n):
oldest_rank = n - 1 - i # 0 for the newest, n-1 for the oldest
slug = OLDEST[oldest_rank] if oldest_rank < len(OLDEST) else f"member{oldest_rank}"
nodes.append({
"id": f"or_{slug}",
"frequency": "MONTHLY",
"status": "ACTIVE",
"createdAt": f"2026-{9 + oldest_rank // 30:02d}-{(oldest_rank % 28) + 1:02d}T10:00:00Z",
"lastChargedAt": "2026-11-02T17:06:25.000Z",
"nextChargeDate": "2026-12-01T00:00:00.000Z",
"fromAccount": {"slug": slug},
"amount": {"value": 15, "currency": "USD"},
"totalAmount": {"value": 15.75, "currency": "USD"},
"transactions": [
{"publicId": f"txn_{slug}_a", "createdAt": "2026-10-02T10:00:00Z",
"type": "CREDIT", "kind": "CONTRIBUTION", "isRefund": False},
{"publicId": f"txn_{slug}_b", "createdAt": "2026-11-02T10:00:00Z",
"type": "CREDIT", "kind": "CONTRIBUTION", "isRefund": False},
],
})
return nodes
NODES = make_nodes()
class Resp:
def __init__(self, body, status_code=200):
self._body = body
self.status_code = status_code
def json(self):
return self._body
def _int_arg(query, name):
"""Read `name: <int>` out of the GraphQL query string."""
for part in query.split("orders(")[1].split(")")[0].split(","):
k, _, v = part.strip().partition(":")
if k.strip() == name:
return int(v)
raise AssertionError(f"query carries no {name}: {query}")
class FakeClient:
"""Async httpx stand-in: serves OC's orders connection page by page."""
def __init__(self, *a, **k):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
async def post(self, url, headers=None, json=None):
q = (json or {}).get("query", "")
REQUESTS.append(q)
limit = _int_arg(q, "limit")
offset = _int_arg(q, "offset")
served = SERVED["n"] if SERVED["n"] is not None else len(NODES)
page = NODES[offset:offset + limit] if offset < served else []
return Resp({"data": {"collective": {"orders": {
"totalCount": len(NODES), "nodes": page}}}})
m.httpx.AsyncClient = FakeClient
results = []
def check(name, ok):
results.append((name, bool(ok)))
async def main():
# --- fetch_member_orders: every order read, oldest members matched ---------
REQUESTS.clear()
by_slug = await m.fetch_member_orders()
check(f"orders read across pages (got {len(REQUESTS)} requests)", len(REQUESTS) == 3)
check(f"all 203 payers grouped (got {len(by_slug)})", len(by_slug) == TOTAL_ORDERS)
for slug in OLDEST:
orders = by_slug.get(slug) or []
check(f"oldest member {slug} is matched ({len(orders)} order)",
len(orders) == 1 and orders[0].get("status") == "ACTIVE")
# the fixed-limit bug's exact reading: these three used to be absent
check("no member is dropped by a 200-entry window",
all(s in by_slug for s in OLDEST))
# --- a partial read must RAISE, never answer short ------------------------
REQUESTS.clear()
SERVED["n"] = 200 # OC says 203, serves 200
raised = None
try:
await m.fetch_member_orders()
except RuntimeError as e:
raised = str(e)
SERVED["n"] = None
check(f"incomplete read raises (got {raised!r})",
raised is not None and "incomplete" in raised)
# --- fetch_oc_monthly_order_charges: paginated too -----------------------
REQUESTS.clear()
records = await m.fetch_oc_monthly_order_charges()
check(f"charge pass pages (got {len(REQUESTS)} requests)", len(REQUESTS) == 3)
check(f"charge pass covers every monthly order (got {len(records)})",
len(records) == TOTAL_ORDERS)
oldest_ids = {f"or_{s}" for s in OLDEST}
check("oldest orders' charge ladders present",
oldest_ids <= {r.get("order_id") for r in records})
asyncio.run(main())
fails = sum(not ok for _, ok in results)
for name, ok in results:
print(f" [{'PASS' if ok else 'FAIL'}] {name}")
print(f"\n{len(results) - fails}/{len(results)} passed")
sys.exit(1 if fails else 0)
+9 -2
View File
@@ -74,6 +74,7 @@ UNREADABLE = set() # rooms whose joined_members 500s
invites_sent = [] # (room, mxid) invites_sent = [] # (room, mxid)
INVITE_429_FOR = set() # mxids whose invite comes back 429 INVITE_429_FOR = set() # mxids whose invite comes back 429
INVITE_TIMEOUT_FOR = set() # mxids whose invite POST raises httpx.ReadTimeout INVITE_TIMEOUT_FOR = set() # mxids whose invite POST raises httpx.ReadTimeout
TIMEOUT_ATTEMPTS = [] # (room, mxid) for every POST that timed out
POSTS = [] # Loomio POST payloads POSTS = [] # Loomio POST payloads
ROSTER = {} # Loomio roster: email -> membership id ROSTER = {} # Loomio roster: email -> membership id
@@ -129,6 +130,7 @@ class FakeClient:
if "/invite" in url: if "/invite" in url:
mxid = (json or {}).get("user_id") mxid = (json or {}).get("user_id")
if mxid in INVITE_TIMEOUT_FOR: if mxid in INVITE_TIMEOUT_FOR:
TIMEOUT_ATTEMPTS.append((url, mxid))
raise httpx.ReadTimeout("timed out") raise httpx.ReadTimeout("timed out")
if mxid in INVITE_429_FOR: if mxid in INVITE_429_FOR:
return FakeResp(429, {"retry_after_ms": 300000}, return FakeResp(429, {"retry_after_ms": 300000},
@@ -165,6 +167,7 @@ def reset():
global invites_sent global invites_sent
invites_sent = [] invites_sent = []
POSTS.clear() POSTS.clear()
TIMEOUT_ATTEMPTS.clear()
async def main(): async def main():
@@ -209,8 +212,8 @@ async def main():
not any(mx == "@amember:inference.coop" for _, mx in invites_sent)) not any(mx == "@amember:inference.coop" for _, mx in invites_sent))
check("per-room: two members can be pending on different rooms", check("per-room: two members can be pending on different rooms",
not any(mx == "@cmember:inference.coop" for _, mx in invites_sent)) not any(mx == "@cmember:inference.coop" for _, mx in invites_sent))
check("return shape: the result carries invited + rate_limited", check("return shape: the result carries invited + rate_limited + transport_skipped",
set(r) == {"invited", "rate_limited"} and r["rate_limited"] is False) set(r) == {"invited", "rate_limited", "transport_skipped"} and r["rate_limited"] is False)
# --- 2. IDEMPOTENCE: a second pass sends nothing ---------------------- # --- 2. IDEMPOTENCE: a second pass sends nothing ----------------------
reset() reset()
@@ -325,6 +328,10 @@ async def main():
{room for room, _ in invites_sent} == set(ROOMS) {room for room, _ in invites_sent} == set(ROOMS)
and all(mx == "@umember:inference.coop" for _, mx in invites_sent)) and all(mx == "@umember:inference.coop" for _, mx in invites_sent))
check("timeout: the timed-out member is not counted as invited", r["invited"] == 1) check("timeout: the timed-out member is not counted as invited", r["invited"] == 1)
check("timeout: a timed-out member is attempted ONCE, not once per room",
len(TIMEOUT_ATTEMPTS) == 1)
check("timeout: the pass reports the member whose rooms it skipped",
r.get("transport_skipped") == 1)
# The next pass retries the timed-out member (invites are idempotent). # The next pass retries the timed-out member (invites are idempotent).
INVITE_TIMEOUT_FOR = set() INVITE_TIMEOUT_FOR = set()