diff --git a/docs/bridge.md b/docs/bridge.md index fbc2ebb..a9d668c 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -319,11 +319,11 @@ A send is one `PUT /rooms/{room}/send/m.room.message/{request_id}`: the request | --- | --- | --- | | `gamecult.persona.chat_send_request.v1` | `[request_id, persona, room_alias, text]` | `chat_send_receipt.v1` `[request_id, event_id, refusal]` | | `gamecult.persona.chat_send_request.v2` | the v1 tuple, then `basis`: nil or `[seen_event_id or nil, since_unix_ms]` | `chat_send_receipt.v2` `[request_id, event_id, refusal, newer]` | -| `gamecult.persona.chat_send_request.v3` | the v2 tuple, then `resend`: a boolean | `chat_send_receipt.v2` | +| `gamecult.persona.chat_send_request.v3` | the v2 tuple, then `resend`: a boolean | `chat_send_receipt.v2`, whose refusal may be `RoomMoved` or `ResendUnknown` | A v2 or v3 send with a `basis` is checked inside the room gate: if messages that move the room are newer than what she saw, the mouth makes no PUT and answers `RoomMoved` with their ids (`newer`, oldest first, at most 50). -**`resend`** is true when the request repeats an earlier send by the same caller under the same `request_id`, for instance after `SendFailed` (the mouth's 10 s send timeout fires although the homeserver may still persist the event). The mouth then skips the basis check, because her decision was made against the original basis, and PUTs under the same transaction id. The homeserver's answer is the receipt: the original event id if the first try posted, a new one if it did not. Everything else is checked as for any send: `PersonaMismatch`, `Brake`, `EmptyText`, `UnknownRoom`, the room gate. A `resend` carries no new basis meaning: the field stays in the tuple, nil or not, and is ignored. A request that does not repeat an earlier send must send `resend` false, and a retry that does not say it is a resend is checked as a new send and may be answered `RoomMoved`. Golden bytes: `tests/fixtures/persona-chat-v2/` (`chat_send_request.v3.first-try`, `.resend`). +**`resend`** is true when the request repeats an earlier send by the same caller under the same `request_id`, for instance after `SendFailed` (the mouth's 10 s send timeout fires although the homeserver may still persist the event). The mouth honours it only for a request id it attempted itself (the id, the room and the time of the first PUT attempt, in memory, at most 500 per Persona, the oldest forgotten first), for the same Persona and room, less than 25 minutes after that first attempt (inside Synapse's 30 minute minimum txn dedupe window; a repeat does not renew it). It then skips the basis check, because her decision was made against the original basis, and PUTs under the same transaction id. The homeserver's answer is the receipt: the original event id if the first try posted, a new one if it did not. Every other resend is answered `ResendUnknown` (v2 receipt only) and posts nothing: the mouth cannot vouch for the earlier send, because it does not remember the id, the id is older than 25 minutes, it was attempted for another room, or the mouth restarted since. The caller must treat the line as not known to have gone out. `PersonaMismatch`, `Brake`, `EmptyText`, `UnknownRoom` and the room gate apply as for any send. `basis` stays in the tuple for shape uniformity and is ignored on a resend. A request that does not repeat an earlier send must send `resend` false, and a retry that does not say it is a resend is checked as a new send and may be answered `RoomMoved`. Golden bytes: `tests/fixtures/persona-chat-v2/` (`chat_send_request.v3.first-try`, `.resend`). ### Fetch a named file (`chat_fetch_request.v1`, `chat_fetch_receipt.v1`) diff --git a/tests/persona-matrix-mouth-runtime.test.mjs b/tests/persona-matrix-mouth-runtime.test.mjs index c1c8d15..199122d 100644 --- a/tests/persona-matrix-mouth-runtime.test.mjs +++ b/tests/persona-matrix-mouth-runtime.test.mjs @@ -389,6 +389,8 @@ test("RoomMoved is v2 only, and the v2 documents are strict about arity and newe assert.throws(() => docs.sendReceiptTuple({ requestId: "r", refusal: "RoomMoved" }), /unknown refusal/, "the v1 receipt cannot carry RoomMoved"); assert.throws(() => docs.parseSendReceipt(["r", null, "RoomMoved"]), /unknown refusal/); assert.throws(() => docs.refusalTuple({ persona: "p", refusal: "RoomMoved" })); + assert.deepEqual(docs.parseSendReceiptV2(docs.sendReceiptV2Tuple({ requestId: "r", refusal: "ResendUnknown" })), { requestId: "r", eventId: null, refusal: "ResendUnknown", newer: [] }); + assert.throws(() => docs.sendReceiptTuple({ requestId: "r", refusal: "ResendUnknown" }), /unknown refusal/, "v2 only, like RoomMoved"); assert.throws(() => docs.sendReceiptV2Tuple({ requestId: "r", refusal: "RoomMoved" }), /newer/, "RoomMoved names what moved the room"); assert.throws(() => docs.sendReceiptV2Tuple({ requestId: "r", eventId: "$e", newer: ["$x"] }), /newer/, "a sent receipt names nothing"); assert.throws(() => docs.sendReceiptV2Tuple({ requestId: "r", refusal: "RoomMoved", newer: Array.from({ length: 51 }, (_, i) => `$${i}`) }), /50/); diff --git a/tests/persona-matrix-mouth-send-gate.test.mjs b/tests/persona-matrix-mouth-send-gate.test.mjs index e01b31c..c30ca9b 100644 --- a/tests/persona-matrix-mouth-send-gate.test.mjs +++ b/tests/persona-matrix-mouth-send-gate.test.mjs @@ -10,6 +10,7 @@ import { resolve } from "node:path"; import { createMouth, createRoomGate, movesRoom } from "../tools/persona-matrix-mouth.mjs"; const HS = "gamecult.org"; +const ROOM2 = "!second-room-for-resend-tests"; const ROOM = "!0pZn8mTZ0FdY5-G99iOuD7JWWlF3yA_5p20yO1C8WeA"; const ALIAS = `#swarm:${HS}`; const captured = JSON.parse(readFileSync(resolve(import.meta.dirname, "fixtures", "persona-chat-v2", "messages-swarm-2026-11-03.json"), "utf8")); @@ -26,7 +27,7 @@ const edit = synthetic("replace", t0 + 20, `@aqua:${HS}`, { msgtype: "m.text", b const notice = synthetic("notice", t0 + 30, `@root-watch:${HS}`, { msgtype: "m.notice", body: "sudo audit line" }); // users: bearer token -> user id. events: the room's history, oldest first. hooks.delay(kind) -> ms to hold a GET /messages or a PUT. -async function homeserver({ events = swarm, users, headStatus = 200, headHangs = false, delay = () => 0 } = {}) { +async function homeserver({ events = swarm, users, headStatus = 200, headHangs = false, delay = () => 0, failPut = () => false } = {}) { const room = [...events]; const seen = []; const sent = new Map(); @@ -41,9 +42,9 @@ async function homeserver({ events = swarm, users, headStatus = 200, headHangs = const record = { method: req.method, path, body: raw ? JSON.parse(raw) : null, who: users[bearer], query: url.searchParams }; seen.push(record); if (path === "/account/whoami") return reply(200, { user_id: users[bearer] }); - if (path === "/joined_rooms") return reply(200, { joined_rooms: [ROOM] }); + if (path === "/joined_rooms") return reply(200, { joined_rooms: [ROOM, ROOM2] }); if (path.includes("/account_data/m.direct")) return reply(404, { errcode: "M_NOT_FOUND", error: "Account data not found" }); - if (path.startsWith("/directory/room/")) return reply(200, { room_id: ROOM, servers: [HS] }); + if (path.startsWith("/directory/room/")) return reply(200, { room_id: path.includes("other") ? ROOM2 : ROOM, servers: [HS] }); if (req.method === "GET" && path === `/rooms/${ROOM}/messages`) { if (headHangs) return; // never answers await new Promise(r => setTimeout(r, delay("get"))); @@ -55,6 +56,7 @@ async function homeserver({ events = swarm, users, headStatus = 200, headHangs = const put = path.match(/^\/rooms\/(.+)\/send\/m\.room\.message\/(.+)$/); if (req.method === "PUT" && put) { await new Promise(r => setTimeout(r, delay("put"))); + if (failPut()) return reply(500, { errcode: "M_UNKNOWN", error: "Internal server error" }); if (!sent.has(put[2])) { sent.set(put[2], `$sent-${sent.size + 1}`); room.push({ type: "m.room.message", event_id: sent.get(put[2]), sender: users[bearer], origin_server_ts: t0 + 1000 + sent.size, content: record.body }); @@ -224,49 +226,98 @@ test("a send queued at the gate re-checks the brake before its PUT: braked durin } finally { await hs.close(); } }); -// A resend (v3): the first try answered SendFailed or never arrived, and the room moved before the repeat. -const slowPut = { ms: 250 }; +// A resend (v3): the first try answered SendFailed or never arrived, and the room moved before the repeat. The mouth vouches for a +// resend only for a request id it attempted itself, for that Persona and room, less than 25 minutes ago. +const ALIAS2 = `#other:${HS}`; +const MIN = 60_000; +const T0 = 1_800_000_000_000; const current = () => basisOn(swarm.at(-1)); // nothing newer when the first try is made const someoneAnswers = hs => hs.room.push({ type: "m.room.message", event_id: "$after-first-try", sender: `@nibu:${HS}`, origin_server_ts: t0 + 5000, content: { msgtype: "m.text", body: "answered her line" } }); -const resend = (m, requestId, basis) => m.send({ requestId, persona: "eureka", roomAlias: ALIAS, text: `line ${requestId}`, basis, resend: true }); +const clock = { t: T0 }; +const timed = (hs, persona, token, extra = {}) => mouth(hs, persona, token, { rooms: [ALIAS, ALIAS2], now: () => clock.t, ...extra }); +const resend = (m, requestId, basis, roomAlias = ALIAS, persona = "eureka") => m.send({ requestId, persona, roomAlias, text: `line ${requestId}`, basis, resend: true }); +const unknown = r => assert.deepEqual([r.eventId, r.refusal, r.newer], [null, "ResendUnknown", []]); -test("a resend whose first try posted returns the same event id, reads no head and posts nothing new", async () => { - const hs = await homeserver({ users: { tok: EUREKA }, delay: kind => (kind === "put" ? slowPut.ms : 0) }); +test("a resend of a remembered id whose first try posted returns the same event id, reads no head and posts nothing new", async () => { + clock.t = T0; + const slow = { ms: 250 }; + const hs = await homeserver({ users: { tok: EUREKA }, delay: kind => (kind === "put" ? slow.ms : 0) }); try { - const m = mouth(hs, "eureka", "tok", { sendTimeoutMs: 80 }); + const m = timed(hs, "eureka", "tok", { sendTimeoutMs: 80 }); const first = await send(m, "r20", current()); assert.deepEqual([first.eventId, first.refusal], [null, "SendFailed"], "the mouth gave up after its timeout"); await new Promise(r => setTimeout(r, 400)); // the homeserver persisted it anyway - assert.equal(hs.room.filter(e => e.sender === EUREKA && e.event_id.startsWith("$sent")).length, 1); + assert.equal(hs.room.filter(e => e.event_id.startsWith("$sent")).length, 1); someoneAnswers(hs); - slowPut.ms = 0; + slow.ms = 0; clock.t += 10 * MIN; const heads = hs.heads().length; const second = await resend(m, "r20", current()); assert.deepEqual([second.eventId, second.refusal, second.newer], ["$sent-1", null, []]); assert.equal(hs.heads().length, heads, "a resend reads no head"); assert.equal(hs.puts().at(-1).path.endsWith("/r20"), true, "under the same txn id"); assert.equal(hs.room.filter(e => e.event_id.startsWith("$sent")).length, 1, "nothing new in the room"); - } finally { slowPut.ms = 250; await hs.close(); } + } finally { await hs.close(); } }); -test("a resend whose first try never posted posts once, though the room moved", async () => { +test("a resend of a remembered id whose first try never posted posts once, though the room moved", async () => { + clock.t = T0; + const down = { on: true }; + const hs = await homeserver({ users: { tok: EUREKA }, failPut: () => down.on }); + try { + const m = timed(hs, "eureka", "tok"); + assert.equal((await send(m, "r21", current())).refusal, "SendFailed", "the homeserver errored: nothing posted"); + assert.equal(hs.room.filter(e => e.event_id.startsWith("$sent")).length, 0); + someoneAnswers(hs); + down.on = false; clock.t += 5 * MIN; + const receipt = await resend(m, "r21", current()); + assert.deepEqual([receipt.eventId, receipt.refusal], ["$sent-1", null]); + assert.equal(hs.room.filter(e => e.event_id.startsWith("$sent")).length, 1, "posted once"); + assert.equal(hs.heads().length, 1, "only the first try read a head"); + } finally { await hs.close(); } +}); + +test("a resend of an id the mouth never attempted is ResendUnknown and posts nothing", async () => { const hs = await homeserver({ users: { tok: EUREKA } }); try { - someoneAnswers(hs); - const receipt = await resend(mouth(hs, "eureka", "tok"), "r21", current()); - assert.deepEqual([receipt.eventId, receipt.refusal], ["$sent-1", null]); - assert.equal(hs.puts().length, 1); - assert.equal(hs.heads().length, 0); + unknown(await resend(timed(hs, "eureka", "tok"), "r22", current())); + assert.equal(hs.puts().length, 0); + } finally { await hs.close(); } +}); + +test("a resend 26 minutes after the first attempt is ResendUnknown; at 24 minutes it is honoured", async () => { + clock.t = T0; + const hs = await homeserver({ users: { tok: EUREKA } }); + try { + const m = timed(hs, "eureka", "tok"); + await send(m, "r23", current()); + clock.t += 24 * MIN; + assert.equal((await resend(m, "r23", current())).eventId, "$sent-1"); + clock.t += 2 * MIN; // 26 minutes after the first attempt: a repeat does not renew the window + unknown(await resend(m, "r23", current())); + assert.equal(hs.puts().length, 2, "the first try and the honoured resend; the late one posts nothing"); + } finally { await hs.close(); } +}); + +test("a resend from another Persona or for another room is ResendUnknown and posts nothing", async () => { + clock.t = T0; + const hs = await homeserver({ users: { tok: EUREKA, tok2: `@aqua:${HS}` } }); + try { + const eureka = timed(hs, "eureka", "tok"); + await send(eureka, "r24", current()); + const puts = hs.puts().length; + unknown(await resend(timed(hs, "aqua", "tok2"), "r24", current(), ALIAS, "aqua")); + unknown(await resend(eureka, "r24", current(), ALIAS2)); + assert.equal(hs.puts().length, puts); } finally { await hs.close(); } }); test("a non-resend retry under the same request id is still refused RoomMoved when the room moved", async () => { const hs = await homeserver({ users: { tok: EUREKA } }); try { - const m = mouth(hs, "eureka", "tok"); - await send(m, "r22", current()); + const m = timed(hs, "eureka", "tok"); + await send(m, "r25", current()); someoneAnswers(hs); - const receipt = await send(m, "r22", current()); + const receipt = await send(m, "r25", current()); assert.deepEqual([receipt.refusal, receipt.eventId, receipt.newer], ["RoomMoved", null, ["$after-first-try"]]); assert.equal(hs.puts().length, 1); } finally { await hs.close(); } @@ -275,10 +326,21 @@ test("a non-resend retry under the same request id is still refused RoomMoved wh test("a resend still answers PersonaMismatch, UnknownRoom and Brake as any send", async () => { const hs = await homeserver({ users: { tok: EUREKA } }); try { - const m = mouth(hs, "eureka", "tok"); - assert.equal((await m.send({ requestId: "r23", persona: "aqua", roomAlias: ALIAS, text: "x", resend: true })).refusal, "PersonaMismatch"); - assert.equal((await m.send({ requestId: "r24", persona: "eureka", roomAlias: `#nowhere:${HS}`, text: "x", resend: true })).refusal, "UnknownRoom"); - assert.equal((await mouth(hs, "eureka", "tok", { brake: async () => false }).send({ requestId: "r25", persona: "eureka", roomAlias: ALIAS, text: "x", resend: true })).refusal, "Brake"); - assert.equal(hs.puts().length, 0); + const m = timed(hs, "eureka", "tok"); + await send(m, "r26", current()); + assert.equal((await resend(m, "r26", undefined, ALIAS, "aqua")).refusal, "PersonaMismatch"); + assert.equal((await resend(m, "r26", undefined, `#nowhere:${HS}`)).refusal, "UnknownRoom"); + assert.equal((await resend(timed(hs, "eureka", "tok", { brake: async () => false }), "r26")).refusal, "Brake"); + assert.equal(hs.puts().length, 1); } finally { await hs.close(); } }); + +test("the attempt record is bounded: the oldest id is forgotten, never a newer one", async () => { + const hs = await homeserver({ users: { tok: EUREKA } }); + try { + const m = timed(hs, "eureka", "tok"); + for (let i = 0; i < 501; i++) await m.send({ requestId: `b${i}`, persona: "eureka", roomAlias: ALIAS, text: "x" }); + unknown(await resend(m, "b0", undefined)); + assert.equal((await resend(m, "b500", undefined)).refusal, null); + } finally { await hs.close(); } +}, { timeout: 60000 }); diff --git a/tools/persona-chat-documents.mjs b/tools/persona-chat-documents.mjs index fef7c47..a21efc9 100644 --- a/tools/persona-chat-documents.mjs +++ b/tools/persona-chat-documents.mjs @@ -29,8 +29,9 @@ export const kinds = Object.freeze({ export const refusals = Object.freeze(["Brake", "PersonaMismatch", "UnknownRoom", "EmptyText", "SendFailed", "UnknownPersona"]); -// RoomMoved exists only in the v2 receipt: the v1 tuple, a v1 parse and the typed refusal document do not know it. -export const refusalsV2 = Object.freeze([...refusals, "RoomMoved"]); +// RoomMoved and ResendUnknown exist only in the v2 receipt: the v1 tuple, a v1 parse and the typed refusal document do not know it. +// ResendUnknown too: a resend the mouth cannot vouch for (it does not remember the request id for that Persona and room, or it is older than the resend window); nothing was posted. +export const refusalsV2 = Object.freeze([...refusals, "RoomMoved", "ResendUnknown"]); // The typed refusal document also answers a request of a kind this mouth does not serve (no Persona is known then). const refusalDocument = Object.freeze([...refusals, "UnknownKind"]); diff --git a/tools/persona-matrix-mouth.mjs b/tools/persona-matrix-mouth.mjs index 49e78a6..17705da 100644 --- a/tools/persona-matrix-mouth.mjs +++ b/tools/persona-matrix-mouth.mjs @@ -24,7 +24,9 @@ // of the PUT. A v1 send, and a v2 send with no basis, are not checked; both still pass through the gate. // A v3 send may say resend: a repeat of an earlier send by the same caller under the same request_id. It skips the basis check // (her decision was made against the original basis) and PUTs under the same txnId; Synapse dedupes the txnId and returns the -// original event id if the first try posted, and a new one if it did not. +// original event id if the first try posted, and a new one if it did not. The mouth honours resend only for a request id it attempted +// itself, for the same Persona and room, less than RESEND_WINDOW_MS ago (inside Synapse's 30 minute txn dedupe); any other resend +// (forgotten, too old, lost in a restart, another room) is answered ResendUnknown and posts nothing. The record is memory only, bounded. // // Follow (CHAT_FOLLOW=1, default off; docs/bridge.md "Follow"): her own send in a public room (not a DM, not encrypted, not bridged) anchors the room // for 10 minutes; those who spoke there in the 10 minutes before it, and whoever it tagged or replied to, get basis "follow" on their later messages @@ -82,6 +84,8 @@ const FOLLOW_ROOM_TTL_MS = 5 * 60 * 1000; // how long a room's public verdict (n const FOLLOW_SLACK_MS = 60 * 1000; // clock disagreement tolerated between this process and the homeserver const FOLLOW_HOUR_MS = 60 * 60 * 1000; const FOLLOW_RING = 200; // recent senders kept per room +const RESEND_WINDOW_MS = 25 * 60 * 1000; // under the 30 minute minimum Synapse dedupes a txn id +const MAX_ATTEMPTS = 500; // request ids remembered per mouth; the oldest are forgotten first, which only makes a resend ResendUnknown const HEAD_PAGE = 50; // the room head a gated send reads; also the most ids a RoomMoved receipt names // The kind of an event for a delivery: an edit (m.replace) and an automated notice (m.notice) are not messages anyone is addressed by. @@ -738,6 +742,19 @@ export function createMouth({ return moved.reverse(); } + const attempts = new Map(); // request id -> { roomId, at } of the first PUT attempt, insertion order = age order + const vouches = (requestId, roomId) => { + const at = now(); + for (const [id, a] of attempts) { if (at - a.at < RESEND_WINDOW_MS) break; attempts.delete(id); } + const a = attempts.get(requestId); + return a !== undefined && a.roomId === roomId; + }; + const remember = (requestId, roomId) => { + if (attempts.has(requestId)) return; // the window runs from the first attempt + attempts.set(requestId, { roomId, at: now() }); + if (attempts.size > MAX_ATTEMPTS) attempts.delete(attempts.keys().next().value); + }; + async function send({ requestId, persona: asked, roomAlias, text, basis, resend = false }) { const refuse = (refusal, newer = []) => ({ requestId, eventId: null, refusal, newer }); if (asked !== persona) return refuse("PersonaMismatch"); @@ -748,11 +765,13 @@ export function createMouth({ const roomId = speakableRoomId(roomAlias); if (!roomId) return refuse("UnknownRoom"); const result = await gate.run(roomId, async () => { + if (resend && !vouches(requestId, roomId)) return refuse("ResendUnknown"); if (basis && !resend) { const newer = await newerThan(roomId, basis); if (newer.length > 0) return refuse("RoomMoved", newer); } if (!(await released())) return refuse("Brake"); // a brake placed during the gate wait or the head read stops this send + remember(requestId, roomId); const sent = await matrix("PUT", `/rooms/${encodeURIComponent(roomId)}/send/m.room.message/${encodeURIComponent(requestId)}`, { msgtype: "m.text", body: text }, API, AbortSignal.timeout(sendTimeoutMs)); return { requestId, eventId: sent.event_id, refusal: null, newer: [] }; });