Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
439cf2c
Keep failed sends visible in conversation on unary RPC transport errors
Fei2411 Dec 4, 2026
2977d47
Harden failed-send reconciliation, retry locking, and RPC delivery cl…
Fei2411 Dec 4, 2026
31173b5
Merge remote-tracking branch 'origin/dev' into fix/2299-rework-r2
Fei2411 Dec 4, 2026
e7210f1
Fix group rpcId receipts, legacy replay dedup, queue durability, send…
Fei2411 Dec 4, 2026
92d7ea6
Require durable requestId receipts, retry failed-send lazy chunk, and…
Fei2411 Dec 4, 2026
07d3b4f
Merge remote-tracking branch 'origin/dev' into fix/2299-rework-r2
Fei2411 Dec 4, 2026
5bbf720
Persist group ledger before inbox dequeue, unify ledger durability ev…
Fei2411 Dec 4, 2026
609fc66
Merge remote-tracking branch 'origin/dev' into fix/2299-rework-r5
Fei2411 Dec 5, 2026
e4a33f7
Hand off group inbox-to-ledger ownership atomically across DSH turns …
Fei2411 Dec 5, 2026
b45c381
Harden group inbox handover, pending dispatch recovery, and pre-step …
Fei2411 Dec 5, 2026
4e5832a
Merge origin/dev into fix/2299-rework-r5 and regenerate contracts
Fei2411 Dec 5, 2026
8006526
Merge remote-tracking branch 'origin/dev' into fix/2299-rework-r5
Fei2411 Dec 5, 2026
ec53081
Deduplicate ledger group dispatches on member receipt and persist sto…
Fei2411 Dec 5, 2026
d3de5df
Enforce cancellation and fail-closed receipt verification at group le…
Fei2411 Dec 5, 2026
ff2d62b
Harden parked room ledger wake recheck and add backoff retry for unre…
Fei2411 Dec 5, 2026
912e502
Release room ledger recovery claim and retry after opening round failure
Fei2411 Dec 5, 2026
89b74c3
Require persisted member receipt before marking group ledger dispatched
Fei2411 Dec 5, 2026
75d7ad0
Require persisted native user/message before room supersede or member…
Fei2411 Dec 5, 2026
8138b46
Share ledger dispatch identity and persist stop across provisional ro…
Fei2411 Dec 5, 2026
0736a27
fix(ds-bot): decouple room supersede from member dispatch and bind pe…
Fei2411 Dec 5, 2026
91e14da
fix(ds-bot): hand off orphaned roomInbox posts on native turn exit an…
Fei2411 Dec 5, 2026
db37d00
fix(ds-bot): guarantee ledger prompt text, persist before roomInbox d…
Fei2411 Dec 5, 2026
5f9b1bc
fix(ds-bot): reconstruct failed ledger handovers per session, persist…
Fei2411 Dec 5, 2026
5db17ab
fix(groups): reconstruct rolled-back native turns from persisted even…
Fei2411 Dec 5, 2026
57d3603
fix(groups): handle unstarted/unknown relay crashes with identity ded…
Fei2411 Dec 5, 2026
41bc542
fix(groups): recover unfinished async group_relay rounds per member a…
Fei2411 Dec 5, 2026
9d7c403
fix(groups): bind round ownership to exact anchors/identities and res…
Fei2411 Dec 5, 2026
87d9570
fix(groups): enforce per-message userIdentities over shared relay anchor
Fei2411 Dec 5, 2026
30951cc
fix(groups): preserve persisted session-reference snapshots across ro…
Fei2411 Dec 5, 2026
ba19e94
fix(groups): isolate reference rounds bidirectionally and resolve eve…
Fei2411 Dec 5, 2026
a01e1cb
fix(groups): enforce unified reference-round isolation across drainRo…
Fei2411 Dec 5, 2026
ca440f2
fix(groups): hand over orphaned laterPosts user entries when ledger r…
Fei2411 Dec 5, 2026
8586269
fix(groups): bind reconstructed laterPosts user entries in-place to p…
Fei2411 Dec 5, 2026
1d5d037
fix(groups): preserve bound laterPosts FIFO across consecutive openin…
Fei2411 Dec 5, 2026
9a31eb0
fix(groups): hold FIFO behind unready head and cancel in-flight Bot c…
Fei2411 Dec 5, 2026
8be78b9
fix(groups): hold partial head FIFO, abort opening before call creati…
Fei2411 Dec 5, 2026
85d9ab9
fix(groups): enforce pending-head barrier, drain bot-only suffix, and…
Fei2411 Dec 5, 2026
7c1652c
fix(ds-bot): enforce pending-head FIFO on postToRoom/holdForNextRound…
Fei2411 Dec 5, 2026
d742f7b
fix(ds-bot): guard partial in-flight heads, keep completed room claim…
Fei2411 Dec 5, 2026
d6dc092
fix(ds-bot): tighten room handoff admission, cold FIFO recovery, and …
Fei2411 Dec 6, 2026
2006932
fix(ds-bot): preserve in-flight and cold-rebuild room FIFO barriers a…
Fei2411 Dec 6, 2026
3d49a4c
fix(ds-bot): guard concurrent unpersisted rebuilds and abort mixed st…
Fei2411 Dec 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(groups): preserve persisted session-reference snapshots across ro…
…om recovery
  • Loading branch information
