From 618962ecfe64d203985d3a8be1c90569cb9b5318 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 04:43:34 +0100 Subject: [PATCH 1/3] Mouth: a v3 send may say resend; a resend skips the basis check and PUTs under the same txn id Co-Authored-By: Claude Opus 5.5 --- tests/persona-matrix-mouth-runtime.test.mjs | 5 ++ tests/persona-matrix-mouth-send-gate.test.mjs | 59 +++++++++++++++++++ tools/persona-chat-documents.mjs | 13 ++++ tools/persona-matrix-mouth.mjs | 14 +++-- 4 files changed, 86 insertions(+), 5 deletions(-) diff --git a/tests/persona-matrix-mouth-runtime.test.mjs b/tests/persona-matrix-mouth-runtime.test.mjs index f231758..a93df04 100644 --- a/tests/persona-matrix-mouth-runtime.test.mjs +++ b/tests/persona-matrix-mouth-runtime.test.mjs @@ -370,6 +370,8 @@ const v2Samples = { "gamecult.persona.chat_send_request.v2.nil-basis": { tuple: v2Request(null), parse: docs.parseSendRequestV2 }, "gamecult.persona.chat_send_request.v2.seen-and-since": { tuple: v2Request({ seenEventId: "$seen", sinceUnixMs: 1793698425998 }), parse: docs.parseSendRequestV2 }, "gamecult.persona.chat_send_request.v2.since-only": { tuple: v2Request({ seenEventId: null, sinceUnixMs: 1793698425998 }), parse: docs.parseSendRequestV2 }, + "gamecult.persona.chat_send_request.v3.resend": { tuple: docs.sendRequestV3Tuple({ requestId: "req-1", persona: "eureka", roomAlias: "#swarm:gamecult.org", text: "hi", basis: { seenEventId: "$seen", sinceUnixMs: 1793698425998 }, resend: true }), parse: docs.parseSendRequestV3 }, + "gamecult.persona.chat_send_request.v3.first-try": { tuple: docs.sendRequestV3Tuple({ requestId: "req-1", persona: "eureka", roomAlias: "#swarm:gamecult.org", text: "hi", basis: null }), parse: docs.parseSendRequestV3 }, "gamecult.persona.chat_send_receipt.v2.sent": { tuple: docs.sendReceiptV2Tuple({ requestId: "req-1", eventId: "$sent" }), parse: docs.parseSendReceiptV2 }, "gamecult.persona.chat_send_receipt.v2.room-moved": { tuple: docs.sendReceiptV2Tuple({ requestId: "req-1", refusal: "RoomMoved", newer: ["$a", "$b"] }), parse: docs.parseSendReceiptV2 }, }; @@ -394,6 +396,9 @@ test("RoomMoved is v2 only, and the v2 documents are strict about arity and newe assert.throws(() => docs.parseSendRequest(v2Request(null)), /4-field/, "a v2 tuple is not a v1 request"); assert.throws(() => docs.parseSendRequestV2(["r", "eureka", "#a:b", "x", [null]]), /2-field/); assert.throws(() => docs.parseSendRequestV2(["r", "eureka", "#a:b", "x", [null, -1]])); + assert.throws(() => docs.parseSendRequestV3(v2Request(null)), /6-field/, "a v2 tuple is not a v3 request"); + assert.throws(() => docs.parseSendRequestV3([...v2Request(null), "yes"]), /resend must be a boolean/); + assert.throws(() => docs.sendRequestV3Tuple({ requestId: "r", persona: "eureka", roomAlias: "#a:b", text: "x", resend: 1 }), /boolean/); }); test("the RUDP endpoint answers a v1 send with the three-field receipt and a v2 send with the four-field one", async () => { diff --git a/tests/persona-matrix-mouth-send-gate.test.mjs b/tests/persona-matrix-mouth-send-gate.test.mjs index 812c311..e01b31c 100644 --- a/tests/persona-matrix-mouth-send-gate.test.mjs +++ b/tests/persona-matrix-mouth-send-gate.test.mjs @@ -223,3 +223,62 @@ test("a send queued at the gate re-checks the brake before its PUT: braked durin assert.deepEqual(hs.puts().map(p => p.body.body), ["line g1"], "the queued send never reaches the room"); } 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 }; +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 }); + +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) }); + try { + const m = mouth(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); + someoneAnswers(hs); + slowPut.ms = 0; + 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(); } +}); + +test("a resend whose first try never posted posts once, though the room moved", 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); + } 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()); + someoneAnswers(hs); + const receipt = await send(m, "r22", current()); + assert.deepEqual([receipt.refusal, receipt.eventId, receipt.newer], ["RoomMoved", null, ["$after-first-try"]]); + assert.equal(hs.puts().length, 1); + } finally { await hs.close(); } +}); + +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); + } finally { await hs.close(); } +}); diff --git a/tools/persona-chat-documents.mjs b/tools/persona-chat-documents.mjs index afdc7f3..fef7c47 100644 --- a/tools/persona-chat-documents.mjs +++ b/tools/persona-chat-documents.mjs @@ -18,6 +18,7 @@ export const kinds = Object.freeze({ sendRequest: "gamecult.persona.chat_send_request.v1", sendReceipt: "gamecult.persona.chat_send_receipt.v1", sendRequestV2: "gamecult.persona.chat_send_request.v2", + sendRequestV3: "gamecult.persona.chat_send_request.v3", // the v2 tuple plus resend; answered with the v2 receipt sendReceiptV2: "gamecult.persona.chat_send_receipt.v2", refusal: "gamecult.persona.chat_refusal.v1", openDirectRequest: "gamecult.persona.chat_open_direct_request.v1", @@ -129,6 +130,18 @@ export function parseSendRequestV2(t) { return { requestId: text(requestId, "request_id"), persona: text(persona, "persona"), roomAlias: text(roomAlias, "room_alias"), text: body, basis: parsed }; } +// v3: the v2 send plus `resend`, true when this repeats an earlier send by the same caller under the same request_id. +// A resend is not checked against the basis (the decision was made against the original); the homeserver's answer is the receipt. +export function sendRequestV3Tuple({ resend = false, ...request }) { + if (typeof resend !== "boolean") throw new Error("chat_send_request_v3 resend must be a boolean"); + return [...sendRequestV2Tuple(request), resend]; +} +export function parseSendRequestV3(t) { + const fields = tuple(t, 6, "chat_send_request_v3"); + if (typeof fields[5] !== "boolean") throw new Error("chat_send_request_v3 resend must be a boolean"); + return { ...parseSendRequestV2(fields.slice(0, 5)), resend: fields[5] }; +} + // `newer` is the ids of the messages that moved the room, oldest first: non-empty exactly when the refusal is RoomMoved. function checkReceiptV2(eventId, refusal, newer) { if ((eventId === null) === (refusal === null)) throw new Error("a send receipt carries exactly one of event_id and refusal"); diff --git a/tools/persona-matrix-mouth.mjs b/tools/persona-matrix-mouth.mjs index 0964830..49e78a6 100644 --- a/tools/persona-matrix-mouth.mjs +++ b/tools/persona-matrix-mouth.mjs @@ -22,6 +22,9 @@ // newest room event she saw): inside the room gate, one step per room across every Persona, the mouth // reads the room's head from Matrix and answers RoomMoved, naming the messages that moved it, instead // 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. // // 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 @@ -735,7 +738,7 @@ export function createMouth({ return moved.reverse(); } - async function send({ requestId, persona: asked, roomAlias, text, basis }) { + 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"); if (!(await released())) return refuse("Brake"); @@ -745,7 +748,7 @@ export function createMouth({ const roomId = speakableRoomId(roomAlias); if (!roomId) return refuse("UnknownRoom"); const result = await gate.run(roomId, async () => { - if (basis) { + if (basis && !resend) { const newer = await newerThan(roomId, basis); if (newer.length > 0) return refuse("RoomMoved", newer); } @@ -1100,7 +1103,7 @@ export async function startChatEndpoint({ mouths, runtime, port, connectionKey, const respond = (peer, persona, kind, recordKey, tuple) => server.send(peer, "schema", msgpack.encode(cultnet.encodeCultNetMessageForWire( docs.envelope({ kind, recordKey, payload: msgpack.encode(tuple), sourceRuntimeId: runtimeId, sourceAgentId: persona, sourceRole: "bifrost-persona-matrix-mouth" }), "cultnet.schema.v0"))); const refuseUnknown = (peer, persona) => respond(peer, persona, docs.kinds.refusal, persona, docs.refusalTuple({ persona, refusal: "UnknownPersona" })); - const served = [docs.kinds.pendingRequest, docs.kinds.pendingRequestV3, ...(replyLink ? [docs.kinds.pendingRequestV4] : []), docs.kinds.ack, docs.kinds.read, docs.kinds.sendRequest, docs.kinds.sendRequestV2, docs.kinds.openDirectRequest, ...(fetchEnabled ? [docs.kinds.fetchRequest] : [])]; + const served = [docs.kinds.pendingRequest, docs.kinds.pendingRequestV3, ...(replyLink ? [docs.kinds.pendingRequestV4] : []), docs.kinds.ack, docs.kinds.read, docs.kinds.sendRequest, docs.kinds.sendRequestV2, docs.kinds.sendRequestV3, docs.kinds.openDirectRequest, ...(fetchEnabled ? [docs.kinds.fetchRequest] : [])]; const handle = async ({ peer, channelId, payload }) => { try { if (channelId !== "schema") throw new Error("chat request arrived on a foreign channel"); @@ -1141,8 +1144,9 @@ export async function startChatEndpoint({ mouths, runtime, port, connectionKey, if (!mouth) return refuseUnknown(peer, request.persona); mouth.read(request).catch(error => log(`read report failed: ${error?.message ?? error}`)); // the peer's next request does not wait on Matrix } else { - const v2 = document.schemaId === docs.kinds.sendRequestV2; - const request = v2 ? docs.parseSendRequestV2(tuple) : docs.parseSendRequest(tuple); + const v3 = document.schemaId === docs.kinds.sendRequestV3; + const v2 = v3 || document.schemaId === docs.kinds.sendRequestV2; // v3 is answered with the v2 receipt + const request = v3 ? docs.parseSendRequestV3(tuple) : v2 ? docs.parseSendRequestV2(tuple) : docs.parseSendRequest(tuple); const mouth = mouths.get(request.persona); const receipt = mouth ? await mouth.send(request) : { requestId: request.requestId, eventId: null, refusal: "UnknownPersona", newer: [] }; if (v2) respond(peer, request.persona, docs.kinds.sendReceiptV2, receipt.requestId, docs.sendReceiptV2Tuple(receipt)); -- 2.47.3 From 22274b7a32c7dd8bf688d4ca742c03df4d16389a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 04:46:31 +0100 Subject: [PATCH 2/3] Mouth: v3 send fixtures, endpoint test, send-request docs Co-Authored-By: Claude Opus 5.5 --- docs/bridge.md | 14 ++++++++++++++ ...persona.chat_send_request.v3.first-try.msgpack | 1 + ...lt.persona.chat_send_request.v3.resend.msgpack | Bin 0 -> 54 bytes tests/persona-matrix-mouth-runtime.test.mjs | 7 ++++++- 4 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 tests/fixtures/persona-chat-v2/gamecult.persona.chat_send_request.v3.first-try.msgpack create mode 100644 tests/fixtures/persona-chat-v2/gamecult.persona.chat_send_request.v3.resend.msgpack diff --git a/docs/bridge.md b/docs/bridge.md index b4cf73c..fbc2ebb 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -311,6 +311,20 @@ The intended shape: VoidBot still owns room reading, moderation judgment, archive/source retrieval, and Persona cognition. Bifrost owns Discord when Discord is being used as the Labor Platform interface or swarm transport. +### Send requests (`chat_send_request.v1`, `.v2`, `.v3`) + +A send is one `PUT /rooms/{room}/send/m.room.message/{request_id}`: the request id is the Matrix transaction id, so a repeat under the same id is idempotent at the homeserver (Synapse dedupes a transaction id per access token for at least 30 minutes and returns the original event id). + +| Kind | Tuple | Answer | +| --- | --- | --- | +| `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` | + +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`). + ### Fetch a named file (`chat_fetch_request.v1`, `chat_fetch_receipt.v1`) A Persona's Mind shell holds no Matrix token, so the mouth keeps a file for her: `chat_fetch_request.v1` is `[request_id, persona, room, event_id]`, a room (alias or id) and an event id, nothing else. The mouth reads her live membership and the room's full state, reads the event itself and takes `content.url` from it, fetches it as her (5 MiB, magic bytes decide the type), compares the file event's `info.sha256` with the hash it computed, stores the bytes in her image store, and answers `chat_fetch_receipt.v1` `[request_id, outcome, room_id, image, receipt]` with one of 14 fixed outcome words. A file with no `info.sha256` is `StoredUnverified` and gets no receipt; a present hash that is not the computed one is `HashMismatch` and stores nothing. For a stored, hash-matching file the mouth posts the contract's `org.gamecult.file_received` event (`{event_id, sha256, size}`) as her own Matrix user, once per (file, Mind): a reply in the album thread, else a plain event with an `m.reference` to the file. The Matrix sender is the Mind; no content key names her. Idempotence is read from Matrix, not kept. Bridged and encrypted rooms and other people's rooms are refused. The kind is served only with `CHAT_FETCH=1` (exactly that value); off, it is answered as any unknown kind (`UnknownKind`). One 15 s deadline owns each fetch, and one Persona may ask 30 in an hour. Each fetch writes one log line, `fetch persona=... outcome=... receipt=...`, and a failure adds a trailing ` cause=/`, on a thrown fetch failure, a store write that throws, or a receipt not proven: `Class` is the error's class name when it matches `[A-Za-z]{1,32}`, else `Error`; `status` is the HTTP status integer of a failed Matrix call, else `-`. No error-derived text (message, code, path, URL) reaches the log; the room and event ids, already shape-checked, are the only ids on the fetch line. `isFetchId` refuses a room-version-3 event id that contains `/` (standard base64), a fail-closed side: it is answered `NoAttachment`. diff --git a/tests/fixtures/persona-chat-v2/gamecult.persona.chat_send_request.v3.first-try.msgpack b/tests/fixtures/persona-chat-v2/gamecult.persona.chat_send_request.v3.first-try.msgpack new file mode 100644 index 0000000..2836e18 --- /dev/null +++ b/tests/fixtures/persona-chat-v2/gamecult.persona.chat_send_request.v3.first-try.msgpack @@ -0,0 +1 @@ +–¥req-1¦eureka³#swarm:gamecult.org¢hiÀÂ \ No newline at end of file diff --git a/tests/fixtures/persona-chat-v2/gamecult.persona.chat_send_request.v3.resend.msgpack b/tests/fixtures/persona-chat-v2/gamecult.persona.chat_send_request.v3.resend.msgpack new file mode 100644 index 0000000000000000000000000000000000000000..f37f0a35fb9757957f36a0d42f26086563c21fd0 GIT binary patch literal 54 zcmbQXv?#Su*Kk>CX;Er+;%4RI^2DNCtMtU&)a25f621JQ^hFt&la{I!r>5qeXJBAl KxZvQMzQX`>9v6=Q literal 0 HcmV?d00001 diff --git a/tests/persona-matrix-mouth-runtime.test.mjs b/tests/persona-matrix-mouth-runtime.test.mjs index a93df04..c1c8d15 100644 --- a/tests/persona-matrix-mouth-runtime.test.mjs +++ b/tests/persona-matrix-mouth-runtime.test.mjs @@ -432,8 +432,13 @@ test("the RUDP endpoint answers a v1 send with the three-field receipt and a v2 assert.equal(document.schemaId, docs.kinds.sendReceiptV2); assert.deepEqual(docs.parseSendReceiptV2(msgpack.decode(document.payload)), { requestId: "v2", eventId: null, refusal: "RoomMoved", newer: ["$a"] }); assert.deepEqual(seen.map(r => r.basis), [undefined, { seenEventId: "$s", sinceUnixMs: 5 }], "v1 reaches the mouth with no basis, v2 with hers"); - put(docs.kinds.sendRequestV2, "v2-ghost", docs.sendRequestV2Tuple({ requestId: "v2-ghost", persona: "ghost", roomAlias: "#swarm:gamecult.org", text: "x" })); + assert.deepEqual(seen.map(r => r.resend), [undefined, undefined]); + put(docs.kinds.sendRequestV3, "v3", docs.sendRequestV3Tuple({ requestId: "v3", persona: "eureka", roomAlias: "#swarm:gamecult.org", text: "again", basis: { seenEventId: "$s", sinceUnixMs: 5 }, resend: true })); document = await reply(3); + assert.equal(document.schemaId, docs.kinds.sendReceiptV2, "a v3 send is answered with the v2 receipt"); + assert.equal(seen.at(-1).resend, true, "the flag reaches the mouth"); + put(docs.kinds.sendRequestV2, "v2-ghost", docs.sendRequestV2Tuple({ requestId: "v2-ghost", persona: "ghost", roomAlias: "#swarm:gamecult.org", text: "x" })); + document = await reply(4); assert.deepEqual(docs.parseSendReceiptV2(msgpack.decode(document.payload)), { requestId: "v2-ghost", eventId: null, refusal: "UnknownPersona", newer: [] }); } finally { server.close(); -- 2.47.3 From 9c87b9540212ce15ee902a4cbe5cdb23d4c0bf3b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 04:50:59 +0100 Subject: [PATCH 3/3] Mouth: honour resend only for an id it attempted (same Persona and room, under 25 min); any other resend is ResendUnknown Co-Authored-By: Claude Opus 5.5 --- docs/bridge.md | 4 +- tests/persona-matrix-mouth-runtime.test.mjs | 2 + tests/persona-matrix-mouth-send-gate.test.mjs | 114 ++++++++++++++---- tools/persona-chat-documents.mjs | 5 +- tools/persona-matrix-mouth.mjs | 21 +++- 5 files changed, 115 insertions(+), 31 deletions(-) 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: [] }; }); -- 2.47.3