Follow: a failed room-state read leaves the post retryable; a no verdict stays recorded

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Heimdall 2026-11-12 12:08:42 +00:00
commit 76cdf13e2a
2 changed files with 58 additions and 13 deletions

View file

@ -21,7 +21,7 @@ const msg = (id, sender, ts, content = {}) => ({ type: "m.room.message", event_i
const tagKiko = { "m.mentions": { user_ids: [KIKO] } };
// rounds: sync replies after the baseline, each { [roomId]: events }. state: room id -> state events.
function world({ rounds, state = {}, stateStatus = {}, hangState = false, baselineEvents = null, onSync = null, follow = true, rooms = [ALIAS, OTHER_ALIAS], direct } = {}) {
function world({ rounds, state = {}, stateStatus = {}, hangState = false, stateFailures = 0, baselineEvents = null, onSync = null, follow = true, rooms = [ALIAS, OTHER_ALIAS], direct } = {}) {
const seen = [];
const known = new Map();
let round = 0;
@ -37,6 +37,7 @@ function world({ rounds, state = {}, stateStatus = {}, hangState = false, baseli
if (p.startsWith("/presence/") || p.includes("/receipt/")) return reply(200, {});
const st = p.match(/^\/rooms\/([^/]+)\/state$/);
if (st && hangState) return new Promise(() => {});
if (st && stateFailures > 0) { stateFailures--; return reply(500, { errcode: "M_UNKNOWN" }); }
if (st) return stateStatus[st[1]] ? reply(stateStatus[st[1]], { errcode: "M_UNKNOWN" }) : reply(200, state[st[1]] ?? []);
if (init.method === "PUT" && p.includes("/send/m.room.message/")) return reply(200, { event_id: "$sent1" });
const ev = p.match(/^\/rooms\/([^/]+)\/event\/(.+)$/);
@ -330,3 +331,37 @@ test("follow: every pass forgets what has aged out: anchors, speakers and cap ti
await go(w, T0 + 3 * 60 * MIN);
assert.deepEqual(w.mouth.followState(), { engagements: [], spoke: [], followsGiven: 0 });
});
test("follow: a failed room-state read at send time leaves the post retryable: its echo anchors it", async () => {
const w = world({ stateFailures: 1, rounds: [{ [ROOM]: [msg("$k0", KIKO, T0 - MIN)] }, { [ROOM]: [msg("$sent1", ME, T0, { body: "hello" })] }, { [ROOM]: [msg("$x", KIKO, T0 + MIN)] }] });
await w.mouth.syncOnce(); await w.basisOfRound();
await w.mouth.send({ requestId: "r1", persona: "eureka", roomAlias: ALIAS, text: "hello" });
await tick();
assert.deepEqual(w.mouth.followState().engagements, [], "the read failed: nothing anchored yet");
await go(w, T0);
assert.equal(w.mouth.followState().engagements.length, 1, "the echo anchored it");
assert.deepEqual(await go(w, T0 + MIN), [["$x", "follow"]]);
});
test("follow: a send and its echo in flight together anchor once, and a failure of that one read leaves the echo to retry", async () => {
const w = world({ stateFailures: 1, rounds: [{ [ROOM]: [msg("$k0", KIKO, T0 - MIN)] }, { [ROOM]: [msg("$sent1", ME, T0, { body: "hello" })] }] });
await w.mouth.syncOnce(); await w.basisOfRound();
const sending = w.mouth.send({ requestId: "r1", persona: "eureka", roomAlias: ALIAS, text: "hello" });
await sending;
await w.basisOfRound(); // the echo, possibly while the send's read is still in flight
await tick();
assert.equal(w.mouth.followState().engagements.length, 1);
assert.equal(w.seen.filter(l => l.endsWith("/state")).length, 2, "one failed read, one that worked; no third");
});
test("follow: a not-public verdict is recorded: the room is not read again for each post or pass", async () => {
const w = world({ state: { [ROOM]: [{ type: "m.bridge", content: {} }] }, rounds: [
{ [ROOM]: [msg("$k0", KIKO, T0 - MIN)] }, { [ROOM]: [msg("$sent1", ME, T0)] }, { [ROOM]: [mine("$a", T0 + SEC), msg("$x", KIKO, T0 + 2 * SEC)] }, { [ROOM]: [mine("$b", T0 + 3 * SEC)] },
] });
await w.mouth.syncOnce(); await w.basisOfRound();
await w.mouth.send({ requestId: "r1", persona: "eureka", roomAlias: ALIAS, text: "hello" });
await tick();
for (const t of [0, 0, 0]) await go(w, T0 + t);
assert.equal(w.seen.filter(l => l.endsWith("/state")).length, 1);
assert.deepEqual(w.mouth.followState().engagements, []);
});

View file

@ -324,21 +324,23 @@ export function createMouth({
const spoke = new Map();
const followsGiven = new Map();
const anchored = new Set(); // event ids of her own posts already anchored: the send path and its /sync echo anchor once
const publicRooms = new Map(); // room id -> { ok, at }
const anchoring = new Map(); // event ids whose anchor is in flight: the send path and its echo never snapshot twice
const publicRooms = new Map(); // room id -> { ok, at }: the verdicts, a "no" included, so a not-public room is read once per FOLLOW_ROOM_TTL_MS, not every pass
const platformId = id => platformEvent({ sender: id });
// true or false is a verdict (kept); null is a failed read: unknown, retryable, kept nowhere.
async function publicRoom(roomId) {
if (directRooms.has(roomId)) return false;
const known = publicRooms.get(roomId);
if (known && now() - known.at < FOLLOW_ROOM_TTL_MS) return known.ok;
try {
const state = await matrix("GET", `/rooms/${encodeURIComponent(roomId)}/state`, undefined, API, AbortSignal.timeout(sendTimeoutMs));
if (!Array.isArray(state)) return false;
if (!Array.isArray(state)) return null;
const ok = !state.some(e => e?.type === "m.room.encryption" || e?.type === "m.bridge" || e?.type === "uk.half-shot.bridge");
publicRooms.set(roomId, { ok, at: now() });
return ok;
} catch (error) {
say(`follow: room ${roomId} state not read: ${error.message}`);
return false; // unknown is not public
return null; // unknown is not public, and not a verdict either
}
}
const eventAt = event => Number.isSafeInteger(event.origin_server_ts) && event.origin_server_ts >= 0 ? event.origin_server_ts : now();
@ -364,15 +366,23 @@ export function createMouth({
}
// Her post at time `at` (the send's own time, or the echo's origin time): snapshot the room. `tagged`: ids from the event's m.mentions, `replyTo` the quoted event id.
async function anchor(roomId, eventId, at, tagged = [], replyTo = null) {
if (!follow || anchored.has(eventId)) return;
anchored.add(eventId); // before the room read: the send path and its echo race, and one event anchors once
if (anchored.size > 200) anchored.delete(anchored.values().next().value);
if (!(await publicRoom(roomId))) return;
const counted = new Set((spoke.get(roomId) ?? []).filter(r => r.at >= at - FOLLOW_WINDOW_MS && r.at <= at).map(r => r.sender));
for (const id of tagged) counted.add(id);
if (typeof replyTo === "string" && replyTo !== "") { const author = await authorOf(roomId, replyTo); if (author !== null) counted.add(author); }
for (const id of [...counted]) if (!docs.isMatrixId("@", id) || id === selfId || platformId(id)) counted.delete(id);
engagements.set(roomId, { from: at, ends: at + FOLLOW_WINDOW_MS, counted });
if (!follow) return;
while (anchoring.has(eventId)) await anchoring.get(eventId).catch(() => {}); // the send and its echo meet here: the second waits, then sees whether the first succeeded
if (anchored.has(eventId)) return;
const run = (async () => {
const verdict = await publicRoom(roomId);
if (verdict === null) return; // the read failed: this post stays retryable, its echo tries again
anchored.add(eventId);
if (anchored.size > 200) anchored.delete(anchored.values().next().value);
if (!verdict) return; // a "no" stays recorded
const counted = new Set((spoke.get(roomId) ?? []).filter(r => r.at >= at - FOLLOW_WINDOW_MS && r.at <= at).map(r => r.sender));
for (const id of tagged) counted.add(id);
if (typeof replyTo === "string" && replyTo !== "") { const author = await authorOf(roomId, replyTo); if (author !== null) counted.add(author); }
for (const id of [...counted]) if (!docs.isMatrixId("@", id) || id === selfId || platformId(id)) counted.delete(id);
engagements.set(roomId, { from: at, ends: at + FOLLOW_WINDOW_MS, counted });
})();
anchoring.set(eventId, run);
try { await run; } finally { anchoring.delete(eventId); }
}
// Her own event seen in /sync (a send from another client, or the echo of a mouth send, which is then not anchored twice).
async function noteOwnPost(roomId, event) {