fix(sidechat): swallow the keep window's leading inbox inserts (real-data e2e catch)

The real loop order writes a turn's inbox INSERT before its turn/start
and the CLAIM right after it; starting the keep window at the turn/start
kept the claim while dropping its insert, and the host's positional
durable-inbox fold rejected the seed at Session.create — caught on the
deployment's real main session during the v4 e2e re-run (thread creation
failed: invalid persisted inbox splice at session seq 7).

The keep start now swallows the contiguous agent/inbox/spliced events
preceding the skeleton root (they replay cleanly from an empty inbox),
and a new inboxSplicesValid gate mirrors the host's fold — positional
splice application with duplicate-id rejection — so any splice history
that cannot replay falls back to the full copy instead of shipping a
seed the host rejects. Pinned by a spec case in the real loop order.
This commit is contained in:
NolanHo authored and Atlas Zeng committed 2026-10-16 16:14:41 +08:00
1 parent 98c42971a2
commit b4e5c62f04
2 files changed
+84 -1

No files matched your search

+42 -1
View File
@@ -335,7 +335,13 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[]
}
const headEvents = headSkeleton(events, head)
if (headEvents === undefined) return undefined
const keepStart = enclosingTurnStart(events, keepFirst)
let keepStart = enclosingTurnStart(events, keepFirst)
// The loop writes a turn's inbox INSERT before its turn/start and the
// CLAIM right after it; starting the keep window at the turn/start would
// keep the claim while dropping its insert, and the host's positional
// inbox fold would reject the seed. Swallow the contiguous splices that
// precede the skeleton root — they replay cleanly from an empty inbox.
while (keepStart > 0 && events[keepStart - 1]?.type === 'agent/inbox/spliced') keepStart -= 1
const groupId = dataOf(events[cut - 1]!).compactionId
// The keep interval is a LOG range; the region may have ended mid-turn,
// so the interval can re-carry surface nodes the checkpoint already
@@ -435,9 +441,44 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[]
return undefined
}
if (!turnSequenceValid(seed)) return undefined
if (!inboxSplicesValid(seed)) return undefined
return seed
}
/**
* Relational pre-check mirroring the host's durable-inbox fold: every kept
* `agent/inbox/spliced` event replays POSITIONALLY over the pending inbox
* (splice.start/removedCount must stay in range, message ids unique). A
* seed whose splice history cannot replay from an empty inbox falls back
* to the full copy.
*/
function inboxSplicesValid(seed: readonly SeedEvent[]): boolean {
const nextTurn: Array<Record<string, unknown>> = []
const nextStep: Array<Record<string, unknown>> = []
for (const event of seed) {
if (event.type !== 'agent/inbox/spliced') continue
const data = dataOf(event)
const inbox = data.target === 'next-step' ? nextStep : nextTurn
const rawStart = data.start
const rawRemoved = data.removedCount
const removedCount = typeof rawRemoved === 'number' ? rawRemoved : 0
const inserted = Array.isArray(data.inserted) ? data.inserted as Array<Record<string, unknown>> : []
const start = typeof rawStart === 'number' ? rawStart : Number.NaN
if (!Number.isSafeInteger(start) || start < 0 || start > inbox.length
|| !Number.isSafeInteger(removedCount) || removedCount < 0
|| start + removedCount > inbox.length) return false
inbox.splice(start, removedCount, ...inserted)
const ids = new Set<string>()
for (const message of [...nextTurn, ...nextStep]) {
const id = message.id
if (typeof id !== 'string') continue
if (ids.has(id)) return false
ids.add(id)
}
}
return true
}
/**
* Relational pre-check mirroring the CORE of the session invariant's
* counters and tool pairing: turn numbers run 1, 2, … with no nested open
+42
View File
@@ -582,6 +582,48 @@ describe('buildSidechatInheritance compaction tail', () => {
expect(invariantFailures(seed)).toEqual([])
})
it('trims when the keep window opens on a turn whose inbox insert precedes its turn/start', () => {
// Real loop order: [insert q][turn/start][claim q][step/start][user].
// The keep window must swallow the insert ahead of the turn/start so
// the positional inbox fold replays; without it the claim dangles and
// Session.create rejects the seed (caught on the real deployment's
// main session during e2e).
const events = [...systemHead(), ...oldSpan().events]
const shadowTurn = turn(9, 2, { callId: 'c-shadow', result: 'shadow result' })
events.push(...shadowTurn.events)
const at = events.length
events.push(
lo('agent/inbox/spliced', at, { target: 'next-turn', start: 0, removedCount: 0, inserted: [userMessage('m-q3', 'q3')] }),
lo('turn/start', at + 1, { turn: 3 }),
lo('agent/inbox/spliced', at + 2, { target: 'next-turn', start: 0, removedCount: 1, inserted: [] }),
lo('step/start', at + 3, { turn: 3, step: 1 }),
sf('user/message', at + 4, userMessage('m-q3', 'q3')),
sf('assistant/message', at + 5, { turn: 3, step: 1, message: assistantMessage('a3'), stream: [] }),
lo('step/end', at + 6, { turn: 3, step: 1 }),
lo('turn/end', at + 7, { turn: 3, reason: { kind: 'completed' } }),
)
events.push(...compactionGroup(events.length, [3, 5, 6, 11, 13, 14]))
events.push(...turn(events.length, 4, { callId: 'c-tail', result: 'tail result' }).events)
const { seed, snapshot } = buildSidechatInheritance(events)
expect(snapshot).toBeNull()
expect(seed.length).toBeLessThan(events.length)
// The insert rode along ahead of the keep window's turn/start, so the
// claim finds its message and the inbox fold replays.
const splices = seed.filter(event => event.type === 'agent/inbox/spliced')
expect(splices.length).toBeGreaterThanOrEqual(2)
expect(visibleSequence(seed)).toEqual(visibleSequence(events))
expect(invariantFailures(seed)).toEqual([])
// The real validator accepts (this is the layer that rejected the
// pre-fix seed on the real session).
const id = 'session-inbox-splice-acceptance'
Session.create(
id as SessionId,
seed as never,
{ version: SESSION_FORMAT_VERSION, id: id as SessionId, createdAt: Date.now(), isSeeded: true },
SessionLogOffset(seed.length),
)
})
it('reuses the previous compaction when the newest summary is orphaned', () => {
const events = compactedLog()
const at = events.length