Author SHA1 Message Date
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
inference-admin f09bec67d8 Merge pull request 'Loomio sync: a stamp must not outlive the membership' (#9) from loomio-reconcile into main
ci/woodpecker/push/woodpecker Pipeline failed
Reviewed-on: #9
2026-11-22 19:47:22 +00:00
inference-bot ffed06d492 loomio sync: a stamp must not outlive the membership
ci/woodpecker/push/woodpecker Pipeline failed
The invite stamp meant 'handed to Loomio once, EVER', so a member whose
membership was later revoked (a lapse that was reversed) or who deleted
their Loomio account was recorded as invited and never invited again.

- Stamp only the addresses Loomio actually returns in added_emails; an
  address accepted in the payload but not added stays eligible.
- Clear the stamp for an ACTIVE member stamped-but-absent from the live
  roster; the invite itself waits one pass so a single stale page cannot
  become an invite.
- Cap stamp clearing per pass (LOOMIO_RECONCILE_MAX, default 10): more
  stamped-but-absent members means a short roster read, not a mass
  re-invite.
- loomio_opt_out exempts members who deliberately left.
- Username fix falls back to the portal slug when a handle is already
  taken (Loomio handles are instance-global; every OC alias resolves to
  opencollective).
2026-11-22 19:45:20 +00:00
6 changed files with 629 additions and 45 deletions

No files matched your search

+1 -1
View File
@@ -31,5 +31,5 @@
"manifestVersion": 2,
"website": "https://inference.coop",
"contactEmail": "info@inference.coop",
"dockerImage": "registry.inference.coop/code/member-portal:20261121-b761136"
"dockerImage": "registry.inference.coop/code/member-portal:20261123-db0c09e"
}
+223 -32
View File
@@ -552,6 +552,10 @@ LOOMIO_B3_KEY = os.environ.get("LOOMIO_B3_KEY", "")
# right way by making the ADD path idempotent, NOT by switching the feature
# off — see sync_loomio_memberships for the guards.)
LOOMIO_SYNC_ENABLED = os.environ.get("LOOMIO_SYNC_ENABLED", "1").strip().lower() not in ("0", "false", "off", "no")
# Safety cap for the reconcile step: if more stamped-but-absent members show up
# than this in one pass, treat it as a short roster read and change nothing
# rather than risk a mass re-invite (the incident of 2026-11-04).
LOOMIO_RECONCILE_MAX = int(os.environ.get("LOOMIO_RECONCILE_MAX", "10"))
# Matrix homeserver (self-hosted Synapse at matrix.inference.coop). The bot
# account (admin) invites every active member to the co-op Space on sync.
@@ -1156,6 +1160,12 @@ def get_db() -> sqlite3.Connection:
# invited) can never be sent a Loomio invite a second time.
if "loomio_invited_at" not in cols:
conn.execute("ALTER TABLE members ADD COLUMN loomio_invited_at TEXT")
# Migration: loomio_opt_out — 1 when a member deliberately left Loomio
# (self-service account deactivation or leaving the group). The reconcile
# step below re-invites an ACTIVE member who is stamped-but-absent; this flag
# exempts someone who left on purpose from being dragged back in.
if "loomio_opt_out" not in cols:
conn.execute("ALTER TABLE members ADD COLUMN loomio_opt_out INTEGER NOT NULL DEFAULT 0")
# Migration: account_type — 'member' (default) or 'guest'. Guest accounts are
# provisioned by /admin/provision-guest with $2 of non-expiring credit, live
# in the Cloudron "guests" group, and sit outside every membership
@@ -1940,6 +1950,45 @@ def mark_loomio_invited(email: str) -> None:
conn.close()
def clear_loomio_invited(email: str) -> bool:
"""Forget the invite stamp for a member who is no longer in the group.
Only the reconcile step calls this, and only for a member who is STILL ACTIVE
but absent from the live roster: their membership was revoked (a lapse that
was later reversed) or they deleted their Loomio account. "Invited once,
ever" must not mean "locked out forever". Opted-out members are never
cleared (they left on purpose). Returns True when a stamp was cleared.
"""
conn = get_db()
cur = conn.execute(
"UPDATE members SET loomio_invited_at = NULL "
"WHERE email = ? AND loomio_invited_at IS NOT NULL AND loomio_opt_out = 0",
(email,),
)
conn.commit()
cleared = cur.rowcount > 0
conn.close()
return cleared
def loomio_opted_out(email: str) -> bool:
"""True when the member deliberately left Loomio and must not be re-invited."""
conn = get_db()
row = conn.execute(
"SELECT loomio_opt_out FROM members WHERE email = ?", (email,)
).fetchone()
conn.close()
return bool(row and row[0])
def _loomio_slug_for_email(email: str) -> str:
"""The member's portal slug (e.g. "matt-h"), used as a username fallback."""
conn = get_db()
row = conn.execute("SELECT slug FROM members WHERE email = ?", (email,)).fetchone()
conn.close()
return (row[0] or "") if row else ""
def get_member_matrix_mxid(email: str) -> str:
"""Return the member's optional extra Matrix MXID, or "" if unset."""
conn = get_db()
@@ -2098,6 +2147,33 @@ def _loomio_is_autogenerated(current: str, email: str) -> bool:
return bool(local) and cur.startswith(local) and len(cur) > len(local)
def _loomio_username_candidates(u: dict, target: str) -> list[str]:
"""Usernames to try, in order, when a rename target is already taken.
Loomio handles are unique per INSTANCE, not per group, so a target derived
from the Cloudron username or the email local part can collide with a handle
someone else already holds. Two structural collisions we have seen:
* a plain Cloudron username — "matt" was already held by another member;
* Open Collective aliases — every OC member's email starts
"opencollective@", so the local part resolves to "opencollective" and
collides with whichever OC member took it first.
Fall back to the member's portal slug (name-based, e.g. "matt-h"), then to
numbered suffixes, so nobody is left carrying an autogenerated handle.
"""
out: list[str] = []
def add(raw) -> None:
v = _loomio_safe_username(raw)
if v and v != (u.get("username") or "") and v not in out:
out.append(v)
add(target)
add(_loomio_slug_for_email(u.get("email") or ""))
for n in range(2, 10):
add(f"{target}-{n}")
return out
async def loomio_fix_usernames(client: httpx.AsyncClient) -> dict:
"""Rename Loomio users with auto-generated handles to their Cloudron username.
@@ -2132,16 +2208,29 @@ async def loomio_fix_usernames(client: httpx.AsyncClient) -> dict:
if not target or u.get("username") == target:
skipped += 1
continue
renamed = None
hard_failure = False
for cand in _loomio_username_candidates(u, target):
rr = await client.patch(
f"{LOOMIO_BASE}/api/b3/users/{u['id']}",
headers=H, json={"username": target},
headers=H, json={"username": cand},
)
if rr.status_code == 200:
fixed += 1
else:
# log the Loomio user id, never the member's email
renamed = cand
break
if rr.status_code != 422 or "already been taken" not in (rr.text or ""):
# Not a collision — log the Loomio user id, never the email.
logger.warning("Loomio username fix for user %s failed: %s %s",
u.get("id"), rr.status_code, rr.text[:120])
hard_failure = True
break
if renamed:
fixed += 1
elif not hard_failure:
logger.warning(
"Loomio username fix for user %s: every candidate is taken",
u.get("id"),
)
if fixed:
logger.info("Loomio usernames fixed: %s", fixed)
return {"fixed": fixed, "skipped": skipped}
@@ -2196,6 +2285,13 @@ async def sync_matrix_space() -> dict:
super().__init__(f"retry_after_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:
try:
r = await client.post(
@@ -2204,14 +2300,16 @@ async def sync_matrix_space() -> dict:
)
except httpx.HTTPError as exc:
# A transport failure (read timeout, connection reset) belongs to
# ONE member/room, not to the sync. Synapse federates some invites
# and can exceed the read timeout. Swallow it, log it, let the next
# pass retry: raising here aborted the whole pass and silently
# skipped every member after this one, which is how a new member
# sat uninvited for a day.
# ONE member, not to the sync. Synapse federates some invites and
# can exceed the read timeout. Raise a member-scoped error so the
# caller can skip this member's REMAINING rooms: a remote homeserver
# that cannot be reached hangs every room until the client timeout
# (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",
mxid, room, type(exc).__name__)
return False
raise _TransportError(type(exc).__name__) from exc
if r.status_code == 200:
return True
if r.status_code == 429:
@@ -2230,6 +2328,7 @@ async def sync_matrix_space() -> dict:
rooms = member_invite_rooms()
invited_count = 0
rate_limited = False
transport_skipped = 0
async with httpx.AsyncClient(timeout=30) as client:
# Snapshot EVERY room's membership once, up front: who is joined and who
@@ -2290,6 +2389,18 @@ async def sync_matrix_space() -> dict:
sent_any = True
if sent_any:
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:
rate_limited = True
logger.info(
@@ -2377,7 +2488,8 @@ async def sync_matrix_space() -> dict:
local_mxid, room, type(exc).__name__)
if 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):
@@ -2573,6 +2685,43 @@ async def sync_loomio_memberships() -> None:
if healed:
logger.info("Loomio sync: stamped %d already-present member(s) as invited", healed)
# --- RECONCILE STAMPS: a stamp must not outlive the membership. ---
# Invite candidates are computed BEFORE this step on purpose: a stamp
# cleared here does NOT become an invite in the same pass. The member
# becomes eligible on the next pass, after a second confirming roster
# read — the one-pass delay is what keeps a single stale/shifted page
# from turning into an invite.
fresh = [
e for e in invite_emails
if e.lower() not in current and not get_loomio_invited_at(e)
]
# An ACTIVE member stamped as invited but absent from the live roster is
# NOT "already invited" in reality: their membership was revoked (e.g. a
# lapse that was later reversed) or they deleted their Loomio account.
# Clear the stamp so the NEXT pass may invite them again. The invite is
# deliberately deferred by one pass: the stamp is only cleared on direct
# roster evidence, and the invite itself waits for a second confirming
# read rather than acting on a single possibly-stale page.
missing = [
e for e in invite_emails
if e.lower() not in current
and get_loomio_invited_at(e)
and not loomio_opted_out(e)
]
if len(missing) > LOOMIO_RECONCILE_MAX:
# A short/truncated roster read must never become a mass re-invite.
logger.warning(
"Loomio sync: %d stamped-but-absent member(s) exceeds the "
"reconcile cap (%d); leaving stamps alone (possible roster read "
"problem)", len(missing), LOOMIO_RECONCILE_MAX,
)
elif missing:
cleared = sum(1 for e in missing if clear_loomio_invited(e))
logger.info(
"Loomio sync: cleared invite stamp for %d member(s) missing "
"from the group; they become eligible on the next pass", cleared,
)
# --- REMOVE: reconcile the group to the current active set. ---
removed = 0
for email, mid in current.items():
@@ -2585,10 +2734,6 @@ async def sync_loomio_memberships() -> None:
logger.info("Loomio sync: %d lapsed membership(s) removed", removed)
# --- ADD: only addresses Loomio has never seen AND we never handed over. ---
fresh = [
e for e in invite_emails
if e.lower() not in current and not get_loomio_invited_at(e)
]
if not fresh:
logger.info(
"Loomio sync: nobody new (all already in Loomio or already "
@@ -2609,13 +2754,23 @@ async def sync_loomio_memberships() -> None:
logger.warning("Loomio membership sync failed: %s %s", r.status_code, r.text[:200])
else:
added = r.json().get("added_emails", []) or []
# Record EVERY address we sent, so it is never sent again — even
# if Loomio didn't add it, or the membership is later revoked. A
# revoked member is NOT a never-invited member, and must not be
# re-invited.
added_lc = {a.lower() for a in added}
# Stamp ONLY the addresses Loomio actually added. An address the
# API accepted in the payload but did not turn into a membership
# (undeliverable address, deactivated target, silent skip) was NOT
# invited, so it must stay eligible for the next pass. Stamping
# the whole payload is how a member ended up recorded as invited
# with no membership — and therefore never invited again.
for e in fresh:
if e.lower() in added_lc:
mark_loomio_invited(e)
logger.info("Loomio sync: first-time invites sent (%d): %s", len(added), added)
not_added = [e for e in fresh if e.lower() not in added_lc]
if not_added:
logger.warning(
"Loomio sync: %d address(es) were not added by Loomio; "
"left unstamped for the next pass", len(not_added),
)
# Fix auto-generated usernames (email+randomsuffix) → Cloudron username.
# Best-effort: no B3 key or an API failure just logs and moves on.
@@ -7951,25 +8106,31 @@ def cycle_start_for_anchor_day(anchor_day: int, now: datetime | None = None) ->
async def fetch_member_orders() -> dict[str, list[dict]]:
"""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
per member. Raises on failure so the caller can skip rather than mis-decide.
Paginated read for the whole collective (OC's own totalCount decides when
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:
raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch orders")
query = (
'{ collective(slug: "%s") { orders(limit: 200) { totalCount nodes { '
per_page = 100
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 "
"fromAccount { slug } amount { value currency } totalAmount { value currency } } } } }"
% OC_COLLECTIVE_SLUG
)
by_slug: dict[str, list[dict]] = {}
seen = 0
total = None
async with httpx.AsyncClient(timeout=30.0) as client:
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},
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}")
@@ -7977,11 +8138,23 @@ async def fetch_member_orders() -> dict[str, list[dict]]:
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]] = {}
for o in orders.get("nodes") 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
@@ -8750,27 +8923,45 @@ async def fetch_oc_monthly_order_charges() -> list[dict]:
"""
if not OC_PERSONAL_TOKEN:
raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch order charges")
query = (
'{ collective(slug: "%s") { orders(limit: 200) { totalCount nodes { '
# Paginate: a fixed limit silently dropped the OLDEST orders once the
# 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 } "
"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:
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},
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}")
body = r.json()
if body.get("errors"):
raise RuntimeError(f"OC order-charge fetch errors: {str(body['errors'])[:200]}")
nodes = (((body.get("data") or {}).get("collective") or {}).get("orders") or {}).get("nodes") or []
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] = []
for o in nodes:
if (o.get("frequency") or "").upper() != "MONTHLY":
+86 -10
View File
@@ -51,6 +51,7 @@ deletes = [] # every b3 membership DELETE url
ROSTER = {} # email -> membership id currently in the group
GET_FAILS = False # exercise fail-closed
DELETE_STATUS = 200 # toggle to prove 404 tolerance
ADDED_OMIT = set() # emails the fake Loomio accepts but does NOT add
class FakeResp:
@@ -88,7 +89,8 @@ class FakeClient:
async def post(self, url, headers=None, json=None):
posts.append({"url": url, "json": json or {}})
return FakeResp(200, {"added_emails": (json or {}).get("emails", [])})
sent = (json or {}).get("emails", [])
return FakeResp(200, {"added_emails": [e for e in sent if e not in ADDED_OMIT]})
async def delete(self, url, headers=None):
deletes.append(url)
@@ -119,7 +121,7 @@ def check(name, ok):
async def main():
global GET_FAILS, ROSTER, DELETE_STATUS
global GET_FAILS, ROSTER, DELETE_STATUS, ADDED_OMIT
m.get_db().close() # create + migrate the fixture schema
conn = m.get_db()
for e in ("new@x.org", "old@x.org", "member@x.org"):
@@ -130,6 +132,7 @@ async def main():
cols = [r[1] for r in m.get_db().execute("PRAGMA table_info(members)").fetchall()]
m.get_db().close()
check("migration: members.loomio_invited_at exists", "loomio_invited_at" in cols)
check("migration: members.loomio_opt_out exists", "loomio_opt_out" in cols)
m.get_active_member_emails = fake_active
m.filter_loomio_activated = fake_activated
@@ -156,17 +159,30 @@ async def main():
check("add: remove_absent is NEVER sent (no re-add path)", "remove_absent" not in body)
check("add: the newly-invited address is recorded",
m.get_loomio_invited_at("new@x.org") is not None)
check("reconcile: a stamped-but-absent member's stamp is cleared (not yet re-invited)",
m.get_loomio_invited_at("old@x.org") is None)
check("add: nothing removed when nobody has lapsed", deletes == [])
# --- 2. Second run adds nobody again. ---
# --- 2. Second run: the cleared member is invited once, then recorded. ---
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99} # Loomio now has new@
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
body = posts[0]["json"] if posts else {}
check("reconcile: the cleared member is re-invited on the next pass",
body.get("emails") == ["old@x.org"])
check("reconcile: the re-invite is recorded", m.get_loomio_invited_at("old@x.org") is not None)
check("reconcile: a present member is never re-invited",
"member@x.org" not in (body.get("emails") or []))
# --- 2b. Third run: nothing left to invite. ---
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "old@x.org": 88}
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("double-run: no second invite", posts == [])
check("double-run: no removals", deletes == [])
# --- 3. REMOVE path: a lapsed member is removed exactly once. ---
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "lapsed@x.org": 77}
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "old@x.org": 88, "lapsed@x.org": 77}
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("remove: the lapsed member is removed exactly once",
@@ -180,7 +196,7 @@ async def main():
all("keep@x.org" not in (p["json"].get("emails") or []) for p in posts))
# --- 4. Second run after the removal changes nothing. ---
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99} # lapsed gone
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "old@x.org": 88} # lapsed gone
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("remove double-run: nothing removed again", deletes == [])
@@ -188,7 +204,7 @@ async def main():
# --- 5. A re-run against a STALE roster (member already gone) must not error:
# Loomio answers 404 for an absent membership, which is success. ---
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "lapsed@x.org": 77}
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "old@x.org": 88, "lapsed@x.org": 77}
DELETE_STATUS = 404
posts.clear(); deletes.clear()
err = None
@@ -201,7 +217,7 @@ async def main():
DELETE_STATUS = 200
# --- 6. FAIL CLOSED: an unreadable roster stops BOTH phases. ---
ROSTER = {"lapsed@x.org": 77}
ROSTER = {"lapsed@x.org": 77, "old@x.org": 88}
GET_FAILS = True
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
@@ -218,10 +234,10 @@ async def main():
m.LOOMIO_SYNC_ENABLED = True
# --- 8. Recording is idempotent — an existing timestamp is never overwritten. ---
first = m.get_loomio_invited_at("old@x.org")
m.mark_loomio_invited("old@x.org")
first = m.get_loomio_invited_at("member@x.org")
m.mark_loomio_invited("member@x.org")
check("mark_loomio_invited never overwrites an existing timestamp",
m.get_loomio_invited_at("old@x.org") == first)
m.get_loomio_invited_at("member@x.org") == first)
# --- 9. remove_loomio_membership status handling (200/204/404 ok, 500 not). ---
async with FakeClient() as c:
@@ -231,6 +247,66 @@ async def main():
check("remove_loomio_membership: 500 is a failure", not await m.remove_loomio_membership(c, 1))
DELETE_STATUS = 200
# --- 10. OPT-OUT: a member who deliberately left is never re-invited. ---
conn = m.get_db()
conn.execute("INSERT OR REPLACE INTO members (email, active, loomio_opt_out) VALUES (?, 1, 1)",
("left@x.org",))
conn.commit()
conn.close()
m.mark_loomio_invited("left@x.org")
async def active_with_left():
return ["member@x.org", "left@x.org"]
m.get_active_member_emails = active_with_left
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("opt-out: a member who left is not re-invited", posts == [])
check("opt-out: their stamp is left intact", m.get_loomio_invited_at("left@x.org") is not None)
# --- 11. RECONCILE CAP: many stamped-but-absent members mean a bad roster
# read, not a mass re-invite. Nothing is cleared. ---
many = [f"miss{n}@x.org" for n in range(1, m.LOOMIO_RECONCILE_MAX + 2)]
conn = m.get_db()
for e in many:
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", (e,))
conn.commit()
conn.close()
for e in many:
m.mark_loomio_invited(e)
async def active_with_many():
return ["member@x.org"] + many
m.get_active_member_emails = active_with_many
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("cap: an over-cap stamp reconciliation sends no invites", posts == [])
check("cap: stamps are untouched when the cap is exceeded",
all(m.get_loomio_invited_at(e) is not None for e in many))
# --- 12. NOT ADDED: if Loomio accepts the payload but adds nothing for an
# address, it must stay unstamped and eligible. ---
conn = m.get_db()
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", ("lost@x.org",))
conn.commit()
conn.close()
async def active_with_lost():
return ["member@x.org", "lost@x.org"]
m.get_active_member_emails = active_with_lost
ADDED_OMIT = {"lost@x.org"}
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("not-added: the address is sent", posts and posts[0]["json"]["emails"] == ["lost@x.org"])
check("not-added: an address Loomio did not add stays unstamped",
m.get_loomio_invited_at("lost@x.org") is None)
ADDED_OMIT = set()
asyncio.run(main())
fails = sum(not ok for _, ok in results)
+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env python3
"""Regression test: Loomio handle collisions are resolved, not left mangled.
WHY THIS EXISTS
Loomio usernames are unique per INSTANCE, not per group. The rename pass
derives a target from the Cloudron username (the OAuth uid) or, before first
SSO login, from the email local part. Both can collide with a handle someone
else already holds:
* a plain Cloudron username — "matt" is held by another member;
* Open Collective aliases — every OC member's address starts
"opencollective@", so the local part resolves to "opencollective" and
collides with whichever OC member took it first.
A 422 "username has already been taken" must fall back to the member's portal
slug (name-based, e.g. "matt-h"), never leave the member on an autogenerated
handle.
Runnable: python3 tests/test_loomio_usernames.py (from the repo root)
"""
import os
import sys
import tempfile
import asyncio
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
os.environ["LOOMIO_API_KEY"] = "test-user-key"
os.environ["LOOMIO_B3_KEY"] = "test-server-key"
os.environ["LOOMIO_GROUP_ID"] = "1"
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"]
TAKEN = {"matt", "opencollective"}
class FakeResp:
def __init__(self, status=200, payload=None):
self.status_code = status
self._payload = payload or {}
self.text = str(payload or {})
def raise_for_status(self):
if self.status_code >= 400:
raise RuntimeError(f"HTTP {self.status_code}")
def json(self):
return self._payload
USERS = [
{"id": 300, "username": "matthiehnouk8f", "email": "matt@mattharwood.com",
"identities": [{"identity_type": "oauth", "uid": "matt"}]},
{"id": 313, "username": "opencollectivewbvgr", "email": "opencollective@jeremiahlee.com",
"identities": []},
{"id": 9, "username": "joshuaztanxk2", "email": "joshua.z.tan@example.org",
"identities": [{"identity_type": "oauth", "uid": "joshua.z.tan"}]},
{"id": 5, "username": "amarino", "email": "amarino@solo.ist",
"identities": [{"identity_type": "oauth", "uid": "amarino"}]},
]
class FakeClient:
def __init__(self, *a, **k):
self.patches = []
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
async def get(self, url, headers=None, params=None):
return FakeResp(200, {"users": USERS})
async def patch(self, url, headers=None, json=None):
uid = int(url.rsplit("/", 1)[-1])
name = (json or {}).get("username")
self.patches.append((uid, name))
if name in TAKEN:
return FakeResp(422, {"errors": {"username": ["has already been taken"]}})
return FakeResp(200, {"user": {"id": uid, "username": name}})
results = []
def check(name, ok):
results.append((name, ok))
async def main():
conn = m.get_db() # create + migrate
for email, slug in (
("matt@mattharwood.com", "matt-h"),
("opencollective@jeremiahlee.com", "jeremiah-lee"),
("joshua.z.tan@example.org", "joshua-z-tan"),
("amarino@solo.ist", "amarino"),
):
conn.execute("INSERT OR REPLACE INTO members (email, slug) VALUES (?, ?)", (email, slug))
conn.commit()
conn.close()
client = FakeClient()
out = await m.loomio_fix_usernames(client)
by_uid = {}
for uid, name in client.patches:
by_uid.setdefault(uid, []).append(name)
# Matt Harwood: Cloudron uid "matt" is taken -> portal slug "matt-h".
check("collision: the taken Cloudron username is tried first",
by_uid.get(300, [])[0] == "matt")
check("collision: falls back to the portal slug",
by_uid.get(300) == ["matt", "matt-h"])
# Jeremiah Lee: OC alias local part "opencollective" is taken -> slug.
check("collision: an OC alias local part is tried first",
by_uid.get(313, [])[0] == "opencollective")
check("collision: an OC alias collision falls back to the slug",
by_uid.get(313) == ["opencollective", "jeremiah-lee"])
# Joshua Tan: a dot-containing uid is sanitized, not passed through.
check("sanitize: a dotted uid becomes a legal handle",
by_uid.get(9) == ["joshua_z_tan"])
# A human-chosen handle is out of scope and never renamed.
check("skip: a hand-chosen handle is never renamed", 5 not in by_uid)
check("summary: three handled, one skipped",
out == {"fixed": 3, "skipped": 1})
# No patch ever sends an illegal character.
check("sanitize: every attempted handle is Loomio-legal",
all(n and n == m._loomio_safe_username(n) for _, names in by_uid.items() for n in names))
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)
+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)
INVITE_429_FOR = set() # mxids whose invite comes back 429
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
ROSTER = {} # Loomio roster: email -> membership id
@@ -129,6 +130,7 @@ class FakeClient:
if "/invite" in url:
mxid = (json or {}).get("user_id")
if mxid in INVITE_TIMEOUT_FOR:
TIMEOUT_ATTEMPTS.append((url, mxid))
raise httpx.ReadTimeout("timed out")
if mxid in INVITE_429_FOR:
return FakeResp(429, {"retry_after_ms": 300000},
@@ -165,6 +167,7 @@ def reset():
global invites_sent
invites_sent = []
POSTS.clear()
TIMEOUT_ATTEMPTS.clear()
async def main():
@@ -209,8 +212,8 @@ async def main():
not any(mx == "@amember:inference.coop" for _, mx in invites_sent))
check("per-room: two members can be pending on different rooms",
not any(mx == "@cmember:inference.coop" for _, mx in invites_sent))
check("return shape: the result carries invited + rate_limited",
set(r) == {"invited", "rate_limited"} and r["rate_limited"] is False)
check("return shape: the result carries invited + rate_limited + transport_skipped",
set(r) == {"invited", "rate_limited", "transport_skipped"} and r["rate_limited"] is False)
# --- 2. IDEMPOTENCE: a second pass sends nothing ----------------------
reset()
@@ -325,6 +328,10 @@ async def main():
{room for room, _ in invites_sent} == set(ROOMS)
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: 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).
INVITE_TIMEOUT_FOR = set()