im: settle a delivery that can never fit instead of retrying it

The intake accepted a message by the size of its draft and the session refused
the delivery by the size of a stored intent that repeated the message: `content`
carried it once and `trigger` carried it again, so the second check measured
about twice the first. A message in that band was stored, acknowledged and then
failed every delivery for good. `drain()` stops a chat at its first failure, the
intent stays pending and the retry timer keeps failing, so that chat kept every
later message — `/stop` and `/clear` included — behind the one that could never
be admitted.

Three changes, one budget:

- The event delivery no longer repeats the message as `trigger`; a delivery that
  names none quotes the message it delivered last, derived at admission. The
  intent is one copy of its messages, which is what the intake measured.
- `inputBytes()` is the one measurement both checks use, on the payload each of
  them stores, so the two cannot drift apart by a factor again.
- A `capacity` failure of the dispatch is terminal: the record is settled with
  the reason and the chat keeps draining. Transient failures still leave the
  record pending, which is what the retry timer and the next start re-dispatch.
This commit is contained in:
MicroBlock committed 2026-11-10 15:31:57 +08:00
1 parent 5c623458bb
commit 3efad4780b
7 files changed
+61 -6

No files matched your search

+1 -1
View File
@@ -129,7 +129,7 @@ export interface ImMessageEvent {
send(content: Fragment, options?: ImSendOptions): Promise<ImSendResult>
/**
* Convenience: deliver this message into a session. `id` defaults to the message key (idempotent on
* re-dispatch), `content` to `[message]` (formatted with `ctx.im.format`), `trigger` to the message.
* re-dispatch), `content` to `[message]` (formatted with `ctx.im.format`), `trigger` to the last delivered message.
*/
deliver(target: SessionId | string, options: ImEventDelivery): Promise<void>
}
-1
View File
@@ -288,7 +288,6 @@ export class ImService extends Service implements ImApi {
...options,
id: options.id ?? message.key,
content: options.content ?? [message],
trigger: options.trigger ?? message,
}),
}
}
+17 -2
View File
@@ -11,7 +11,9 @@ import {
ImChatKey, ImMessageKey, ImSourceId, splitKey, type ImChat, type ImCommand, type ImConfig, type ImMessage,
type ImMessageEvent, type ImOutcome, type ImSourceConfig,
} from './api.ts'
import { ImError } from './error.ts'
import type { ImDispatchState, ImMessageDraft, ImStore } from './store.ts'
import { inputBytes } from './store.ts'
/** What the dispatch loop needs from the service to build waterfall events. */
export interface ImIntakeHost {
@@ -225,7 +227,7 @@ export class ImIntake {
*/
private enriched(draft: ImMessageDraft, read: InboundMessage): ImMessageDraft {
const next: ImMessageDraft = { ...draft, content: read.content, text: toText(read.content) }
return Buffer.byteLength(JSON.stringify(next)) > this.config.maxInputBytes ? draft : next
return inputBytes(next) > this.config.maxInputBytes ? draft : next
}
/**
@@ -271,7 +273,7 @@ export class ImIntake {
await this.store.remember(key, { digest, receivedAt })
return
}
const bytes = Buffer.byteLength(JSON.stringify(draft))
const bytes = inputBytes(draft)
if (bytes > this.config.maxInputBytes) {
// Acknowledge and dedupe like a drifted redelivery: a refusal would leave the frame unacked, and the platform
// would redeliver a message that can never be accepted.
@@ -329,6 +331,19 @@ export class ImIntake {
await this.store.settle(message.key, await this.ctx.waterfall('im/message', event, fallback))
return true
} catch (error) {
if (error instanceof ImError && error.code === 'capacity') {
// The message can never be dispatched: it is over the size the delivery budget allows. Settling it keeps the
// chat draining — one oversized message used to stay pending forever, so every later message of that chat
// (including the `/stop` and `/clear` that would have unstuck it) waited behind it.
this.ctx.logger.warn('IM message %s cannot be dispatched and was dropped: %s', message.key, String(error))
try {
await this.store.settle(message.key, { kind: 'ignored', reason: error.message })
} catch (failure) {
this.ctx.logger.error('IM message %s could not be settled: %s', message.key, String(failure))
return false
}
return true
}
this.ctx.logger.warn('IM message %s was not dispatched and stays pending: %s', message.key, String(error))
return false
}
+8 -2
View File
@@ -23,6 +23,7 @@ import { ImError } from './error.ts'
import type { ImFormatter } from './format.ts'
import { sessionIdOf, type ImAgentHost } from './hosting.ts'
import { isStoredMessage, isStoredRecord, storedChatKey, storedSessionId } from './state.ts'
import { inputBytes } from './store.ts'
declare module '@deepseek-ai/dsh-llm' {
interface MessageSourceMap {
@@ -247,7 +248,9 @@ export class ImSessionHost implements ImSessions {
return
}
const stored: StoredDelivery = { session: record.sessionId, delivery, createdAt: Date.now(), admitted: false }
if (Buffer.byteLength(JSON.stringify(stored)) > this.config.maxInputBytes) {
// The same budget the intake applied to the message, measured on the same payload: the intent repeats the messages
// it carries, not a second copy of each (`trigger` is derived at admission).
if (inputBytes(delivery) > this.config.maxInputBytes) {
throw new ImError('capacity', 'IM delivery exceeds the configured byte limit.')
}
await this.write(() => this.domainOf().table('deliveries').put(id, stored))
@@ -382,7 +385,10 @@ export class ImSessionHost implements ImSessions {
media: delivery.media === true, ...delivery.header === undefined ? {} : { header: delivery.header },
})
: delivery.content
if (delivery.mode !== 'inject' && delivery.trigger) this.triggers.set(sessionId, delivery.trigger)
// A delivery that names no trigger quotes the message it delivered last: the intent already carries those
// messages, and repeating one of them as `trigger` doubled what a delivery had to fit into the budget.
const trigger = delivery.trigger ?? (isMessages(delivery.content) ? delivery.content.at(-1) : undefined)
if (delivery.mode !== 'inject' && trigger !== undefined) this.triggers.set(sessionId, trigger)
const message: UserMessage = {
id: messageId, role: 'user', content,
source: { kind: 'im', form: 'relay' },
+11
View File
@@ -21,6 +21,17 @@ const RECENT_OUTCOMES = 100
const noop = () => {}
/**
* Byte size of one message-shaped value, the one budget `maxInputBytes` bounds everywhere: the draft the intake
* accepts, and the delivery intent a session records. Both measure the JSON they are going to store, so a message that
* passes one check passes the other — the two used to measure different objects and disagree by a factor of two.
* @param value - the draft, intent or stored record to measure.
* @returns its UTF-8 JSON size in bytes.
*/
export function inputBytes(value: unknown): number {
return Buffer.byteLength(JSON.stringify(value))
}
/**
* Durable message store.
*
@@ -14,6 +14,7 @@ import {
ImChatKey, ImMessageKey, ImSourceId, type ImConfig, type ImMessage, type ImSourceConfig,
} from '../src/api.ts'
import { Config } from '../src/config.ts'
import { ImError } from '../src/error.ts'
import { admit, draftOf, ImIntake, parseCommand } from '../src/intake.ts'
import { ImStore } from '../src/store.ts'
@@ -338,6 +339,27 @@ describe('ImIntake pump', () => {
expect(dispatched).toHaveLength(2)
})
it('settles a message no delivery can fit and keeps the chat draining', async () => {
const harness = await boot()
const { ctx, intake, dispatched, store } = harness
ctx.on('im/message', async (event, next) => {
if (event.message.text === 'huge') {
throw new ImError('capacity', 'IM delivery exceeds the configured byte limit.')
}
return next()
})
await record(harness, inbound({ id: 'huge', content: h('message', h.text('huge')) }))
await record(harness, inbound({ id: 'small', content: h('message', h.text('small')) }))
intake.pump()
await intake.idle()
// Dropped rather than retried forever: the message behind it is dispatched in the same pass (the pump used to stop
// the chat at the first failure, so `small` never got an event at all).
expect(store.state(ImMessageKey('fake:bot', 'huge'))?.dispatch).toBe('done')
expect(dispatched.map(message => message.text)).toEqual(['huge', 'small'])
})
it('stops draining a chat whose first message failed and resumes in order', async () => {
const harness = await boot()
const { ctx, intake, dispatched } = harness
@@ -227,6 +227,8 @@ describe('delivery', () => {
expect(harness.formats).toHaveLength(1)
expect(harness.model.promptText(0)).toContain('from the chat')
// No explicit trigger: the delivery quotes the message it delivered last, so nothing is stored twice.
expect(harness.host.trigger(record.sessionId)).toBe(trigger)
await expect(harness.host.deliver('missing', delivery('followup', 'x'))).rejects.toThrow(/No IM session missing is hosted/)
})