matrix sync: a transport error on one invite must not abort the pass

An httpx.ReadTimeout during an invite POST raised out of sync_matrix_space,
so every member after the timed-out one got nothing and the service-sync log
said only 'Matrix sync failed:' (httpx transport exceptions stringify to '').
One new member sat uninvited for a day that way.

- invite(): catch httpx.HTTPError per member/room, log the type, return False
- pass counts only members whose invite actually returned True
- room-membership snapshot, the retire half and the Cloudron users walk no
  longer abort on a transport error; the unreadable room/member is skipped
- service-sync now logs the exception TYPE (empty str(e) hid the cause)

Regression in tests/test_service_invites.py section 7: a timed-out member does
not stop the member after them, and the next pass retries them.
This commit is contained in:
inference-bot committed 2026-11-21 18:20:00 +00:00
1 parent d7c812ba07
commit a4b6aa5357
2 files changed
+93 -6

No files matched your search

+45 -6
View File
@@ -2197,10 +2197,21 @@ async def sync_matrix_space() -> dict:
self.wait_ms = wait_ms
async def invite(mxid: str, room: str) -> bool:
try:
r = await client.post(
f"{MATRIX_HOMESERVER}/_matrix/client/v3/rooms/{room}/invite",
headers=H, json={"user_id": mxid},
)
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.
logger.warning("Matrix invite %s -> %s transport error: %s",
mxid, room, type(exc).__name__)
return False
if r.status_code == 200:
return True
if r.status_code == 429:
@@ -2230,6 +2241,7 @@ async def sync_matrix_space() -> dict:
joined_by_room: dict[str, set[str]] = {}
invited_by_room: dict[str, set[str]] = {}
for room in rooms:
try:
r = await client.get(
f"{MATRIX_HOMESERVER}/_matrix/client/v3/rooms/{room}/joined_members",
headers=H)
@@ -2241,6 +2253,11 @@ async def sync_matrix_space() -> dict:
r2 = await client.get(
f"{MATRIX_HOMESERVER}/_matrix/client/v3/rooms/{room}/members",
headers=H, params={"membership": "invite"})
except httpx.HTTPError as exc:
logger.warning(
"Matrix sync: cannot read members of %s (%s); leaving that room alone",
room, type(exc).__name__)
continue
if r2.status_code != 200:
logger.warning(
"Matrix sync: cannot read invites of %s (%s); leaving that room alone",
@@ -2267,15 +2284,18 @@ async def sync_matrix_space() -> dict:
if not missing:
continue
try:
sent_any = False
for room in missing:
await invite(mxid, room)
if await invite(mxid, room):
sent_any = True
if sent_any:
invited_count += 1
except _RateLimited as exc:
rate_limited = True
logger.info(
"Matrix sync: rate limited (retry_after_ms=%s); ending this pass — "
"the next run resumes where this one stopped", exc.wait_ms)
break
invited_count += 1
if invited_count:
logger.info("Matrix space invites sent: %s", invited_count)
@@ -2292,11 +2312,16 @@ async def sync_matrix_space() -> dict:
page = 1
async with httpx.AsyncClient(timeout=30) as uc:
while True:
try:
r = await uc.get(
f"{CLOUDRON_API}/api/v1/users",
params={"page": page},
headers=cloudron_headers(),
)
except httpx.HTTPError as exc:
logger.warning("Matrix sync: Cloudron users lookup page %s failed (%s); stopping lookup",
page, type(exc).__name__)
break
if r.status_code != 200:
break
batch = r.json().get("users", [])
@@ -2325,6 +2350,7 @@ async def sync_matrix_space() -> dict:
# from every room we invite members to, not just Space + General.
for room in readable:
enc_room = urllib.parse.quote(room, safe="")
try:
if local_mxid in joined_by_room.get(room, set()):
await client.post(
f"{MATRIX_HOMESERVER}/_matrix/client/v3/rooms/{enc_room}/kick",
@@ -2343,6 +2369,12 @@ async def sync_matrix_space() -> dict:
)
retired += 1
logger.info("Matrix sync: revoked stale invite for local account %s (member uses %s)", local_mxid, ext_mxid)
except httpx.HTTPError as exc:
# One room's transport failure must not abort the retire
# half for every member after this one.
logger.warning(
"Matrix sync: retire %s in %s failed (%s); continuing",
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}
@@ -2362,11 +2394,16 @@ async def matrix_member_mxids(client: httpx.AsyncClient):
users: dict[str, str] = {}
page = 1
while True:
try:
r = await client.get(
f"{CLOUDRON_API}/api/v1/users",
params={"page": page},
headers=cloudron_headers(),
)
except httpx.HTTPError as exc:
logger.warning("Cloudron users lookup page %s failed (%s); using the pages read so far",
page, type(exc).__name__)
break
if r.status_code != 200:
logger.warning("Cloudron users lookup page %s failed: %s", page, r.status_code)
break
@@ -10197,13 +10234,15 @@ async def admin_service_sync(request: Request):
await sync_loomio_memberships()
result["loomio"] = "ok"
except Exception as e: # noqa: BLE001
result["loomio"] = str(e)[:200]
logger.warning("service-sync: Loomio sync failed: %s", e)
result["loomio"] = f"{type(e).__name__}: {e}"[:200]
logger.warning("service-sync: Loomio sync failed: %s: %s", type(e).__name__, e)
try:
result["matrix"] = await sync_matrix_space()
except Exception as e: # noqa: BLE001
result["matrix"] = str(e)[:200]
logger.warning("service-sync: Matrix sync failed: %s", e)
# An empty str(e) used to log "Matrix sync failed:" with no cause at
# all (httpx transport exceptions stringify to ""); name the type.
result["matrix"] = f"{type(e).__name__}: {e}"[:200]
logger.warning("service-sync: Matrix sync failed: %s: %s", type(e).__name__, e)
finally:
_service_sync_inflight = False
+48
View File
@@ -73,6 +73,7 @@ ROOM_INVITED = {} # room -> set(mxid)
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
POSTS = [] # Loomio POST payloads
ROSTER = {} # Loomio roster: email -> membership id
@@ -127,6 +128,8 @@ class FakeClient:
async def post(self, url, headers=None, json=None):
if "/invite" in url:
mxid = (json or {}).get("user_id")
if mxid in INVITE_TIMEOUT_FOR:
raise httpx.ReadTimeout("timed out")
if mxid in INVITE_429_FOR:
return FakeResp(429, {"retry_after_ms": 300000},
text='{"errcode":"M_LIMIT_EXCEEDED"}')
@@ -295,6 +298,51 @@ async def main():
m.mark_loomio_invited("e@x.org")
check("pending: empty once every member is stamped", m._service_sync_pending() == [])
# --- 7. ONE MEMBER'S TRANSPORT TIMEOUT MUST NOT KILL THE PASS ---------
# A ReadTimeout on ONE invite used to abort the whole sync: every member
# after the timed-out one silently got nothing, and the log line carried an
# empty message. Two members need invites; the FIRST times out.
global INVITE_TIMEOUT_FOR
conn = m.get_db()
for email, stamp in (("t@x.org", "2026-01-01 00:00:00"), ("u@x.org", "2026-01-01 00:00:00")):
conn.execute("INSERT OR REPLACE INTO members (email, active, loomio_invited_at) VALUES (?, 1, ?)",
(email, stamp))
conn.commit()
conn.close()
USERS["t@x.org"] = "tmember"
USERS["u@x.org"] = "umember"
async def active_with_tu():
return ["t@x.org", "u@x.org"]
m.get_active_member_emails = active_with_tu
ROOM_JOINED = {r_: set() for r_ in ROOMS}
ROOM_INVITED = {r_: set() for r_ in ROOMS}
INVITE_TIMEOUT_FOR = {"@tmember:inference.coop"}
reset()
r = await m.sync_matrix_space()
check("timeout: a transport timeout does not raise out of the pass", isinstance(r, dict))
check("timeout: the member AFTER the timed-out one is still invited",
{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)
# The next pass retries the timed-out member (invites are idempotent).
INVITE_TIMEOUT_FOR = set()
reset()
await m.sync_matrix_space()
check("timeout: the next pass sends the timed-out member's invites",
len(invites_sent) == 3 and all(mx == "@tmember:inference.coop" for _, mx in invites_sent))
# Clean up so the endpoint checks see a steady state.
conn = m.get_db()
conn.execute("DELETE FROM members WHERE email IN ('t@x.org', 'u@x.org')")
conn.commit()
conn.close()
INVITE_TIMEOUT_FOR = set()
m.get_active_member_emails = _active
ROOM_JOINED = {r_: set() for r_ in ROOMS}
ROOM_INVITED = {r_: set() for r_ in ROOMS}
asyncio.run(main())