Fei2411 committed Dec 5, 2026
commit 30951cc21f60c6c7e793210a0e816fd318b7e6db
144 changes: 122 additions & 22 deletions ds-bot/src/host/groups.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
HISTORY_TIMEOUT_MS,
INSTANT_WORK_TOOLS,
MESSAGE_INLINE_MAX,
REFERENCE_KIND,
ROOM_REPLY_TIMEOUT_MS,
ROOM_STEP_GAP_MS,
ROOM_WORK_GRACE_MS,
Expand Down Expand Up @@ -2164,6 +2165,49 @@ export function install(rt) {
}
return unhandled
}
const collectRoomSessionReferences = (events) => {
const byKey = new Map()
if (!Array.isArray(events) || events.length === 0) return byKey
let currentKeys = []
for (const ev of events) {
if (ev === null || typeof ev !== 'object') continue
if (ev.type === 'user/message' && ev.data?.source?.kind === 'user') {
const rpcId = typeof ev.data?.source?.rpcId === 'string' ? ev.data.source.rpcId.trim() : ''
const inboxId = typeof ev.data?.id === 'string' ? ev.data.id.trim() : ''
currentKeys = rpcId !== '' && !rpcId.startsWith('api:')
? roomIdentityKeysOf({ inboxId: inboxId || undefined, rpcId })
: []
continue
}
if (ev.type === 'user/message' && ev.data?.source?.kind === REFERENCE_KIND) {
const refText = textOf(ev.data?.content)
if (refText !== '' && currentKeys.length > 0) {
const labels = (Array.isArray(ev.data?.source?.references) ? ev.data.source.references : [])
.map(ref => ref?.label)
.filter(label => typeof label === 'string' && label !== '')
const entry = { labels, text: refText }
for (const key of currentKeys) {
let list = byKey.get(key)
if (list === undefined) { list = []; byKey.set(key, list) }
list.push(entry)
}
}
continue
}
if (ev.type === 'assistant/message' || ev.type === 'tool/call' || ev.type === 'tool/result' || ev.type === 'turn/end') {
currentKeys = []
}
}
return byKey
}
const refsOfIdentity = (refsByIdentity, identity) => {
if (refsByIdentity === undefined || refsByIdentity.size === 0) return undefined
for (const key of roomIdentityKeysOf(identity)) {
const list = refsByIdentity.get(key)
if (list !== undefined && list.length > 0) return list
}
return undefined
}
const isAsyncRelayCoveredByCompletedRound = (records, { rpcId, inboxId, relayAnchor } = {}) => {
if (!Array.isArray(records) || records.length === 0) return false
const identityKeys = roomIdentityKeysOf({ inboxId, rpcId })
Expand Down Expand Up @@ -2267,6 +2311,7 @@ export function install(rt) {
let created = 0
let hadFailure = false
let hadConcurrentInFlight = false
const refsByIdentity = collectRoomSessionReferences(events)
for (const { ev, rpcId, inboxId, asyncRelay, relayAnchor } of orphaned) {
const identity = { inboxId: inboxId || undefined, rpcId }
if (hasExistingLedgerDispatch(rpcId, inboxId)) continue
Expand Down Expand Up @@ -2316,15 +2361,20 @@ export function install(rt) {
try {
const text = textOf(ev.data?.content)
const via = viaOf(ev.data?.source)
const content = Array.isArray(ev.data?.content) ? ev.data.content : []
const files = content.filter(block => block?.type === 'file' && block.attachment !== undefined).map(block => block.attachment)
const references = refsOfIdentity(refsByIdentity, identity)
const rec = appendLine(room, {
who: 'User',
text,
...(files.length > 0 ? { files } : {}),
...(references !== undefined ? { hasReferences: true } : {}),
...(via ? { via } : {}),
rpcId,
...(inboxId !== '' ? { messageId: inboxId } : {}),
...(Number.isInteger(ev.seq) ? { eventSeq: ev.seq, eventSession: roomSid } : {}),
dispatch: 'pending',
})
}, references)
noteSessionClaimedSeq(room.id, rec.seq)
const write = lineWrites.get(lineWriteKey(room, rec.seq)) ?? rt.ledger.written?.(book)
try {
Expand Down Expand Up @@ -4908,6 +4958,13 @@ export function install(rt) {
for (const line of shown) {
if (line === undefined || line === null || line.botId !== undefined || line.kind !== undefined || line.event !== undefined) continue
const lineIdentityKeys = roomIdentityKeysOf({ inboxId: line.messageId, rpcId: line.rpcId })
const matched = line.dispatch === 'pending' && Number.isInteger(line.seq)
? (rt.ledger?.record?.(book, line.seq) ?? line)
: findMatchingRoomLedgerDispatchRecord(room.id, { inboxId: line.messageId, rpcId: line.rpcId })
const requiresReferencePayload = line.hasReferences === true || matched?.hasReferences === true
const roundCarriesLineRefs = (round.references?.length ?? 0) > 0
&& lineIdentityKeys.some(key => round.userIdentities?.has(key))
if (requiresReferencePayload && !roundCarriesLineRefs) continue
if (lineIdentityKeys.length > 0) {
const lineMentions = mentionsIn(line.text ?? '', roomMembers)
const lineInvite = resolveUserInvite({ members: roomMembers, adminId: room.admin, mode: room.mode, mentions: lineMentions })
Expand All @@ -4916,9 +4973,6 @@ export function install(rt) {
for (const key of lineIdentityKeys) slot.roomMessageIdentities.add(key)
}
}
const matched = line.dispatch === 'pending' && Number.isInteger(line.seq)
? (rt.ledger?.record?.(book, line.seq) ?? line)
: findMatchingRoomLedgerDispatchRecord(room.id, { inboxId: line.messageId, rpcId: line.rpcId })
if (matched === undefined || matched.dispatch !== 'pending' || !Number.isInteger(matched.seq)) continue
if (slot.ledgerDispatchSeqs?.has(matched.seq) === true) continue
if (typeof rt.ledger?.isPersisted === 'function' && rt.ledger.isPersisted(book, matched) !== true) continue
Expand Down Expand Up @@ -6755,6 +6809,7 @@ export function install(rt) {
...(typeof post.messageId === 'string' && post.messageId !== '' ? { messageId: post.messageId } : {}),
...(post.images === undefined ? {} : { images: post.images }),
...(post.files === undefined ? {} : { files: post.files }),
...(post.references?.length > 0 ? { hasReferences: true } : {}),
...(post.externalPost === true && post.fullText !== undefined ? { overflow: true } : {}),
...(presented.length > 0 ? { presented } : {}),
...(post.via === undefined ? {} : { via: post.via }),
Expand Down Expand Up @@ -8784,7 +8839,7 @@ export function install(rt) {
}
rt.greetRoom = greetRoom

const pendingRoomLedgerDispatches = (room) => {
const pendingRoomLedgerDispatches = (room, { refsByIdentity } = {}) => {
if (room === undefined) return []
const book = bookOf(room.id)
if (typeof rt.ledger?.hasBook === 'function' && !rt.ledger.hasBook(book)) return []
Expand Down Expand Up @@ -8829,7 +8884,8 @@ export function install(rt) {
if (hasInFlightRoomDrainSeq(room.id, record.seq)) continue
if (recovering?.has(record.seq) === true) continue
if (queuedSeqs.has(record.seq)) continue
const mentions = mentionsIn(record.text ?? '', members)
const references = refsOfIdentity(refsByIdentity, { inboxId: record.messageId, rpcId: record.rpcId })
const mentions = mentionsIn(record.text ?? '', members, references ?? [])
const invite = resolveUserInvite({ members, adminId: room.admin, mode: room.mode, mentions })
const allSpeakers = addressedMembers(invite, members)
const doneBots = dispatchedBots?.get(record.seq)
Expand Down Expand Up @@ -8859,6 +8915,7 @@ export function install(rt) {
invite,
speakers: remainingSpeakers,
skipSpeakerIds: skipIds.size > 0 ? skipIds : undefined,
...(references !== undefined ? { references } : {}),
note,
})
}
Expand Down Expand Up @@ -8936,9 +8993,15 @@ export function install(rt) {
// Reconcile against native session events before re-dispatching so a crash between
// native `user/message` flush and ledger `supersede` flush never double-dispatches.
const liveRoomSession = agent?.session ?? liveSessionOf(rt.sessionOfRoom(room))
let roomSessionEvents
let roomSessionEventsReadable = false
if (typeof liveRoomSession?.snapshotEvents === 'function') {
await reconcileRoomLedgerWithSessionEvents(room, liveRoomSession.snapshotEvents(), { session: liveRoomSession })
roomSessionEvents = liveRoomSession.snapshotEvents()
roomSessionEventsReadable = true
await reconcileRoomLedgerWithSessionEvents(room, roomSessionEvents, { session: liveRoomSession })
} else if (cachedColdRoomEvidence !== undefined) {
roomSessionEvents = cachedColdRoomEvidence.events
roomSessionEventsReadable = true
await reconcileRoomLedgerWithSessionEvents(
room,
cachedColdRoomEvidence.events,
Expand All @@ -8950,11 +9013,15 @@ export function install(rt) {
try {
const evidence = await rt.readSessionEvidence(roomSid, AbortSignal.timeout(2_000), { preferPersisted: true })
if (evidence?.status === 'ok' && Array.isArray(evidence.events)) {
roomSessionEvents = evidence.events
roomSessionEventsReadable = evidence.persisted === true
await reconcileRoomLedgerWithSessionEvents(
room,
evidence.events,
evidence.persisted === true ? { persistedEvents: evidence.events } : {},
)
} else if (evidence?.status === 'not_found') {
roomSessionEventsReadable = true
} else if (evidence?.status === 'error') {
rt.warn?.('ds-bot: deferring room ledger recovery for %s because room session evidence is unreadable: %s', room.id, evidence.error?.message ?? evidence.error ?? 'error')
schedulePendingRoomLedgerRetry(room.id)
Expand All @@ -8971,7 +9038,8 @@ export function install(rt) {
clearPendingRoomLedgerRetry(room.id)
return 0
}
const beforeMemberCheck = pendingRoomLedgerDispatches(room)
const refsByIdentity = collectRoomSessionReferences(roomSessionEvents)
const beforeMemberCheck = pendingRoomLedgerDispatches(room, { refsByIdentity })
if (beforeMemberCheck.length === 0) {
if (hasPendingRoomLedgerWork(room)) {
schedulePendingRoomLedgerRetry(room.id)
Expand All @@ -8992,7 +9060,17 @@ export function install(rt) {
}
// Re-read pending dispatches synchronously right before `trackRecoveredDispatches` (zero awaits
// between snapshot and claim) so concurrent callers can never double-dispatch the same seq.
let pending = pendingRoomLedgerDispatches(room)
let pending = pendingRoomLedgerDispatches(room, { refsByIdentity })
let hasMissingReferences = false
if (!roomSessionEventsReadable && pending.length > 0) {
pending = pending.filter((item) => {
if (item.record.hasReferences === true && item.references === undefined) {
hasMissingReferences = true
return false
}
return true
})
}
const liveRoomAgent = agent ?? ctx.get?.('agents')?.get?.(rt.sessionOfRoom(room))
if (liveRoomAgent?.status === 'running' && pending.length > 0) {
const claimedRoomSeqs = sessionClaimedSeqs.get(room.id)
Expand Down Expand Up @@ -9023,7 +9101,7 @@ export function install(rt) {
return { ...item, speakers, skipSpeakerIds }
}).filter(Boolean)
}
const hasDeferred = unknownBySeq.size > 0 || claimedBySeq.size > 0 || hasUnpersistedRoomSupersedes(room.id) || failedRoomLedgerHandovers.has(room.id) || pendingColdRoomReconstructions.has(room.id)
const hasDeferred = hasMissingReferences || unknownBySeq.size > 0 || claimedBySeq.size > 0 || hasUnpersistedRoomSupersedes(room.id) || failedRoomLedgerHandovers.has(room.id) || pendingColdRoomReconstructions.has(room.id)
if (hasDeferred) {
schedulePendingRoomLedgerRetry(room.id)
} else if (pending.length === 0 && !inFlightRecoveredDispatches.has(room.id)) {
Expand All @@ -9038,20 +9116,35 @@ export function install(rt) {
}
}
ensureRoomLog(room)
const pendingSeqSet = new Set(pending.map(item => item.record.seq))
const running = runningRound(room.id)
const canJoinRunning = running !== undefined && !running.starting && !running.closed && !running.abort?.signal.aborted
let batch
if (canJoinRunning) {
// Messages carrying session references require their own round (just like `joinRound`),
// so they never contaminate an active round's members with another message's references.
batch = running.kickoff ? [] : pending.filter(item => item.references === undefined)
} else if (pending.length > 1 && pending.some(item => item.references !== undefined)) {
const firstRefAt = pending.findIndex(item => item.references !== undefined)
batch = firstRefAt === 0 ? [pending[0]] : pending.slice(0, firstRefAt)
} else {
batch = pending
}
if (batch.length < pending.length) schedulePendingRoomLedgerRetry(room.id)
if (batch.length === 0) return 0
const batchSeqSet = new Set(batch.map(item => item.record.seq))
const currentRoomInbox = rt.roomInbox.get(room.id)
if (Array.isArray(currentRoomInbox) && currentRoomInbox.length > 0 && liveRoomAgent?.status !== 'running') {
const keptInbox = currentRoomInbox.filter((post) => {
if (post?.botId !== undefined) return true
const matched = findMatchingRoomLedgerDispatchRecord(room.id, { inboxId: post?.messageId, rpcId: post?.rpcId })
return !(matched !== undefined && pendingSeqSet.has(matched.seq))
return !(matched !== undefined && batchSeqSet.has(matched.seq))
})
if (keptInbox.length !== currentRoomInbox.length) {
if (keptInbox.length > 0) rt.roomInbox.set(room.id, keptInbox)
else rt.roomInbox.delete(room.id)
}
}
for (const { record } of pending) {
for (const { record } of batch) {
const alreadyInLog = room.log.some(line => (
line.seq === record.seq
|| (typeof record.rpcId === 'string' && record.rpcId !== '' && line.rpcId === record.rpcId)
Expand All @@ -9065,22 +9158,23 @@ export function install(rt) {
}
if (Number.isInteger(record.seq) && record.seq > room.seq) room.seq = record.seq
}
const seqs = pending.map(item => item.record.seq)
const seqs = batch.map(item => item.record.seq)
trackRecoveredDispatches(room.id, seqs)
let handedOff = false
try {
const recoveredPosts = pending.map(({ record, skipSpeakerIds }) => ({
const recoveredPosts = batch.map(({ record, skipSpeakerIds, references }) => ({
logged: record.seq,
text: record.text ?? '',
...(record.via ? { via: record.via } : {}),
...(record.files !== undefined ? { files: record.files } : {}),
...(references !== undefined ? { references } : {}),
...(typeof record.rpcId === 'string' && record.rpcId !== '' ? { rpcId: record.rpcId } : {}),
...(typeof record.messageId === 'string' && record.messageId !== '' ? { messageId: record.messageId } : {}),
ledgerDispatchSeq: record.seq,
...(skipSpeakerIds !== undefined ? { skipSpeakerIds } : {}),
}))
const running = runningRound(room.id)
if (running !== undefined && !running.starting && !running.closed && !running.abort?.signal.aborted) {
for (const item of pending) {
if (canJoinRunning) {
for (const item of batch) {
running.userIdentities ??= new Set()
for (const key of roomIdentityKeysOf({ inboxId: item.record.messageId, rpcId: item.record.rpcId })) running.userIdentities.add(key)
callIn(running, item.speakers, item.note, undefined, {
Expand Down Expand Up @@ -9112,16 +9206,22 @@ export function install(rt) {
clearPendingRoomLedgerRetry(room.id)
}
}
return pending.length
return batch.length
}
if (finalizing.has(room.id) || running !== undefined) {
laterPosts.set(room.id, [...(laterPosts.get(room.id) ?? []), ...recoveredPosts])
const existingLater = laterPosts.get(room.id) ?? []
const hasAnyRefs = recoveredPosts.some(post => post.references !== undefined) || existingLater.some(post => (post?.references?.length ?? 0) > 0)
if (hasAnyRefs && (existingLater.length > 0 || recoveredPosts.length > 1)) {
schedulePendingRoomLedgerRetry(room.id)
return 0
}
laterPosts.set(room.id, [...existingLater, ...recoveredPosts])
handedOff = true
return pending.length
return batch.length
}
startRound(room, recoveredPosts, agent)
handedOff = true
return pending.length
return batch.length
} finally {
if (!handedOff) {
untrackRecoveredDispatches(room.id, seqs)
Expand Down
Loading
Loading