Mouth: tail_gaps on chat_pending.v3, the rooms whose tail is incomplete

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Heimdall 2026-11-11 10:21:14 +00:00
commit cc0385cf53
9 changed files with 164 additions and 36 deletions

View file

@ -94,7 +94,7 @@ test("the brake reader reads a real CultCache control store", async () => {
test("two clients served at once each get their own answer on their own session", async () => {
const mouth = {
pendingAfter: () => [],
tail: async () => [],
tail: async () => ({ lines: [], gaps: [], rooms: [] }),
ack: async () => {},
// Slow enough that the two requests are in flight together.
send: async request => { await new Promise(r => setTimeout(r, 150)); return { requestId: request.requestId, eventId: `$${request.requestId}`, refusal: null }; },
@ -140,7 +140,8 @@ test("the RUDP endpoint serves pending, ack and send over CultNet, and answers a
const calls = { acks: [], sends: [], reads: [] };
const mouth = {
pendingAfter: after => (after < 7 ? [delivery] : []),
tail: async () => { if (calls.tailFails) throw new Error("room read failed"); return [tailLine]; },
tail: async () => { if (calls.tailFails) throw new Error("room read failed"); return { lines: [tailLine], gaps: ["#operator:gamecult.org"], rooms: ["#operator:gamecult.org", "#swarm:gamecult.org"] }; },
speakableRooms: () => ["#operator:gamecult.org", "#swarm:gamecult.org"],
ack: async through => { calls.acks.push(through); },
read: async request => { calls.reads.push(request); return null; },
send: async request => { calls.sends.push(request); return request.text === "muted" ? { requestId: request.requestId, eventId: null, refusal: "Brake" } : { requestId: request.requestId, eventId: "$sent", refusal: null }; },
@ -175,6 +176,7 @@ test("the RUDP endpoint serves pending, ack and send over CultNet, and answers a
const pending = docs.parsePending(msgpack.decode(document.payload));
assert.deepEqual(pending.deliveries.map(d => d.eventId), ["$e1"]);
assert.deepEqual(pending.deliveries[0], delivery, "sender, mentions and the DM flag cross the wire exactly");
assert.deepEqual(Buffer.from(document.payload), await readFile(resolve(root, "tests", "fixtures", "persona-chat-v3", "gamecult.persona.chat_pending.v2.no-image.msgpack")), "a v1 request is answered with the two-field v2, byte for byte the golden, whatever the tail gaps");
reply = nextReply();
put(docs.kinds.pendingRequestV3, "eureka", docs.pendingRequestTuple({ persona: "eureka", afterSeq: 0 }));
@ -183,6 +185,7 @@ test("the RUDP endpoint serves pending, ack and send over CultNet, and answers a
const v3 = docs.parsePendingV3(msgpack.decode(document.payload));
assert.deepEqual(v3.deliveries[0], { ...delivery, basis: null, form: "message" });
assert.deepEqual(v3.tail, [tailLine], "the v3 answer carries the room tail");
assert.deepEqual(v3.tailGaps, ["#operator:gamecult.org"], "and the rooms whose tail is incomplete");
calls.tailFails = true;
reply = nextReply();
@ -191,6 +194,7 @@ test("the RUDP endpoint serves pending, ack and send over CultNet, and answers a
const degraded = docs.parsePendingV3(msgpack.decode(document.payload));
assert.equal(degraded.deliveries.length, 1, "a tail that throws does not silence the deliveries");
assert.deepEqual(degraded.tail, []);
assert.deepEqual(degraded.tailGaps, ["#operator:gamecult.org", "#swarm:gamecult.org"], "a tail that throws leaves every speakable room a gap, not quiet");
calls.tailFails = false;
put(docs.kinds.ack, "eureka:7", docs.ackTuple({ persona: "eureka", throughSeq: 7 }));
@ -340,6 +344,9 @@ const v5Samples = {
{ roomAlias: "#operator:gamecult.org", eventId: "$e0", atUnixMs: 1_700_000_000_000, sender: "@meta:gamecult.org", form: "message", basis: null, text: "earlier" },
{ roomAlias: "#operator:gamecult.org", eventId: "$e1", atUnixMs: 1_700_000_001_000, sender: "@meta:gamecult.org", form: "notice", basis: "tag", text: "hello eureka" },
] }), parse: docs.parsePendingV3 },
"gamecult.persona.chat_pending.v3.tail-gaps": { tuple: docs.pendingV3Tuple({ persona: "eureka", deliveries: [], tail: [
{ roomAlias: "#operator:gamecult.org", eventId: "$e1", atUnixMs: 1_700_000_001_000, sender: "@meta:gamecult.org", form: "message", basis: null, text: "hello eureka" },
], tailGaps: ["#swarm:gamecult.org", "!dm1:gamecult.org"] }), parse: docs.parsePendingV3 },
"gamecult.persona.chat_pending.v3.unproven-notice": { tuple: docs.pendingV3Tuple({ persona: "eureka", deliveries: [{ ...delivery, isDirect: false, mentions: [], basis: null, form: "notice" }] }), parse: docs.parsePendingV3 },
};
for (const [name, { tuple, parse }] of Object.entries(v5Samples)) {
@ -349,9 +356,10 @@ for (const [name, { tuple, parse }] of Object.entries(v5Samples)) {
if (process.env.UPDATE_FIXTURES === "1") { await mkdir(v5Dir, { recursive: true }); await writeFile(file, bytes); }
assert.deepEqual(bytes, await readFile(file), "wire bytes changed: Huginn decodes these fixtures");
assert.deepEqual(parse(msgpack.decode(bytes)), parse(tuple));
if (name.includes("pending.v3")) assert.equal(msgpack.decode(bytes).length, 3, "persona, deliveries, tail");
if (name.includes("pending.v3")) assert.equal(msgpack.decode(bytes).length, 4, "persona, deliveries, tail, tail_gaps");
if (name.endsWith("v3.tag") || name.endsWith("unproven-notice")) assert.equal(msgpack.decode(bytes)[1][0].length, 14);
if (name.endsWith("v3.tail")) assert.equal(msgpack.decode(bytes)[2][0].length, 7);
if (name.endsWith("v3.tail")) { assert.equal(msgpack.decode(bytes)[2][0].length, 7); assert.deepEqual(msgpack.decode(bytes)[3], [], "no gap: every room read fully"); }
if (name.endsWith("v3.tail-gaps")) assert.deepEqual(msgpack.decode(bytes)[3], ["#swarm:gamecult.org", "!dm1:gamecult.org"]);
});
}
@ -390,7 +398,7 @@ test("RoomMoved is v2 only, and the v2 documents are strict about arity and newe
test("the RUDP endpoint answers a v1 send with the three-field receipt and a v2 send with the four-field one", async () => {
const seen = [];
const mouth = { pendingAfter: () => [], tail: async () => [], ack: async () => {}, send: async request => {
const mouth = { pendingAfter: () => [], tail: async () => ({ lines: [], gaps: [], rooms: [] }), ack: async () => {}, send: async request => {
seen.push(request);
return request.basis ? { requestId: request.requestId, eventId: null, refusal: "RoomMoved", newer: ["$a"] } : { requestId: request.requestId, eventId: "$sent", refusal: null, newer: [] };
} };
@ -566,3 +574,16 @@ test("the RUDP endpoint answers an open-direct request with a receipt for its Pe
try { client.close(); } catch { /* the connection already closed its socket */ }
}
});
test("tail_gaps is additive: a three-field reader finds persona, deliveries and tail unchanged in the first three elements of the new bytes", async () => {
const sample = { persona: "eureka", deliveries: [{ ...delivery, isDirect: false, basis: "tag", form: "message" }], tail: [{ roomAlias: "#operator:gamecult.org", eventId: "$e0", atUnixMs: 1_700_000_000_000, sender: "@meta:gamecult.org", form: "message", basis: null, text: "earlier" }] };
const noGaps = msgpack.decode(msgpack.encode(docs.pendingV3Tuple(sample)));
const after = msgpack.decode(await readFile(resolve(root, "tests", "fixtures", "persona-chat-v5", "gamecult.persona.chat_pending.v3.tail-gaps.msgpack")));
const withGaps = msgpack.decode(msgpack.encode(docs.pendingV3Tuple({ ...sample, tailGaps: ["#swarm:gamecult.org"] })));
assert.equal(withGaps.length, 4);
assert.deepEqual(withGaps.slice(0, 3), noGaps.slice(0, 3), "persona, deliveries and tail are byte-for-meaning the same with or without gaps");
assert.deepEqual(docs.parsePendingV3([...withGaps.slice(0, 3), []]).tail, docs.parsePendingV3(noGaps).tail);
assert.equal(after.length, 4);
// Not claimed: a strict three-field decoder (rmp-serde into a three-field tuple) accepts it. It fails on the length, as it did for the tail, so Huginn defaults tail_gaps before this mouth deploys.
assert.notEqual(withGaps.length, 3);
});

View file

@ -1485,7 +1485,8 @@ async function tailed({ preload, direct, member, events = [], act = async () =>
const mouth = mouthFor(hs);
await mouth.syncOnce();
await act(mouth);
return { tail: await mouth.tail(), mouth, hs };
const read = await mouth.tail();
return { tail: read.lines, gaps: read.gaps, rooms: read.rooms, mouth, hs };
} finally { await hs.close(); }
}
@ -1538,10 +1539,10 @@ test("room tail: acking a delivery does not hide it, so an unaddressed line she
const mouth = mouthFor(hs);
await mouth.syncOnce();
const made = await mouth.syncOnce();
assert.deepEqual((await mouth.tail()).map(l => [l.eventId, l.basis]), [["$a", null], ["$b", "tag"]]);
assert.deepEqual((await mouth.tail()).lines.map(l => [l.eventId, l.basis]), [["$a", null], ["$b", "tag"]]);
await mouth.ack(made[1].seq);
assert.equal(mouth.pendingAfter(0).length, 0);
assert.deepEqual((await mouth.tail()).map(l => l.eventId), ["$a", "$b"], "acked lines are the ones no delivery will bring again");
assert.deepEqual((await mouth.tail()).lines.map(l => l.eventId), ["$a", "$b"], "acked lines are the ones no delivery will bring again");
} finally { await hs.close(); }
});
@ -1551,15 +1552,16 @@ test("room tail: a room that never answers is absent after the timeout and does
try {
const mouth = mouthFor(hs, { fetch: hang, sendTimeoutMs: 50 });
await mouth.syncOnce();
const tail = await mouth.tail();
assert.deepEqual([...new Set(tail.map(l => l.roomAlias))], [`#operator:${HS_NAME}`]);
const read = await mouth.tail();
assert.deepEqual([...new Set(read.lines.map(l => l.roomAlias))], [`#operator:${HS_NAME}`]);
assert.deepEqual(read.gaps, [`#swarm:${HS_NAME}`], "the room that timed out is a gap; the one that answered is not");
} finally { await hs.close(); }
});
test("room tail: a mouth that has not started reads no room", async () => {
const hs = await fakeHomeserver({ preload: { [ROOM]: lines(ROOM, 2) }, sync: since => ({ next_batch: since ?? "b0" }) });
try {
assert.deepEqual(await mouthFor(hs).tail(), []);
assert.deepEqual(await mouthFor(hs).tail(), { lines: [], gaps: Object.keys(ROOMS), rooms: Object.keys(ROOMS) }, "no room is known before start, so every configured room is a gap");
assert.equal(hs.seen.filter(r => r.path.includes("/messages")).length, 0);
} finally { await hs.close(); }
});
@ -1571,24 +1573,90 @@ test("room tail: a body is clipped like a context line, and an unreadable room i
try {
const mouth = mouthFor(hs);
await mouth.syncOnce();
assert.deepEqual(await mouth.tail(), []);
const read = await mouth.tail();
assert.deepEqual(read.lines, []);
assert.deepEqual(read.gaps, Object.keys(ROOMS).filter(a => read.rooms.includes(a)), "an unreadable room is a gap, not quiet");
assert.ok(read.gaps.length > 0);
} finally { await hs.close(); }
});
test("room tail: only the v3 answer carries it; the v2 answer a v1 request gets is unchanged", async () => {
const { tail } = await tailed({ preload: { [ROOM]: lines(ROOM, 2) } });
const { tail, gaps, rooms } = await tailed({ preload: { [ROOM]: lines(ROOM, 2) } });
const pack = { encode: v => Buffer.from(JSON.stringify(v)) };
assert.deepEqual(docs.parsePendingV3(pageOf("eureka", [], pack, () => {}, true, tail)).tail.map(l => l.text), ["line 0", "line 1"]);
const v2 = pageOf("eureka", [], pack, () => {}, false, tail);
assert.deepEqual(docs.parsePendingV3(pageOf("eureka", [], pack, () => {}, true, { lines: tail, gaps, rooms })).tail.map(l => l.text), ["line 0", "line 1"]);
const v2 = pageOf("eureka", [], pack, () => {}, false, { lines: tail, gaps: rooms, rooms });
assert.equal(v2.length, 2);
assert.deepEqual(docs.parsePending(v2), { persona: "eureka", deliveries: [] });
assert.throws(() => docs.parsePendingV3(["eureka", []]), /3-field/);
assert.throws(() => docs.parsePendingV3(["eureka", []]), /4-field/);
});
test("room tail: the reply byte budget trims the oldest tail lines, never a delivery", async () => {
const pack = { encode: v => Buffer.from(JSON.stringify(v)) };
const big = Array.from({ length: 60 }, (_, i) => ({ roomAlias: "#r:x", eventId: `$${i}`, atUnixMs: i, sender: "@a:x", form: "message", basis: null, text: "y".repeat(5000) }));
const kept = docs.parsePendingV3(pageOf("eureka", [], pack, () => {}, true, big)).tail;
const kept = docs.parsePendingV3(pageOf("eureka", [], pack, () => {}, true, { lines: big, gaps: [], rooms: ["#r:x"] })).tail;
assert.ok(kept.length > 0 && kept.length < 60);
assert.equal(kept.at(-1).eventId, "$59", "the newest survive");
});
// tail_gaps (docs/bridge.md, "Gaps in the tail"): the rooms whose lines are not all in the tail, so a reader says "unknown", not "quiet".
// Each case goes through the composition the RUDP endpoint serves: mouth.tail() into pageOf into the strict v3 parser.
const replied = (read, pack = { encode: v => Buffer.from(JSON.stringify(v)) }) => docs.parsePendingV3(pageOf("eureka", [], pack, () => {}, true, read));
const SWARM_ALIAS = `#swarm:${HS_NAME}`, OPERATOR_ALIAS = `#operator:${HS_NAME}`;
test("tail gaps: a room whose read times out is a gap; the room that answered, quiet or not, is not", async () => {
const hs = await fakeHomeserver({ preload: { [OPERATOR]: lines(OPERATOR, 2) }, sync: since => ({ next_batch: since ?? "b0" }) });
const hang = (url, init) => String(url).includes(encodeURIComponent(ROOM)) && String(url).includes("/messages") ? new Promise(() => {}) : hs.fetch(url, init);
try {
const mouth = mouthFor(hs, { fetch: hang, sendTimeoutMs: 50 });
await mouth.syncOnce();
const got = replied(await mouth.tail());
assert.deepEqual(got.tailGaps, [SWARM_ALIAS]);
assert.deepEqual(got.tail.map(l => l.roomAlias), [OPERATOR_ALIAS, OPERATOR_ALIAS]);
} finally { await hs.close(); }
});
test("tail gaps: a failed read is a gap, a quiet room (no lines) and a normal room (a few lines) are not, and exactly the per-room cap is not a trim", async () => {
const failing = await fakeHomeserver({ failContext: true, sync: since => ({ next_batch: since ?? "b0" }) });
try {
const mouth = mouthFor(failing);
await mouth.syncOnce();
assert.deepEqual(replied(await mouth.tail()).tailGaps, [SWARM_ALIAS, OPERATOR_ALIAS], "every read failed: both rooms unknown, in room order");
} finally { await failing.close(); }
const { gaps } = await tailed({ preload: { [ROOM]: lines(ROOM, docs.limits.tailPerRoom) } });
assert.deepEqual(gaps, [], "20 lines in one room and none in the other: nothing was left out");
const some = await tailed({ preload: { [ROOM]: lines(ROOM, 3), [OPERATOR]: [] } });
assert.deepEqual(replied({ lines: some.tail, gaps: some.gaps, rooms: some.rooms }).tailGaps, []);
});
test("tail gaps: a room with more lines than the per-room cap is a gap, once, and only that room", async () => {
const { tail, gaps } = await tailed({ preload: { [ROOM]: lines(ROOM, docs.limits.tailPerRoom + 1), [OPERATOR]: lines(OPERATOR, 3) } });
assert.equal(tail.filter(l => l.roomAlias === SWARM_ALIAS).length, docs.limits.tailPerRoom);
assert.deepEqual(gaps, [SWARM_ALIAS]);
});
test("tail gaps: the total cap names the rooms it dropped lines from, in room order, never a room whose lines all fit", async () => {
const dms = ["!d1:gamecult.test", "!d2:gamecult.test", "!d3:gamecult.test"];
const preload = { [ROOM]: lines(ROOM, 25, 100), [OPERATOR]: lines(OPERATOR, 20, 0) };
dms.forEach((dm, i) => { preload[dm] = lines(dm, 20, 200 + 20 * i); });
const { tail, gaps } = await tailed({ preload, direct: { [META]: dms }, member: [...Object.values(ROOMS), ...dms] });
assert.equal(tail.length, 60);
assert.deepEqual(gaps, [SWARM_ALIAS, OPERATOR_ALIAS], "swarm is gapped by both caps and named once; the three DMs kept all 20 lines");
});
test("tail gaps: the reply byte budget and a line that will not encode gap their rooms, and only those", () => {
const pack = { encode: v => Buffer.from(JSON.stringify(v)) };
const mk = (room, i, extra = {}) => ({ roomAlias: room, eventId: `$${room}${i}`, atUnixMs: i, sender: "@a:x", form: "message", basis: null, text: "y".repeat(5000), ...extra });
const old = Array.from({ length: 30 }, (_, i) => mk("#old:x", i)), fresh = Array.from({ length: 30 }, (_, i) => mk("#new:x", 100 + i));
const got = replied({ lines: [...old, ...fresh], gaps: [], rooms: ["#old:x", "#new:x", "#empty:x"] }, pack);
assert.ok(got.tail.length < 60);
assert.deepEqual(got.tailGaps, ["#old:x"], "the oldest lines were trimmed; the newer room and the quiet room are whole");
const bad = replied({ lines: [mk("#a:x", 1), mk("#b:x", 2, { sender: 123 })], gaps: [], rooms: ["#a:x", "#b:x"] }, pack);
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/);
assert.throws(() => docs.parsePendingV3(["eureka", [], []]), /4-field/);
assert.throws(() => docs.parsePendingV3(["eureka", [], [], "#a:x"]), /list/);
});