Skip to content

Commit fe42f4c

Browse files
committed
fix(resume): note a message once, so a resend is not sent twice
The notes keep what is still owed across a restart, so a message sent again carries the `exchangeId` the notes already hold. The delivery wrapper noted it a second time anyway, and `forgetQueued` dropped only the first entry: a turn taking the message up left one copy on disk, and the start after that sent the same message again. Measured on this branch: after a resent message was taken up, `inflight.json` held 1 entry for its exchange where `main` holds 0, so every restart inside `QUEUED_KEPT_MS` (24 h) re-answered it, and `resent` also bypasses the 60 s Bot de-duplication — "sent again once" did not survive a restart. Now an exchange the notes already hold is not noted twice, and a turn taking a message up forgets every note of that exchange (a Session moving to a new part can leave the exchange noted under two Session ids). The doc's pickup rule says both. Fixes #727 Fixes #769
1 parent 8d9118b commit fe42f4c

4 files changed

Lines changed: 131 additions & 17 deletions

File tree

‎core/src/host/resume.js‎

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -89,26 +89,33 @@ export function install(rt) {
8989
else turns[id] = next
9090
persist()
9191
}
92+
// Every entry of that exchange: one exchange can be noted under two Sessions while a Session
93+
// moves to a new part, and leaving one behind made the next start send the message again.
9294
const forgetQueued = (exchangeId) => {
95+
const rest = {}
96+
let dropped = false
9397
for (const [sessionId, list] of Object.entries(queued)) {
94-
const at = list.findIndex(item => item.args.exchangeId === exchangeId)
95-
if (at === -1) continue
96-
const rest = list.toSpliced(at, 1)
97-
queued = { ...queued }
98-
if (rest.length === 0) delete queued[sessionId]
99-
else queued[sessionId] = rest
100-
persist()
101-
return
98+
const kept = list.filter(item => item.args.exchangeId !== exchangeId)
99+
if (kept.length !== list.length) dropped = true
100+
if (kept.length > 0) rest[sessionId] = kept
102101
}
102+
if (!dropped) return
103+
queued = rest
104+
persist()
103105
}
104106

