Mouth tail: no ack cursor (acked unaddressed lines are what it exists for), per-room read timeout, tests for the gaps Soul found
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8e9ffb32f4
commit
db91716a3f
4 changed files with 51 additions and 27 deletions
|
|
@ -221,14 +221,14 @@ Proposed runtime half (follow-up `persona-wakes-on-address-only`):
|
|||
|
||||
### Room tail (`chat_pending.v3`, field 2)
|
||||
|
||||
The v3 answer is `[persona, deliveries, tail]`. `tail` is a list of recent room lines, oldest first, for a reader that was not woken for them (a scheduled beat). It is built from the same `/messages` read as a delivery's `context`, as her account, with no new endpoint and no new homeserver call per line. A `chat_pending_request.v1` is still answered with the two-field `chat_pending.v2`, and `chat_pending.v3` has not been deployed, so no reader sees the third field before it is ready for it.
|
||||
The v3 answer is `[persona, deliveries, tail]`. `tail` is a list of recent room lines, oldest first, for a reader that was not woken for them (a scheduled beat). It uses the same room read as a delivery's `context` (the same function, a separate read), as her account, with no new endpoint; the cost is one `/messages` call per speakable room per poll (15 seconds cached), including every DM. A `chat_pending_request.v1` is still answered with the two-field `chat_pending.v2`. `chat_pending.v3` has not been deployed, but a reader that decodes it as a two-field tuple fails on the third element (rmp-serde `LengthMismatch`), so Huginn must accept `tail` (a defaulted field) before this mouth is deployed.
|
||||
|
||||
| Bound | Rule |
|
||||
|---|---|
|
||||
| Rooms | Only rooms the Persona may speak in: a configured room she has joined, or one of her DMs. The same rule `send` uses (`speakableRoomId`). A room she is in but cannot speak in, and any other room, is absent. |
|
||||
| Lines | A text line outside threads, not an edit, newest `20` per room, newest `60` over all rooms. Trimmed oldest first if the reply byte budget (256 KiB, deliveries first) would be exceeded. |
|
||||
| Cursor | Only lines past her ack cursor in that room: the origin time of the newest delivery she has acked there (ties by event id). A room she has acked nothing in since the mouth started returns its recent lines, a quiet room included. The cursor is in memory: a restart forgets it and the next tail shows the recent lines again. |
|
||||
| Read | A room's read is kept 15 seconds, dropped when a sync brings the room news or an ack moves the cursor. A room that cannot be read is logged and absent; the other rooms and the deliveries are unaffected. |
|
||||
| Cursor | None. The tail is each room's newest lines whether or not they were delivered or acked: a message the wake rule left unaddressed is acked and leaves `pending`, and the tail is where a beat still finds it. A reader removes the lines a delivery already shows (by event id). Her own lines are included. |
|
||||
| Read | A room's read is kept 15 seconds, dropped when a sync brings the room news. A room that cannot be read within 10 seconds is logged and absent; the other rooms and the deliveries are unaffected. |
|
||||
|
||||
A line is the 7-field tuple `[room, event_id, at_unix_ms, sender, form, basis, body]`: `room` is the configured alias (the room id for a DM), `form` and `basis` as for a delivery, `body` clipped to 1000 bytes with the same typed text line for media a delivery has (nothing is fetched). `basis` is what Matrix says on the event itself (`direct` in a DM, `tag`, `room`) and nothing the mouth would have to look up, so a reply is nil here: **nil is unproven, not "not for her"**, and a line in a DM is `direct`. Huginn's rule that an `is_direct` delivery wakes with a nil `basis` is unchanged and lives with Huginn; the tail does not feed it.
|
||||
|
||||
|
|
|
|||
|
|
@ -140,7 +140,7 @@ 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 () => [tailLine],
|
||||
tail: async () => { if (calls.tailFails) throw new Error("room read failed"); return [tailLine]; },
|
||||
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 }; },
|
||||
|
|
@ -184,6 +184,15 @@ test("the RUDP endpoint serves pending, ack and send over CultNet, and answers a
|
|||
assert.deepEqual(v3.deliveries[0], { ...delivery, basis: null, form: "message" });
|
||||
assert.deepEqual(v3.tail, [tailLine], "the v3 answer carries the room tail");
|
||||
|
||||
calls.tailFails = true;
|
||||
reply = nextReply();
|
||||
put(docs.kinds.pendingRequestV3, "eureka", docs.pendingRequestTuple({ persona: "eureka", afterSeq: 0 }));
|
||||
document = await reply;
|
||||
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, []);
|
||||
calls.tailFails = false;
|
||||
|
||||
put(docs.kinds.ack, "eureka:7", docs.ackTuple({ persona: "eureka", throughSeq: 7 }));
|
||||
reply = nextReply();
|
||||
put(docs.kinds.sendRequest, "req-2", docs.sendRequestTuple({ requestId: "req-2", persona: "eureka", roomAlias: "#operator:gamecult.org", text: "muted" }));
|
||||
|
|
|
|||
|
|
@ -1528,7 +1528,7 @@ test("room tail: about 60 lines over all rooms, the newest, whatever the room co
|
|||
assert.equal(Math.min(...tail.map(l => l.atUnixMs)), 110, "the oldest kept is the 60th newest of the 120 offered");
|
||||
});
|
||||
|
||||
test("room tail: lines at or before her ack cursor are gone, later ones stay, and mention basis rides on the line", async () => {
|
||||
test("room tail: acking a delivery does not hide it, so an unaddressed line she has acked is still found, and mention basis rides on the line", async () => {
|
||||
const events = [
|
||||
withContent("$a", META, { body: "first" }, 3000),
|
||||
withContent("$b", META, { body: "tag", "m.mentions": { user_ids: [SELF] } }, 3001),
|
||||
|
|
@ -1538,12 +1538,29 @@ test("room tail: lines at or before her ack cursor are gone, later ones stay, an
|
|||
const mouth = mouthFor(hs);
|
||||
await mouth.syncOnce();
|
||||
const made = await mouth.syncOnce();
|
||||
assert.equal(made.length, 2);
|
||||
assert.deepEqual((await mouth.tail()).map(l => [l.eventId, l.basis]), [["$a", null], ["$b", "tag"]]);
|
||||
await mouth.ack(made[0].seq);
|
||||
assert.deepEqual((await mouth.tail()).map(l => l.eventId), ["$b"], "unacked past the cursor only");
|
||||
await mouth.ack(made[1].seq);
|
||||
assert.deepEqual(await mouth.tail(), []);
|
||||
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");
|
||||
} finally { await hs.close(); }
|
||||
});
|
||||
|
||||
test("room tail: a room that never answers is absent after the timeout and does not hold the others", 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 tail = await mouth.tail();
|
||||
assert.deepEqual([...new Set(tail.map(l => l.roomAlias))], [`#operator:${HS_NAME}`]);
|
||||
} 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.equal(hs.seen.filter(r => r.path.includes("/messages")).length, 0);
|
||||
} finally { await hs.close(); }
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -142,8 +142,7 @@ export function createMouth({
|
|||
let started = false;
|
||||
let lastPresence = null; // 'online' | 'unavailable' | 'offline' | null: command-only, suppresses repeat presence PUTs
|
||||
let activeUntil = 0; // her last sign of life in a turn, plus the grace
|
||||
const ackedThrough = new Map(); // room id -> { ts, ids }: the newest delivery she has acked there, ids those at exactly that time; the tail is what lies past it
|
||||
const tailReads = new Map(); // room id -> { at, lines }: a room's tail read, kept TAIL_TTL_MS or until a sync brings the room news or an ack moves the cursor
|
||||
const tailReads = new Map(); // room id -> { at, lines }: a room's tail read, kept TAIL_TTL_MS or until a sync brings the room news
|
||||
const delivered = new Map(); // event id -> { roomId, roomAlias, seq }: what the mouth handed her, newest last, bounded
|
||||
const readThrough = new Map(); // room id -> { seq, eventId } of the last receipt that landed
|
||||
const readTails = new Map(); // room id -> the read report in flight: reports for one room run one at a time
|
||||
|
|
@ -472,22 +471,18 @@ export function createMouth({
|
|||
}
|
||||
|
||||
async function ack(throughSeq) {
|
||||
for (const d of pending) if (d.seq <= throughSeq) {
|
||||
const through = ackedThrough.get(d.roomId);
|
||||
if (!through || d.atUnixMs > through.ts) ackedThrough.set(d.roomId, { ts: d.atUnixMs, ids: new Set([d.eventId]) });
|
||||
else if (d.atUnixMs === through.ts) through.ids.add(d.eventId);
|
||||
}
|
||||
pending = pending.filter(d => d.seq > throughSeq);
|
||||
tailReads.clear();
|
||||
images?.acked(throughSeq);
|
||||
await commit(pending.length ? pending[0].seq - 1 : seqCounter);
|
||||
touch();
|
||||
}
|
||||
|
||||
// Her rooms' recent talk, for a reader that was not woken for it: in each room she may speak in, the newest tailPerRoom lines past
|
||||
// her ack cursor there (a room she has acked nothing in yields its recent lines), the newest tailTotal over all rooms, oldest
|
||||
// first. From the same /messages read as a delivery's context, as her account, bodies clipped as context lines are. The basis is
|
||||
// what Matrix says on the event itself (no reply lookup: nil is unproven). A room that cannot be read is logged and absent.
|
||||
// Her rooms' recent talk, for a reader that was not woken for it: in each room she may speak in, the newest tailPerRoom lines
|
||||
// whether or not they were delivered or acked (a delivery the wake rule left unaddressed is acked and gone from `pending`; the tail
|
||||
// is where a beat still finds it, and the reader removes what a delivery already shows), the newest tailTotal over all rooms,
|
||||
// oldest first. From the same /messages read as a delivery's context, as her account, bodies clipped as context lines are. The
|
||||
// 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.
|
||||
async function tail() {
|
||||
if (!started) return [];
|
||||
const targets = new Set();
|
||||
|
|
@ -495,21 +490,24 @@ export function createMouth({
|
|||
const perRoom = await Promise.all([...targets].map(async roomId => {
|
||||
let read = tailReads.get(roomId);
|
||||
if (!read || now() - read.at >= TAIL_TTL_MS) {
|
||||
read = { at: now(), lines: roomEvents(roomId).catch(error => { say(`tail for ${roomId} not fetched: ${error.message}`); return null; }) };
|
||||
let timer;
|
||||
const lines = Promise.race([
|
||||
roomEvents(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); return []; }
|
||||
const through = ackedThrough.get(roomId);
|
||||
const alias = aliasByRoomId.get(roomId) ?? roomId;
|
||||
const lines = [];
|
||||
for (const e of events) {
|
||||
const at = Number.isSafeInteger(e.origin_server_ts) && e.origin_server_ts >= 0 ? e.origin_server_ts : 0;
|
||||
if (through && (at < through.ts || (at === through.ts && through.ids.has(e.event_id)))) continue;
|
||||
for (const e of events.slice(-docs.limits.tailPerRoom)) {
|
||||
if (typeof e.event_id !== "string" || e.event_id === "") continue;
|
||||
const at = Number.isSafeInteger(e.origin_server_ts) && e.origin_server_ts >= 0 ? e.origin_server_ts : 0;
|
||||
lines.push({ roomAlias: alias, eventId: e.event_id, atUnixMs: at, sender: e.sender, form: formOf(e.content), basis: await basisOf(roomId, e, false), text: bodyText(e.content, docs.limits.contextBytes) });
|
||||
}
|
||||
return lines.slice(-docs.limits.tailPerRoom);
|
||||
return lines;
|
||||
}));
|
||||
return perRoom.flat().sort((a, b) => a.atUnixMs - b.atUnixMs).slice(-docs.limits.tailTotal);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue