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).
This commit is contained in:
inference-bot committed 2026-11-22 19:45:20 +00:00
1 parent 146bfaf45e
commit ffed06d492
3 files changed
+376 -28

No files matched your search

+150 -18
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
rr = await client.patch(
f"{LOOMIO_BASE}/api/b3/users/{u['id']}",
headers=H, json={"username": target},
)
if rr.status_code == 200:
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": cand},
)
if rr.status_code == 200:
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
else:
# log the Loomio user id, never the member's email
logger.warning("Loomio username fix for user %s failed: %s %s",
u.get("id"), rr.status_code, rr.text[:120])
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}
@@ -2573,6 +2662,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 +2711,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 +2731,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:
mark_loomio_invited(e)
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.