105107
const deliver = rt.deliver
106108
rt.deliver = async (args) => {
107109
const noted = { ...args, exchangeId: args.exchangeId ?? randomUUID() }
108110
const sessionId = noted.sessionId ?? rt.chatOf(noted.toId)
109-
// Noted before it is sent: a turn may take it up before the send returns.
110-
queued = { ...queued, [sessionId]: [...(queued[sessionId] ?? []), { at: Date.now(), args: noted }].slice(-QUEUED_MAX) }
111-
persist()
111+
// Noted before it is sent: a turn may take it up before the send returns. A resend delivers an
112+
// exchange the notes already hold, and noting it twice left the second copy on disk after the
113+
// turn took it up; that copy was sent again by the next start.
114+
const notedAlready = Object.values(queued).some(list => list.some(item => item.args.exchangeId === noted.exchangeId))
115+
if (!notedAlready) {
116+
queued = { ...queued, [sessionId]: [...(queued[sessionId] ?? []), { at: Date.now(), args: noted }].slice(-QUEUED_MAX) }
117+
persist()
118+
}
112119
try {
113120
return await deliver(noted)
114121
} catch (error) {

‎core/test/follow-through.test.js‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,37 @@ test('a message a shutdown cancelled is sent again once; one still waiting, take
371371
assert.equal((await second.call('exchange', { a: 'a', b: 'b' })).value.length, 4)
372372
})
373373

374+
test('a message sent again is forgotten everywhere once a turn takes it up', async (t) => {
375+
const home = freshHome(t)
376+
const first = await start(home)
377+
await first.tool('message_bot', { to: 'Writer', message: 'Draft the plan', when: 'queue' }, 'a')
378+
await settle(() => (notes(home).queued.b ?? []).length === 1)
379+
const [plan] = first.agentOf('b').calls
380+
const { exchangeId } = plan.source
381+
await first.stop()
382+
383+
// The second start sends the noted message again, under the same exchange.
384+
t.mock.timers.enable({ apis: ['setTimeout'] })
385+
const second = await start(home)
386+
t.mock.timers.tick(3000)
387+
await settle(() => second.agentOf('b').calls.length === 1)
388+
const [again] = second.agentOf('b').calls
389+
assert.equal(again.source.exchangeId, exchangeId)
390+
// The turn takes it up. Nothing of that exchange may stay noted: a second copy on disk made
391+
// every later start send the message once more.
392+
second.emit('b', 'user/message', { content: again.content, source: again.source })
393+
const notedExchange = () => Object.values(notes(home).queued ?? {}).flat().filter(item => item?.args?.exchangeId === exchangeId)
394+
await settle(() => notedExchange().length === 0)
395+
await second.stop()
396+
assert.equal(notedExchange().length, 0, 'the exchange a turn took up is still noted on disk')
397+
398+
// The third start has nothing to send.
399+
const third = await start(home)
400+
t.mock.timers.tick(3000)
401+
await flushWrites()
402+
assert.equal(third.agentOf('b').calls.length, 0, 'the message was sent a third time')
403+
})
404+
374405
test('a live interrupted end does not drop the note of a turn still owed a pickup', async (t) => {
375406
t.mock.timers.enable({ apis: ['setTimeout'] })
376407
const home = freshHome(t)

‎docs/subsystems/core-host.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ Work a member hands a Bot with `message_bot` from its group Session runs in a hi
225225
- A friend's Bot @-mentioned in a group never has its reply delivered back into that group (it lands in the friend's Bot's own chat), so the host posts one receipt line into the room per mention (`src/host/hooks.js` `mentionReceipt`, source role `mention`) and the client renders it as a muted event line (`src/client/cells.js`) (#80, #81). The role stays outside the room's round trigger (`groups.js` `opens`) and outside `RELAY_ROLES`, so the receipt opens no round and folds no turns. When that friend's Bot is already a current participant of the room, `sendUserMentions` skips the 1:1 `bot.send` entirely (#143): the human line in the room is the delivery, and Chief's grant is not consulted. A friend's line Bot Social attests they typed themselves (#227) arrives as `remoteChats.deliver({ human: true, ownerName })`: the message source carries `typedBy`, `turns.js` `claimTrigger` records the turn in `state.remoteTypedTurns[sessionId][turn]` (capped at 400 per Session, dropped with the part), `channel.js` publishes it as `roster.remoteTypedTurns` (narrowed per owner in `authz.js`), and the client draws that turn's reply as the person (`typedBy` in `src/client/text.js`, `PersonMessage` in `cells.js`). The flag is never derived from text. A failed 1:1 remote-chat send (`remote-chat.js` `forward` / `notSentLine`) is one short English line with a next step, never a raw `Bot Social send_as_member: …` preview. A local Bot's answer to a friend's Bot (`turns.js` `answer` → `flybotReplyRemote`, `role: 'reply'`, `via: 'auto-reply'`) that the send chain refuses is logged with its reason (#272): a `deny` resolves, it does not throw.
226226
- `deliver()` (`src/host/delivery.js`) copies a cleaned, plugin-attested `remote.typedBy` onto the message `source.remote` for a friend's line to a local Bot; the client uses it to draw the person (#233 follow-up).
227227
- A friend's line in a Bot's own chat (#420): `deliver()` (`noteFriendLine`) stamps the receiving Bot with `friendLineAt` (published in the roster, so the save moves the revision) and keeps the senders seen per Bot in `state.remoteContacts[botId][handle]` (host only, capped at 200, dropped with the Bot). A sender's first line carries `source.remote.firstContact`. Group lines, and re-deliveries (`deferred`, `resumed`, `retried`, `resent`), stamp nothing. Covered by `core/test/flybot.test.js`.
228-
- **Pickup after a restart** (`resume.js`): every running Bot turn and every delivered-but-not-taken message is noted in `inflight.json`. At the next start a noted turn is picked up once only if a restart really cut it: the durable Session log's `turn/end` for that turn is `interrupted` (or an abort caused by `disposed`, or there is no end). A turn that finished while this plugin was not listening — `completed`, `blocked`, `max-tokens`, `forked`, or aborted by the user / hook / parent — is not repeated; a `turn/start` seen after the start means the noted turn ended too. Notes from a build before the record carried `turn` keep the old behaviour. A pickup is confirmed before its note is dropped: the notes read at start are seeded into the live `turns`/`queued` (so the file keeps everything still owed), a turn's note stays while its pickup runs and is dropped only once handed over (unless the resumed turn has written its own note first), and a queued message whose resend fails is kept for the next start; a crash or a failed delivery during the pickup no longer loses the work — a pickup is at-least-once, not once: a crash between handing the turn over and the write that drops its note repeats that pickup once, because the `taken` set and the inbox that would tell the next start otherwise are process-local. That is the safe side of the trade, a repeated turn the user can see instead of work the user was told about going silently dead. Covered by `core/test/follow-through.test.js`.
228+
- **Pickup after a restart** (`resume.js`): every running Bot turn and every delivered-but-not-taken message is noted in `inflight.json`. At the next start a noted turn is picked up once only if a restart really cut it: the durable Session log's `turn/end` for that turn is `interrupted` (or an abort caused by `disposed`, or there is no end). A turn that finished while this plugin was not listening — `completed`, `blocked`, `max-tokens`, `forked`, or aborted by the user / hook / parent — is not repeated; a `turn/start` seen after the start means the noted turn ended too. Notes from a build before the record carried `turn` keep the old behaviour. A pickup is confirmed before its note is dropped: the notes read at start are seeded into the live `turns`/`queued` (so the file keeps everything still owed), a turn's note stays while its pickup runs and is dropped only once handed over (unless the resumed turn has written its own note first), and a queued message whose resend fails is kept for the next start, an exchange is noted once (a resend delivers the `exchangeId` the notes already hold, and noting it again left a copy behind after a turn took it up, so the start after that sent the message once more), and a turn taking up a message forgets every note of its exchange; a crash or a failed delivery during the pickup no longer loses the work — a pickup is at-least-once, not once: a crash between handing the turn over and the write that drops its note repeats that pickup once, because the `taken` set and the inbox that would tell the next start otherwise are process-local. That is the safe side of the trade, a repeated turn the user can see instead of work the user was told about going silently dead. Covered by `core/test/follow-through.test.js`.
229229
- A repeated Bot-to-Bot line becomes one turn (#641): `deliver()` keys the last 60 s of Bot-to-Bot text by sender + recipient Session + the text with its whitespace collapsed (`DEDUPE_MS`, `duplicateDelivery`), drops a repeat before it is recorded as an exchange or handed to the Session, and journals the drop as `delivery: dedupe <sender> -> <session>` in the host warning log. The key includes the Session, so the same line to another Session (a group copy, another Bot) is its own delivery; `deferred` / `resumed` / `retried` / `resent` carry on a message the Session already has and are never judged, and a friend's line, the user's own message and a group round are not Bot-to-Bot. Routing (parent and direct children) and the existing unread-queue refusal are unchanged, and the map is process-local and capped at 500 entries. Covered by `core/test/repeated-delivery.test.js`.
230230
- **A part moves before it is committed** (`parts.js` `moveOn`): the handoff package is written to the fresh Session first, then the Bot's `sessionId` / `room.sessions` and the new segment are saved (a failed save restores the old state and archives the fresh Session), and the move is marked done only after the stopped turn's input and the old inbox messages are forwarded. A failure at any point leaves the old part current and hands that input on there; a switch that never starts (no place, another switch, a read-only host) lets the step continue instead of rejecting its messages, which DSH has already taken out of the inbox. Covered by `core/test/work-dir.test.js`.
231231

‎patches/ds-bot/0001-core-fixes.patch‎

Lines changed: 81 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3255,7 +3255,52 @@ diff --git a/src/host/resume.js b/src/host/resume.js
32553255
const update = (id, change) => {
32563256
const next = change(turns[id])
32573257
if (next === turns[id]) return
3258-
@@ -137,10 +142,13 @@
3258+
@@ -84,26 +89,33 @@
3259+
else turns[id] = next
3260+
persist()
3261+
}
3262+
+ // Every entry of that exchange: one exchange can be noted under two Sessions while a Session
3263+
+ // moves to a new part, and leaving one behind made the next start send the message again.
3264+
const forgetQueued = (exchangeId) => {
3265+
+ const rest = {}
3266+
+ let dropped = false
3267+
for (const [sessionId, list] of Object.entries(queued)) {
3268+
- const at = list.findIndex(item => item.args.exchangeId === exchangeId)
3269+
- if (at === -1) continue
3270+
- const rest = list.toSpliced(at, 1)
3271+
- queued = { ...queued }
3272+
- if (rest.length === 0) delete queued[sessionId]
3273+
- else queued[sessionId] = rest
3274+
- persist()
3275+
- return
3276+
+ const kept = list.filter(item => item.args.exchangeId !== exchangeId)
3277+
+ if (kept.length !== list.length) dropped = true
3278+
+ if (kept.length > 0) rest[sessionId] = kept
3279+
}
3280+
+ if (!dropped) return
3281+
+ queued = rest
3282+
+ persist()
3283+
}
3284+
3285+
const deliver = rt.deliver
3286+
rt.deliver = async (args) => {
3287+
const noted = { ...args, exchangeId: args.exchangeId ?? randomUUID() }
3288+
const sessionId = noted.sessionId ?? rt.chatOf(noted.toId)
3289+
- // Noted before it is sent: a turn may take it up before the send returns.
3290+
- queued = { ...queued, [sessionId]: [...(queued[sessionId] ?? []), { at: Date.now(), args: noted }].slice(-QUEUED_MAX) }
3291+
- persist()
3292+
+ // Noted before it is sent: a turn may take it up before the send returns. A resend delivers an
3293+
+ // exchange the notes already hold, and noting it twice left the second copy on disk after the
3294+
+ // turn took it up; that copy was sent again by the next start.
3295+
+ const notedAlready = Object.values(queued).some(list => list.some(item => item.args.exchangeId === noted.exchangeId))
3296+
+ if (!notedAlready) {
3297+
+ queued = { ...queued, [sessionId]: [...(queued[sessionId] ?? []), { at: Date.now(), args: noted }].slice(-QUEUED_MAX) }
3298+
+ persist()
3299+
+ }
3300+
try {
3301+
return await deliver(noted)
3302+
} catch (error) {
3303+
@@ -137,10 +149,13 @@
32593304
case 'turn/start': {
32603305
const owner = rt.groupOwners.get(id)
32613306
const botId = owner?.botId ?? rt.chatOwners.get(id)
@@ -3270,7 +3315,7 @@ diff --git a/src/host/resume.js b/src/host/resume.js
32703315
if (event.data?.source?.kind !== SOURCE_KIND) break
32713316
// turns.js, installed earlier, has already claimed the turn's trigger.
32723317
const info = rt.live.get(id)?.info
3273-
@@ -151,7 +159,9 @@
3318+
@@ -151,7 +166,9 @@
32743319
case 'turn/end': {
32753320
// DSH stops every turn as it shuts down; that one is picked up at the next start.
32763321
const reason = event.data?.reason
@@ -3281,7 +3326,7 @@ diff --git a/src/host/resume.js b/src/host/resume.js
32813326
update(id, () => undefined)
32823327
break
32833328
}
3284-
@@ -173,17 +183,17 @@
3329+
@@ -173,17 +190,17 @@
32853330
// A turn already picked up once and cut off again stays stopped: a restart loop
32863331
// must not run it forever.
32873332
if (record.resumed) return
@@ -3302,7 +3347,7 @@ diff --git a/src/host/resume.js b/src/host/resume.js
33023347
}
33033348

33043349
// A hard stop keeps the inbox, which the Session runs once it wakes; only what DSH
3305-
@@ -198,39 +208,93 @@
3350+
@@ -198,39 +215,93 @@
33063351
&& current(item.args) !== undefined && taken?.has(item.args.exchangeId) !== true)
33073352
if (fresh.length === 0) return
33083353
const target = current(fresh[0].args)
@@ -5558,10 +5603,41 @@ diff --git a/test/follow-through.test.js b/test/follow-through.test.js
55585603
test('a finished turn leaves nothing to pick up', async (t) => {
55595604
t.mock.timers.enable({ apis: ['setTimeout'] })
55605605
const home = freshHome(t)
5561-
@@ -246,6 +371,34 @@
5606+
@@ -246,6 +371,65 @@
55625607
assert.equal((await second.call('exchange', { a: 'a', b: 'b' })).value.length, 4)
55635608
})
55645609

5610+
+test('a message sent again is forgotten everywhere once a turn takes it up', async (t) => {
5611+
+ const home = freshHome(t)
5612+
+ const first = await start(home)
5613+
+ await first.tool('message_bot', { to: 'Writer', message: 'Draft the plan', when: 'queue' }, 'a')
5614+
+ await settle(() => (notes(home).queued.b ?? []).length === 1)
5615+
+ const [plan] = first.agentOf('b').calls
5616+
+ const { exchangeId } = plan.source
5617+
+ await first.stop()
5618+
+
5619+
+ // The second start sends the noted message again, under the same exchange.
5620+
+ t.mock.timers.enable({ apis: ['setTimeout'] })
5621+
+ const second = await start(home)
5622+
+ t.mock.timers.tick(3000)
5623+
+ await settle(() => second.agentOf('b').calls.length === 1)
5624+
+ const [again] = second.agentOf('b').calls
5625+
+ assert.equal(again.source.exchangeId, exchangeId)
5626+
+ // The turn takes it up. Nothing of that exchange may stay noted: a second copy on disk made
5627+
+ // every later start send the message once more.
5628+
+ second.emit('b', 'user/message', { content: again.content, source: again.source })
5629+
+ const notedExchange = () => Object.values(notes(home).queued ?? {}).flat().filter(item => item?.args?.exchangeId === exchangeId)
5630+
+ await settle(() => notedExchange().length === 0)
5631+
+ await second.stop()
5632+
+ assert.equal(notedExchange().length, 0, 'the exchange a turn took up is still noted on disk')
5633+
+
5634+
+ // The third start has nothing to send.
5635+
+ const third = await start(home)
5636+
+ t.mock.timers.tick(3000)
5637+
+ await flushWrites()
5638+
+ assert.equal(third.agentOf('b').calls.length, 0, 'the message was sent a third time')
5639+
+})
5640+
+
55655641
+test('a live interrupted end does not drop the note of a turn still owed a pickup', async (t) => {
55665642
+ t.mock.timers.enable({ apis: ['setTimeout'] })
55675643
+ const home = freshHome(t)

0 commit comments

Comments
 (0)