From 8af72c84286481d78ef21da3512e70c232d7618f Mon Sep 17 00:00:00 2001 From: Heimdall Date: Wed, 11 Nov 2026 10:43:47 +0000 Subject: [PATCH] Mouth: a full read window is a tail gap; boundary and mutation-killing tests Co-Authored-By: Claude Sonnet 5.5 --- docs/bridge.md | 5 +-- tests/persona-matrix-mouth.test.mjs | 55 +++++++++++++++++++++++++++-- tools/persona-chat-documents.mjs | 5 +-- tools/persona-matrix-mouth.mjs | 18 ++++++---- 4 files changed, 70 insertions(+), 13 deletions(-) diff --git a/docs/bridge.md b/docs/bridge.md index 68534e2..a338dd1 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -241,14 +241,15 @@ The tail is **data, not instruction**. A line is what a sender typed in a room, | Cause | Where | |---|---| | The room's read failed (the homeserver refused or errored) or did not answer within 10 seconds (`sendTimeoutMs`); the room is logged and contributes no lines | the mouth | -| The room had more than 20 lines outside threads (the per-room cap), so older ones were left out | the mouth | +| The room had more than 20 lines outside threads (the per-room cap; her own lines count), so older ones were left out | the mouth | +| The read window came back full (100 raw events, before edits and thread replies are set aside), so real lines older than the window may exist and are unseen; a shorter chunk means the room's history was exhausted. A room whose history is exactly 100 events long is gapped too, since the mouth cannot tell | the mouth | | One of the room's lines was cut by the 60-line total cap (only the newest 60 over all rooms are kept) | the mouth | | A line was dropped as malformed (no event id) | the mouth | | The reply byte budget (256 KiB, deliveries first) cut the room's oldest lines, or a line would not encode and was skipped | the reply | | The mouth has not started: every configured room is a gap (DMs are not yet known) | the mouth | | The whole tail read failed: every speakable room is a gap, and the deliveries are still served | the endpoint | -A line a delivery already shows, her own lines and a room she cannot speak in change nothing here. A read the mouth kept for 15 seconds counts as a read. +A line a delivery already shows and a room she cannot speak in change nothing here; her own lines are lines like any other and count toward the caps. A read the mouth kept for 15 seconds counts as a read. Golden bytes: `tests/fixtures/persona-chat-v5/` (`chat_pending.v3.tail` carries two lines and no gap, `chat_pending.v3.tail-gaps` one line and two gap rooms; the earlier v3 samples gain an empty fourth element); Huginn pins the same bytes. diff --git a/tests/persona-matrix-mouth.test.mjs b/tests/persona-matrix-mouth.test.mjs index 7cb52a5..8d9b30f 100644 --- a/tests/persona-matrix-mouth.test.mjs +++ b/tests/persona-matrix-mouth.test.mjs @@ -1655,8 +1655,9 @@ test("tail gaps: the reply byte budget and a line that will not encode gap their assert.deepEqual(bad.tailGaps, ["#b:x"]); }); -test("tail gaps: the builder refuses a repeated room, and a pre-gap decoder is stopped by arity, as the tail was", () => { - assert.throws(() => docs.pendingV3Tuple({ persona: "eureka", deliveries: [], tailGaps: ["#a:x", "#a:x"] }), /repeats/); +test("tail gaps: the parser refuses a repeated room, and a pre-gap decoder is stopped by arity, as the tail was", () => { + assert.throws(() => docs.parsePendingV3(["eureka", [], [], ["#a:x", "#a:x"]]), /repeats/); + assert.deepEqual(docs.parsePendingV3(["eureka", [], [], ["#a:x", "#b:x"]]).tailGaps, ["#a:x", "#b:x"]); assert.throws(() => docs.parsePendingV3(["eureka", [], []]), /4-field/); assert.throws(() => docs.parsePendingV3(["eureka", [], [], "#a:x"]), /list/); }); @@ -1666,3 +1667,53 @@ test("tail gaps: a line the mouth drops as malformed (no event id) gaps its room assert.deepEqual(tail.map(l => l.eventId).sort(), ["$ok", "$ope0"].sort()); assert.deepEqual(gaps, [SWARM_ALIAS]); }); + +const edit = (id, ts) => ({ type: "m.room.message", event_id: id, sender: META, origin_server_ts: ts, content: { msgtype: "m.text", body: "* edited", "m.relates_to": { rel_type: "m.replace", event_id: "$x" } } }); +const threaded = (id, ts) => ({ type: "m.room.message", event_id: id, sender: META, origin_server_ts: ts, content: { msgtype: "m.text", body: "in thread", "m.relates_to": { rel_type: "m.thread", event_id: "$root" } } }); +const noise = (n, from) => Array.from({ length: n }, (_, i) => (i % 2 ? threaded : edit)(`$n${from + i}`, 1000 + from + i)); + +test("tail gaps: a full read window hides older real lines behind edits and thread replies, so the room is a gap; a short chunk is exhausted history, not a gap", async () => { + const hidden = await tailed({ preload: { [ROOM]: [...lines(ROOM, 5), ...noise(120, 0)] } }); + assert.deepEqual(hidden.tail, [], "the five real lines lie beyond the 100-event window"); + assert.deepEqual(hidden.gaps, [SWARM_ALIAS], "so the room is unknown, not quiet"); + const whole = await tailed({ preload: { [ROOM]: [...lines(ROOM, 5), ...noise(60, 0)] } }); + assert.equal(whole.tail.length, 5); + assert.deepEqual(whole.gaps, [], "a chunk shorter than the window reached the room's start"); +}); + +test("tail gaps: the total cap boundary: exactly 60 lines over all rooms is no gap, a 61st names the room that lost its oldest line", async () => { + const dms = ["!d1:gamecult.test", "!d2:gamecult.test"]; + const rooms60 = { [ROOM]: lines(ROOM, 20, 0), [OPERATOR]: lines(OPERATOR, 20, 20), [dms[0]]: lines(dms[0], 20, 40) }; + const at60 = await tailed({ preload: rooms60, direct: { [META]: dms }, member: [...Object.values(ROOMS), ...dms] }); + assert.equal(at60.tail.length, 60); + assert.deepEqual(at60.gaps, []); + const at61 = await tailed({ preload: { ...rooms60, [dms[1]]: lines(dms[1], 1, 60) }, direct: { [META]: dms }, member: [...Object.values(ROOMS), ...dms] }); + assert.equal(at61.tail.length, 60); + assert.deepEqual(at61.gaps, [SWARM_ALIAS]); +}); + +test("tail gaps: a byte-budget cut is contiguous at the oldest end, so an older line that would still fit is cut and its room gapped", () => { + const pack = { encode: v => Buffer.from(JSON.stringify(v)) }; + const mk = (room, i, text) => ({ roomAlias: room, eventId: `$${room}${i}`, atUnixMs: i, sender: "@a:x", form: "message", basis: null, text }); + const tiny = mk("#tiny:x", 0, "t"), big = Array.from({ length: 70 }, (_, i) => mk("#big:x", 1 + i, "y".repeat(5000))); + const got = replied({ lines: [tiny, ...big], gaps: [], rooms: ["#tiny:x", "#big:x"] }, pack); + assert.ok(!got.tail.some(l => l.roomAlias === "#tiny:x"), "nothing older than the cut is kept"); + assert.deepEqual(got.tailGaps, ["#tiny:x", "#big:x"]); +}); + +test("tail gaps: the read timer is cleared when the read answers, and a mouth that has not started names its configured rooms for an endpoint that cannot read", async () => { + const delay = 4321, made = new Set(), cleared = new Set(); + const realSet = globalThis.setTimeout, realClear = globalThis.clearTimeout; + globalThis.setTimeout = (fn, ms, ...rest) => { const t = realSet(fn, ms, ...rest); if (ms === delay) made.add(t); return t; }; + globalThis.clearTimeout = t => { cleared.add(t); return realClear(t); }; + const hs = await fakeHomeserver({ preload: { [ROOM]: lines(ROOM, 2), [OPERATOR]: lines(OPERATOR, 2) }, sync: since => ({ next_batch: since ?? "b0" }) }); + try { + const mouth = mouthFor(hs, { sendTimeoutMs: delay }); + assert.deepEqual(mouth.speakableRooms(), Object.keys(ROOMS), "before start: the configured rooms"); + await mouth.syncOnce(); + assert.deepEqual(mouth.speakableRooms(), Object.keys(ROOMS), "after start: the rooms she can speak in"); + await mouth.tail(); + assert.ok(made.size >= 2); + assert.ok([...made].every(t => cleared.has(t)), "no read timer is left running"); + } finally { globalThis.setTimeout = realSet; globalThis.clearTimeout = realClear; await hs.close(); } +}); diff --git a/tools/persona-chat-documents.mjs b/tools/persona-chat-documents.mjs index 313602b..7dc790d 100644 --- a/tools/persona-chat-documents.mjs +++ b/tools/persona-chat-documents.mjs @@ -251,7 +251,6 @@ function parseTailLine(t) { // tail_gaps: the rooms (alias, or room id for a DM) whose lines are not all in the tail, each once. Absent or empty: every room was read fully. export function pendingV3Tuple({ persona, deliveries, tail = [], tailGaps = [] }) { if (tail.length > limits.tailTotal) throw new Error("chat_pending tail is over the line bound"); - if (new Set(tailGaps).size !== tailGaps.length) throw new Error("chat_pending tail_gaps repeats a room"); return [text(persona, "persona"), deliveries.map(deliveryV3Tuple), tail.map(tailLineTuple), tailGaps.map(room => text(room, "tail_gap"))]; } export function parsePendingV3(t) { @@ -259,7 +258,9 @@ export function parsePendingV3(t) { if (!Array.isArray(deliveries)) throw new Error("chat_pending deliveries must be a list"); if (!Array.isArray(tail)) throw new Error("chat_pending tail must be a list"); if (!Array.isArray(tailGaps)) throw new Error("chat_pending tail_gaps must be a list"); - return { persona: text(persona, "persona"), deliveries: deliveries.map(parseDeliveryV3), tail: tail.map(parseTailLine), tailGaps: tailGaps.map(room => text(room, "tail_gap")) }; + const gaps = tailGaps.map(room => text(room, "tail_gap")); + if (new Set(gaps).size !== gaps.length) throw new Error("chat_pending tail_gaps repeats a room"); + return { persona: text(persona, "persona"), deliveries: deliveries.map(parseDeliveryV3), tail: tail.map(parseTailLine), tailGaps: gaps }; } // The CultNet document_put_raw envelope every chat_* document travels in. diff --git a/tools/persona-matrix-mouth.mjs b/tools/persona-matrix-mouth.mjs index a9f925e..c9767c3 100644 --- a/tools/persona-matrix-mouth.mjs +++ b/tools/persona-matrix-mouth.mjs @@ -254,11 +254,14 @@ export function createMouth({ const lineOf = e => ({ sender: e.sender, text: bodyText(e.content, docs.limits.contextBytes), atUnixMs: Number.isSafeInteger(e.origin_server_ts) && e.origin_server_ts >= 0 ? e.origin_server_ts : 0 }); // The room's recent messages outside threads, oldest first. - async function roomEvents(roomId) { + // `truncated`: the homeserver filled the whole window, so older history may exist that this read never saw. + async function roomRead(roomId) { const filter = encodeURIComponent(JSON.stringify({ types: ["m.room.message"] })); const reply = await matrix("GET", `/rooms/${encodeURIComponent(roomId)}/messages?dir=b&limit=${FETCH_LIMIT}&filter=${filter}`); - return (reply.chunk ?? []).filter(e => isLine(e) && threadRootOf(e) === null).reverse(); + const chunk = reply.chunk ?? []; + return { events: chunk.filter(e => isLine(e) && threadRootOf(e) === null).reverse(), truncated: chunk.length >= FETCH_LIMIT }; } + const roomEvents = async roomId => (await roomRead(roomId)).events; // One thread's messages, root first. async function threadEvents(roomId, rootId) { const room = encodeURIComponent(roomId); @@ -484,7 +487,7 @@ export function createMouth({ // basis is what Matrix says on the event itself (no reply lookup: nil is unproven). A room that cannot be read in sendTimeoutMs // is logged and absent, so one stuck room never holds the reply. // Returns { lines, gaps, rooms }: `rooms` are the rooms read, in read order (configured rooms in join order, then DMs); `gaps` are - // those of them whose lines are not all in `lines` (read failed or timed out, a line past a cap, a line dropped as malformed), in + // those of them whose lines are not all in `lines` (read failed or timed out, the read window full so older lines may be unseen, a line past a cap, a line dropped as malformed), in // the same order. A room with nothing to show because it is quiet is not a gap. A mouth that has not started knows no room but the // configured ones, and all of those are gaps. async function tail() { @@ -498,15 +501,16 @@ export function createMouth({ if (!read || now() - read.at >= TAIL_TTL_MS) { let timer; const lines = Promise.race([ - roomEvents(roomId), + roomRead(roomId), new Promise((_, fail) => { timer = setTimeout(() => fail(new Error(`no answer in ${sendTimeoutMs} ms`)), sendTimeoutMs); }), ]).catch(error => { say(`tail for ${roomId} not fetched: ${error.message}`); return null; }).finally(() => clearTimeout(timer)); read = { at: now(), lines }; tailReads.set(roomId, read); } - const events = await read.lines; - if (events === null) { if (tailReads.get(roomId) === read) tailReads.delete(roomId); gapped.add(alias); return []; } - if (events.length > docs.limits.tailPerRoom) gapped.add(alias); + const got = await read.lines; + if (got === null) { if (tailReads.get(roomId) === read) tailReads.delete(roomId); gapped.add(alias); return []; } + const { events, truncated } = got; + if (truncated || events.length > docs.limits.tailPerRoom) gapped.add(alias); const lines = []; for (const e of events.slice(-docs.limits.tailPerRoom)) { if (typeof e.event_id !== "string" || e.event_id === "") { gapped.add(alias); continue; }