manual-compaction.spec.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  4. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  5. import InvariantRegistry from '@deepseek-ai/dsh-invariants'
  6. import { CommandId } from '@deepseek-ai/dsh-commands/brand'
  7. import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant'
  8. import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant'
  9. import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant'
  10. import * as CompactionInvariant from '@deepseek-ai/dsh-compaction/invariant'
  11. import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic'
  12. import { CompactionId, isCompactCheckpointSource, ManualCompactionError } from '@deepseek-ai/dsh-compaction'
  13. import type { CompactionResult } from '@deepseek-ai/dsh-compaction'
  14. import {
  15. createAssistantMessage,
  16. createUserMessage,
  17. LlmAdapter,
  18. } from '@deepseek-ai/dsh-llm'
  19. import type {
  20. ContentBlock,
  21. LlmResolvedModelInfo,
  22. Message,
  23. StreamChunk,
  24. TokenUsage,
  25. } from '@deepseek-ai/dsh-llm'
  26. import SessionStore, { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
  27. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  28. import LlmRuntime from '@deepseek-ai/dsh-llm'
  29. import TokenMeter from '@deepseek-ai/dsh-token-meter'
  30. import type { Agent } from '@deepseek-ai/dsh-agent'
  31. import type {
  32. SummarizationInput,
  33. SummaryResult,
  34. } from '@deepseek-ai/dsh-compaction-basic/src/summarizer.ts'
  35. const MODEL = 'mock'
  36. const SIGNAL = new AbortController().signal
  37. const PROMPT = 'older conversation history '.repeat(60)
  38. /** A summarizer under test control: it can block, fail, or mutate mid-call. */
  39. class GatedCompactionEngine extends BasicCompactionEngine {
  40. summary: ContentBlock[] = [{ type: 'text', text: 'checkpoint' }]
  41. rawOutput: ContentBlock[] | undefined
  42. usage: TokenUsage | undefined
  43. error: unknown
  44. gate: Promise<undefined> | undefined
  45. duringSummary: (() => void) | undefined
  46. calls: SummarizationInput[] = []
  47. override async summarize(
  48. input: SummarizationInput,
  49. _agent: Agent,
  50. _signal?: AbortSignal,
  51. ): Promise<SummaryResult> {
  52. this.calls.push(input)
  53. this.duringSummary?.()
  54. if (this.gate !== undefined) await this.gate
  55. if (this.error !== undefined) throw this.error
  56. return {
  57. summary: this.summary,
  58. ...this.rawOutput === undefined ? {} : { rawOutput: this.rawOutput },
  59. provider: 'summary-provider',
  60. model: 'summary-model',
  61. ...this.usage === undefined ? {} : { usage: this.usage },
  62. }
  63. }
  64. }
  65. /** One text answer per request, with a context window large enough to avoid pressure. */
  66. class TextAdapter extends LlmAdapter {
  67. readonly requests: Message[][] = []
  68. override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
  69. return Promise.resolve({
  70. provider,
  71. id: model,
  72. name: model,
  73. context: { contextWindow: 100_000 },
  74. })
  75. }
  76. override async * stream(options: { messages: readonly Message[] }): AsyncIterable<StreamChunk> {
  77. this.requests.push([...options.messages])
  78. yield { type: 'block-start', index: 0, blockType: 'text' }
  79. yield { type: 'block-end', index: 0, block: { type: 'text', text: 'answer' } }
  80. yield { type: 'finish', reason: { kind: 'stop' } }
  81. }
  82. }
  83. interface LoopHarness {
  84. readonly ctx: Context
  85. readonly agent: Agent
  86. readonly compact: GatedCompactionEngine
  87. readonly adapter: TextAdapter
  88. readonly log: string[]
  89. }
  90. /** Real loop, session store, and invariant companions around manual compaction. */
  91. async function loopHarness(): Promise<LoopHarness> {
  92. const ctx = new Context()
  93. await mountAgentLoopTestDependencies(ctx)
  94. await ctx.plugin(InvariantRegistry)
  95. await ctx.plugin(SessionInvariant)
  96. await ctx.plugin(AgentInvariant)
  97. await ctx.plugin(AgentLoopInvariant)
  98. await ctx.plugin(CompactionInvariant)
  99. await ctx.plugin(AgentLoop, { agents: [] })
  100. await ctx.plugin(TokenMeter)
  101. const adapter = new TextAdapter()
  102. ctx.llm.registerAdapter([MODEL], adapter)
  103. const compact = new GatedCompactionEngine(ctx, { auto: false })
  104. const agent = await ctx.agentLoop.create(SessionId('manual-compact'), { provider: MODEL, model: MODEL })
  105. const log: string[] = []
  106. ctx.on('session/event', (_session, event) => {
  107. if (event.type === 'turn/start') log.push('turn/start')
  108. if (event.type === 'turn/end') log.push('turn/end')
  109. if (event.type === 'compaction/start') log.push(`compaction/start:${String(event.data.turn)}`)
  110. if (event.type === 'compaction/summary') log.push('compaction/summary')
  111. if (event.type === 'compaction/end') log.push(`compaction/end:${String(event.data.turn)}`)
  112. if (event.type === 'user/message') log.push('user/message')
  113. })
  114. ctx.on('session/flush', () => { log.push('flush') })
  115. return { ctx, agent, compact, adapter, log }
  116. }
  117. /** Drive one real turn so the closed history holds a compactable older span. */
  118. async function seedHistory(harness: LoopHarness): Promise<void> {
  119. harness.agent.followup(createUserMessage({
  120. content: [{ type: 'text', text: PROMPT }],
  121. source: { kind: 'user' },
  122. }))
  123. await harness.agent.whenIdle()
  124. harness.log.length = 0
  125. }
  126. /** Text of every derived model-visible message, in request order. */
  127. function derivedText(session: Session): string[] {
  128. return session.deriveMessages().map((message: Message) => message.content
  129. .map(block => block.type === 'text' ? block.text : '')
  130. .join(''))
  131. }
  132. /** Await one classified manual-compaction rejection. */
  133. async function rejection(operation: Promise<unknown> | (() => Promise<unknown>)): Promise<ManualCompactionError> {
  134. let caught: unknown
  135. try {
  136. const value = await (typeof operation === 'function' ? operation() : operation)
  137. throw new Error(`expected a rejection, resolved with ${String(value)}`)
  138. } catch (error: unknown) {
  139. caught = error
  140. }
  141. if (!(caught instanceof ManualCompactionError)) {
  142. throw new Error(`expected a ManualCompactionError, got ${String(caught)}`)
  143. }
  144. return caught
  145. }
  146. /** The Error a classified failure wraps. */
  147. function causeOf(error: ManualCompactionError): Error {
  148. const { cause } = error
  149. if (!(cause instanceof Error)) throw new Error(`expected an Error cause, got ${String(cause)}`)
  150. return cause
  151. }
  152. function deferred(): { promise: Promise<undefined>; resolve: () => void } {
  153. const { promise, resolve } = Promise.withResolvers<undefined>()
  154. return { promise, resolve: () => { resolve(undefined) } }
  155. }
  156. /** A closed-tail session with compactable exchanges and no live agent. */
  157. function closedConversation(turns = 2, lastTurnNumber = turns): Session {
  158. const session = Session.create(SessionId(`closed-${turns}-${lastTurnNumber}`))
  159. for (let index = 1; index <= turns; index += 1) {
  160. const turn = index === turns ? lastTurnNumber : index
  161. session.append('turn/start', { turn })
  162. session.append('user/message', createUserMessage({
  163. content: [{ type: 'text', text: `${PROMPT} ${turn}` }],
  164. source: { kind: 'user' },
  165. }), { surfaceOp: 'append' })
  166. session.append('step/start', { turn, step: 1 })
  167. if (index === 1) {
  168. session.append('request/header', {
  169. header: { config: { provider: MODEL, model: MODEL } },
  170. reason: 'initial',
  171. })
  172. }
  173. session.append('assistant/message', {
  174. stream: [],
  175. turn,
  176. step: 1,
  177. message: createAssistantMessage({
  178. content: [{ type: 'text', text: `answer ${turn}` }],
  179. source: { provider: MODEL, model: MODEL },
  180. }),
  181. }, { surfaceOp: 'append' })
  182. session.append('step/end', { turn, step: 1 })
  183. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  184. }
  185. return session
  186. }
  187. /** A fake idle agent whose maintenance claim is scripted per test. */
  188. function fakeAgent(
  189. session: Session,
  190. reserve: () => (() => void) | undefined,
  191. maintenanceSignal = new AbortController().signal,
  192. ): Agent {
  193. return {
  194. session,
  195. options: { provider: MODEL, model: MODEL },
  196. runMaintenance<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T> {
  197. const release = reserve()
  198. if (release === undefined) throw new Error('agent already has active work')
  199. return task(maintenanceSignal).finally(release)
  200. },
  201. } as unknown as Agent
  202. }
  203. /** Service over a store-detached session for failure classification. */
  204. function detachedService(): { ctx: Context; compact: GatedCompactionEngine; flushes: () => number } {
  205. const ctx = new Context()
  206. void new LlmRuntime(ctx)
  207. void new SessionStore(ctx)
  208. new SessionProjectionRegistry(ctx)
  209. void new TokenMeter(ctx)
  210. ctx.llm.registerAdapter([MODEL], new TextAdapter())
  211. let flushes = 0
  212. vi.spyOn(ctx.sessions, 'flush').mockImplementation(() => {
  213. flushes += 1
  214. return Promise.resolve(false)
  215. })
  216. return { ctx, compact: new GatedCompactionEngine(ctx, { auto: false }), flushes: () => flushes }
  217. }
  218. function compactEvents(session: Session): SessionEvent[] {
  219. return session.snapshotEvents().filter(event => event.type.startsWith('compaction/'))
  220. }
  221. describe('compactNow through the real loop', () => {
  222. it('holds a prompt accepted during summarization until the standalone bracket is flushed', async () => {
  223. const harness = await loopHarness()
  224. const { agent, compact, adapter, log } = harness
  225. await seedHistory(harness)
  226. const gate = deferred()
  227. compact.gate = gate.promise
  228. const running = compact.compactNow(agent, SIGNAL)
  229. await Promise.resolve()
  230. expect(log).toEqual(['compaction/start:null'])
  231. agent.followup(createUserMessage({
  232. content: [{ type: 'text', text: 'after compaction' }],
  233. source: { kind: 'user' },
  234. }))
  235. await new Promise<void>((resolve) => { setTimeout(resolve, 5) })
  236. expect(agent.status).toBe('idle')
  237. expect(adapter.requests).toHaveLength(1)
  238. expect(log).toEqual(['compaction/start:null'])
  239. gate.resolve()
  240. const result = await running
  241. expect(result).not.toBeNull()
  242. await agent.whenIdle()
  243. const start = log.indexOf('compaction/start:null')
  244. const summary = log.indexOf('compaction/summary')
  245. const end = log.indexOf('compaction/end:null')
  246. const flush = log.indexOf('flush')
  247. const nextTurn = log.indexOf('turn/start')
  248. expect(start).toBeLessThan(summary)
  249. expect(summary).toBeLessThan(end)
  250. expect(end).toBeLessThan(flush)
  251. expect(flush).toBeLessThan(nextTurn)
  252. expect(adapter.requests).toHaveLength(2)
  253. const second = (adapter.requests[1] ?? []).map(message => message.content
  254. .map(block => block.type === 'text' ? block.text : '')
  255. .join(''))
  256. expect(adapter.requests[1]?.[0]?.role).toBe('system')
  257. expect(second[1]).toContain('checkpoint')
  258. expect(second.at(-1)).toBe('after compaction')
  259. expect(second.some(text => text.includes(PROMPT))).toBe(false)
  260. })
  261. it('keeps context injected during summarization pending for the next step', async () => {
  262. const harness = await loopHarness()
  263. const { agent, compact } = harness
  264. await seedHistory(harness)
  265. compact.duringSummary = () => {
  266. agent.inject(createUserMessage({
  267. content: [{ type: 'text', text: 'INJECTED CONTEXT' }],
  268. source: { kind: 'plugin', plugin: 'test' },
  269. }))
  270. }
  271. const result = await compact.compactNow(agent, SIGNAL)
  272. expect(result).not.toBeNull()
  273. const start = agent.session.snapshotEvents().findLast(event => event.type === 'compaction/start')
  274. const injected = agent.inbox.nextStep.find(message =>
  275. message.source.kind === 'plugin' && message.source.plugin === 'test')
  276. const end = agent.session.snapshotEvents().findLast(event => event.type === 'compaction/end')
  277. expect(start).toBeDefined()
  278. expect(injected).toBeDefined()
  279. expect(end).toBeDefined()
  280. expect(agent.session.snapshotEvents().some(event => event.type === 'user/message'
  281. && event.data.id === injected?.id)).toBe(false)
  282. agent.followup(createUserMessage({
  283. content: [{ type: 'text', text: 'after compaction' }],
  284. source: { kind: 'user' },
  285. }))
  286. await agent.whenIdle()
  287. const messages = derivedText(agent.session)
  288. expect(agent.session.deriveMessages()[0]?.role).toBe('system')
  289. expect(messages[1]).toContain('checkpoint')
  290. expect(messages.filter(text => text.includes('INJECTED CONTEXT'))).toHaveLength(1)
  291. })
  292. it('keeps the marker order when listeners attempt a re-entrant injection', async () => {
  293. const harness = await loopHarness()
  294. const { ctx, agent, compact } = harness
  295. await seedHistory(harness)
  296. const attempts: string[] = []
  297. ctx.on('session/event', (_session, event) => {
  298. if (event.type !== 'compaction/start' && event.type !== 'compaction/summary') return
  299. attempts.push(event.type)
  300. agent.inject(createUserMessage({
  301. content: [{ type: 'text', text: `from ${event.type}` }],
  302. source: { kind: 'plugin', plugin: 'listener' },
  303. }))
  304. })
  305. const result = await compact.compactNow(agent, SIGNAL)
  306. expect(attempts).toEqual(['compaction/start', 'compaction/summary'])
  307. expect(result).not.toBeNull()
  308. expect(agent.session.deriveMessages()[0]?.role).toBe('system')
  309. expect(derivedText(agent.session)[1]).toContain('checkpoint')
  310. expect(agent.session.snapshotEvents().filter(event => event.type === 'user/message'
  311. && event.data.source.kind === 'plugin' && event.data.source.plugin === 'listener')).toHaveLength(0)
  312. const types = compactEvents(agent.session).map(event => event.type)
  313. expect(types).toEqual(['compaction/start', 'compaction/summary', 'compaction/end'])
  314. })
  315. it('reports busy without summarizing when a prompt already owns the next turn', async () => {
  316. const harness = await loopHarness()
  317. const { agent, compact, adapter } = harness
  318. await seedHistory(harness)
  319. agent.followup(createUserMessage({
  320. content: [{ type: 'text', text: 'first in line' }],
  321. source: { kind: 'user' },
  322. }))
  323. expect((await rejection(() => compact.compactNow(agent, SIGNAL))).code).toBe('busy')
  324. expect(compact.calls).toHaveLength(0)
  325. await agent.whenIdle()
  326. expect(adapter.requests).toHaveLength(2)
  327. expect(agent.session.snapshotEvents().some(event => event.type === 'compaction/start')).toBe(false)
  328. })
  329. it('releases turn admission after a summarizer failure and records the failed attempt', async () => {
  330. const harness = await loopHarness()
  331. const { agent, compact, adapter } = harness
  332. await seedHistory(harness)
  333. compact.error = new Error('summarizer unavailable')
  334. const before = [...agent.session.surface.nodes]
  335. expect((await rejection(compact.compactNow(agent, SIGNAL))).code).toBe('summary')
  336. expect(agent.session.surface.nodes).toEqual(before)
  337. const markers = compactEvents(agent.session)
  338. expect(markers.map(event => event.type)).toEqual(['compaction/start', 'compaction/end'])
  339. expect(markers[1]?.type === 'compaction/end' && markers[1].data.error)
  340. .toContain('summarizer unavailable')
  341. agent.followup(createUserMessage({
  342. content: [{ type: 'text', text: 'runs after the failure' }],
  343. source: { kind: 'user' },
  344. }))
  345. await agent.whenIdle()
  346. expect(adapter.requests).toHaveLength(2)
  347. })
  348. })
  349. describe('compactNow transaction and failure classification', () => {
  350. it('returns null without writing a bracket for history that cannot be compacted', async () => {
  351. const { compact } = detachedService()
  352. const session = Session.create(SessionId('empty'))
  353. let released = 0
  354. const agent = fakeAgent(session, () => () => { released += 1 })
  355. expect(await compact.compactNow(agent, SIGNAL)).toBeNull()
  356. expect(released).toBe(1)
  357. expect(compact.calls).toHaveLength(0)
  358. expect(compactEvents(session)).toEqual([])
  359. })
  360. it('commits a standalone bracket without consuming a turn number and checkpoints durability', async () => {
  361. const { compact, flushes } = detachedService()
  362. const session = closedConversation(2, 7)
  363. const agent = fakeAgent(session, () => () => undefined)
  364. const commandId = CommandId('manual-compact-command')
  365. const result = await compact.compactNow(agent, SIGNAL, commandId)
  366. expect(result).not.toBeNull()
  367. expect(result?.sourceCommandId).toBe(commandId)
  368. expect(flushes()).toBe(1)
  369. expect(session.snapshotEvents().filter(event => event.type === 'turn/start').at(-1)?.data.turn).toBe(7)
  370. const start = session.snapshotEvents().findLast(event => event.type === 'compaction/start')
  371. const summaryEvent = session.snapshotEvents().findLast(event => event.type === 'compaction/summary')
  372. const checkpoint = session.snapshotEvents().findLast(
  373. (event): event is SessionEvent<'user/message'> => event.type === 'user/message'
  374. && isCompactCheckpointSource(event.data.source),
  375. )
  376. const end = session.snapshotEvents().findLast(event => event.type === 'compaction/end')
  377. const correlated = { compactionId: result?.compactionId, sourceCommandId: commandId }
  378. expect(start?.data).toEqual({ ...correlated, turn: null })
  379. expect(summaryEvent?.data.sourceCommandId).toBe(commandId)
  380. expect(checkpoint?.data.source).toMatchObject(correlated)
  381. expect(end?.data).toEqual({ ...correlated, turn: null })
  382. })
  383. it('reports a live unmatched bracket as busy without summarizing', async () => {
  384. const { compact } = detachedService()
  385. const session = closedConversation(2)
  386. session.append('compaction/start', {
  387. compactionId: CompactionId('live-manual-compaction'),
  388. turn: null,
  389. })
  390. const agent = fakeAgent(session, () => () => undefined)
  391. const error = await rejection(() => compact.compactNow(agent, SIGNAL))
  392. expect(error.code).toBe('busy')
  393. expect(error.message).toContain('compaction lock is already active')
  394. expect(compact.calls).toHaveLength(0)
  395. })
  396. it('ignores an unmatched bracket inherited before a later end-seed marker', async () => {
  397. const { compact } = detachedService()
  398. const original = closedConversation(2)
  399. original.append('compaction/start', {
  400. compactionId: CompactionId('stale-manual-compaction'),
  401. turn: null,
  402. })
  403. const reloaded = Session.create(SessionId('stale-orphan'), original.snapshotEvents())
  404. const boundary = reloaded.snapshotEvents().findLast(event => event.type === 'session/end-seed')
  405. const orphan = reloaded.snapshotEvents().find(event => event.type === 'compaction/start')
  406. const agent = fakeAgent(reloaded, () => () => undefined)
  407. expect(boundary?.seq).toBeGreaterThan(orphan?.seq ?? Number.MAX_SAFE_INTEGER)
  408. await expect(compact.compactNow(agent, SIGNAL)).resolves.not.toBeNull()
  409. expect(compact.calls).toHaveLength(1)
  410. })
  411. it('scans a stale orphan independently of later repaired turn state', async () => {
  412. const { compact } = detachedService()
  413. const original = closedConversation(2)
  414. original.append('compaction/start', {
  415. compactionId: CompactionId('reloaded-manual-compaction'),
  416. turn: null,
  417. })
  418. original.append('turn/start', { turn: 3 })
  419. original.append('turn/end', { turn: 3, reason: { kind: 'interrupted' } })
  420. const reloaded = Session.create(SessionId('reloaded-orphan'), original.snapshotEvents())
  421. const agent = fakeAgent(reloaded, () => () => undefined)
  422. await expect(compact.compactNow(agent, SIGNAL)).resolves.not.toBeNull()
  423. expect(compact.calls).toHaveLength(1)
  424. })
  425. it('refuses an open turn in the log', async () => {
  426. const { compact } = detachedService()
  427. const session = closedConversation(2)
  428. session.append('turn/start', { turn: 3 })
  429. const agent = fakeAgent(session, () => () => undefined)
  430. const error = await rejection(compact.compactNow(agent, SIGNAL))
  431. expect(error.code).toBe('busy')
  432. expect(error.message).toContain('already has an open turn')
  433. })
  434. it('reports busy and skips summarization when admission is unavailable', async () => {
  435. const { compact } = detachedService()
  436. const agent = fakeAgent(closedConversation(2), () => undefined)
  437. expect((await rejection(() => compact.compactNow(agent, SIGNAL))).code).toBe('busy')
  438. expect(compact.calls).toHaveLength(0)
  439. })
  440. it('rejects a selected span replaced during summarization and records an error close', async () => {
  441. const { compact, flushes } = detachedService()
  442. const session = closedConversation(2)
  443. let released = 0
  444. const agent = fakeAgent(session, () => () => { released += 1 })
  445. compact.duringSummary = () => {
  446. const [head] = session.surface.nodes
  447. session.append('user/message', createUserMessage({
  448. content: [{ type: 'text', text: 'competing replacement' }],
  449. source: { kind: 'plugin', plugin: 'rival' },
  450. }), {
  451. surfaceOp: { op: 'replace', startSeq: head!, endSeq: head! },
  452. sourceEventSeqs: [head!],
  453. })
  454. }
  455. expect((await rejection(compact.compactNow(agent, SIGNAL))).code).toBe('changed')
  456. expect(released).toBe(1)
  457. expect(flushes()).toBe(1)
  458. expect(compactEvents(session).map(event => event.type)).toEqual(['compaction/start', 'compaction/end'])
  459. })
  460. it('rejects a selected span whose middle node was replaced during summarization', async () => {
  461. const { compact } = detachedService()
  462. const session = closedConversation(3)
  463. const agent = fakeAgent(session, () => () => undefined)
  464. compact.duringSummary = () => {
  465. const middle = session.surface.nodes[1]
  466. session.append('user/message', createUserMessage({
  467. content: [{ type: 'text', text: 'rewritten middle node' }],
  468. source: { kind: 'plugin', plugin: 'rival' },
  469. }), {
  470. surfaceOp: { op: 'replace', startSeq: middle!, endSeq: middle! },
  471. sourceEventSeqs: [middle!],
  472. })
  473. }
  474. const error = await rejection(compact.compactNow(agent, SIGNAL))
  475. expect(error.code).toBe('changed')
  476. expect(causeOf(error).message).toContain('span changed during summarization')
  477. })
  478. it('revalidates the selected span after the summarizer continuation settles', async () => {
  479. const { compact, flushes } = detachedService()
  480. const session = closedConversation(2)
  481. const gate = deferred()
  482. compact.gate = gate.promise
  483. let released = 0
  484. const agent = fakeAgent(session, () => () => { released += 1 })
  485. const head = session.surface.nodes[0]!
  486. const generation = session.surface.replaceGeneration
  487. const running = compact.compactNow(agent, SIGNAL)
  488. await Promise.resolve()
  489. expect(compact.calls).toHaveLength(1)
  490. gate.resolve()
  491. queueMicrotask(() => {
  492. queueMicrotask(() => {
  493. session.append('user/message', createUserMessage({
  494. content: [{ type: 'text', text: 'late competing replacement' }],
  495. source: { kind: 'plugin', plugin: 'rival' },
  496. }), {
  497. surfaceOp: { op: 'replace', startSeq: head, endSeq: head },
  498. sourceEventSeqs: [head],
  499. })
  500. })
  501. })
  502. const error = await rejection(running)
  503. expect(error.code).toBe('changed')
  504. expect(causeOf(error).message).toContain('selected span')
  505. expect(released).toBe(1)
  506. expect(flushes()).toBe(1)
  507. expect(session.surface.replaceGeneration).toBe(generation + 1)
  508. expect(session.surface.nodes).not.toContain(head)
  509. expect(compactEvents(session).map(event => event.type)).toEqual(['compaction/start', 'compaction/end'])
  510. expect(session.snapshotEvents().some(event => event.type === 'user/message'
  511. && isCompactCheckpointSource(event.data.source))).toBe(false)
  512. })
  513. it('classifies a failing compaction/end as commit failure and leaves one orphan', async () => {
  514. const { compact, flushes } = detachedService()
  515. const session = closedConversation(2)
  516. const agent = fakeAgent(session, () => () => undefined)
  517. const append = session.append.bind(session)
  518. vi.spyOn(session, 'append').mockImplementation(((type: string, ...rest: never[]) => {
  519. if (type === 'compaction/end') throw new Error('boundary rejected')
  520. return (append as (...args: never[]) => unknown)(type as never, ...rest)
  521. }) as never)
  522. const error = await rejection(compact.compactNow(agent, SIGNAL))
  523. expect(error.code).toBe('commit')
  524. expect(causeOf(error).message).toBe('boundary rejected')
  525. vi.restoreAllMocks()
  526. expect(flushes()).toBe(0)
  527. expect(session.snapshotEvents().findLast(event => event.type.startsWith('compaction/'))?.type)
  528. .toBe('compaction/summary')
  529. expect(compactEvents(session).filter(event => event.type === 'compaction/start')).toHaveLength(1)
  530. const calls = compact.calls.length
  531. expect((await rejection(compact.compactNow(agent, SIGNAL))).code).toBe('busy')
  532. expect(compact.calls).toHaveLength(calls)
  533. })
  534. it('keeps a failed error-close as the commit failure and does not flush', async () => {
  535. const { compact, flushes } = detachedService()
  536. const session = closedConversation(2)
  537. let released = 0
  538. const agent = fakeAgent(session, () => () => { released += 1 })
  539. compact.error = new Error('summary rejected')
  540. const append = session.append.bind(session)
  541. vi.spyOn(session, 'append').mockImplementation(((type: string, ...rest: never[]) => {
  542. if (type === 'compaction/end') throw new Error('error boundary rejected')
  543. return (append as (...args: never[]) => unknown)(type as never, ...rest)
  544. }) as never)
  545. const error = await rejection(compact.compactNow(agent, SIGNAL))
  546. vi.restoreAllMocks()
  547. expect(error.code).toBe('commit')
  548. expect(causeOf(error).message).toBe('error boundary rejected')
  549. expect(released).toBe(1)
  550. expect(flushes()).toBe(0)
  551. expect(compactEvents(session).map(event => event.type)).toEqual(['compaction/start'])
  552. })
  553. it('rejects a selected span whose pricing changed during summarization', async () => {
  554. const { ctx, compact } = detachedService()
  555. const session = closedConversation(2)
  556. const agent = fakeAgent(session, () => () => undefined)
  557. const meter = ctx.tokenMeter
  558. const original = meter.measure.bind(meter)
  559. compact.duringSummary = () => {
  560. vi.spyOn(meter, 'measure').mockImplementationOnce((target) => {
  561. const measurement = original(target)
  562. return {
  563. ...measurement,
  564. nodes: measurement.nodes.map((node, index) =>
  565. index === 0 ? { ...node, tokens: node.tokens + 1 } : node),
  566. }
  567. })
  568. }
  569. expect((await rejection(compact.compactNow(agent, SIGNAL))).code).toBe('changed')
  570. vi.restoreAllMocks()
  571. })
  572. it('classifies a commit-body failure and still releases admission', async () => {
  573. const { compact } = detachedService()
  574. const session = closedConversation(2)
  575. let released = 0
  576. const agent = fakeAgent(session, () => () => { released += 1 })
  577. const append = session.append.bind(session)
  578. vi.spyOn(session, 'append').mockImplementation(((type: string, ...rest: never[]) => {
  579. if (type === 'compaction/summary') throw new Error('summary record rejected')
  580. return (append as (...args: never[]) => unknown)(type as never, ...rest)
  581. }) as never)
  582. const error = await rejection(compact.compactNow(agent, SIGNAL))
  583. vi.restoreAllMocks()
  584. expect(error.code).toBe('commit')
  585. expect(released).toBe(1)
  586. const end = session.snapshotEvents().findLast(event => event.type === 'compaction/end')
  587. expect(end?.type === 'compaction/end' && end.data.error).toContain('summary record rejected')
  588. expect(end?.type === 'compaction/end' && end.data.turn).toBeNull()
  589. })
  590. it('keeps a commit failure when the durability checkpoint also fails', async () => {
  591. const { ctx, compact } = detachedService()
  592. const session = closedConversation(2)
  593. const agent = fakeAgent(session, () => () => undefined)
  594. const append = session.append.bind(session)
  595. vi.spyOn(session, 'append').mockImplementation(((type: string, ...rest: never[]) => {
  596. if (type === 'compaction/summary') throw new Error('summary record rejected')
  597. return (append as (...args: never[]) => unknown)(type as never, ...rest)
  598. }) as never)
  599. vi.spyOn(ctx.sessions, 'flush').mockRejectedValueOnce(new Error('disk full'))
  600. const error = await rejection(compact.compactNow(agent, SIGNAL))
  601. expect(error.code).toBe('commit')
  602. expect(causeOf(error).message).toBe('summary record rejected')
  603. vi.restoreAllMocks()
  604. })
  605. it('compacts a session with no durable turn boundary without creating one', async () => {
  606. const { compact } = detachedService()
  607. const session = Session.create(SessionId('turnless'))
  608. for (const text of [PROMPT, 'recent tail']) {
  609. session.append('user/message', createUserMessage({
  610. content: [{ type: 'text', text }],
  611. source: { kind: 'user' },
  612. }), { surfaceOp: 'append' })
  613. }
  614. const agent = fakeAgent(session, () => () => undefined)
  615. const result = await compact.compactNow(agent, SIGNAL)
  616. expect(result).not.toBeNull()
  617. expect(session.snapshotEvents().some(event => event.type === 'turn/start')).toBe(false)
  618. expect(session.snapshotEvents().find(event => event.type === 'compaction/start')?.data)
  619. .toEqual({ compactionId: result?.compactionId, turn: null })
  620. })
  621. it('classifies a durability failure after the standalone bracket committed', async () => {
  622. const { ctx, compact } = detachedService()
  623. const session = closedConversation(2)
  624. const agent = fakeAgent(session, () => () => undefined)
  625. vi.spyOn(ctx.sessions, 'flush').mockRejectedValueOnce(new Error('disk full'))
  626. expect((await rejection(compact.compactNow(agent, SIGNAL))).code).toBe('persistence')
  627. vi.restoreAllMocks()
  628. expect(session.snapshotEvents().some(event => event.type === 'compaction/summary')).toBe(true)
  629. const start = session.snapshotEvents().findLast(event => event.type === 'compaction/start')
  630. const end = session.snapshotEvents().findLast(event => event.type === 'compaction/end')
  631. expect(end?.data).toEqual({ compactionId: start?.data.compactionId, turn: null })
  632. })
  633. it('lets a pre-aborted signal win before reservation, measurement, or summarization', async () => {
  634. const cases = [
  635. { name: 'busy', session: closedConversation(2), release: undefined },
  636. { name: 'empty', session: Session.create(SessionId('pre-aborted-empty')), release: () => undefined },
  637. { name: 'compactable', session: closedConversation(2, 9), release: () => undefined },
  638. ] as const
  639. for (const testCase of cases) {
  640. const { ctx, compact } = detachedService()
  641. const reserve = vi.fn(() => testCase.release)
  642. const measure = vi.spyOn(ctx.tokenMeter, 'measure')
  643. const agent = fakeAgent(testCase.session, reserve)
  644. const before = testCase.session.snapshotEvents()
  645. const reason = Object.freeze({ kind: 'cancelled', case: testCase.name })
  646. const controller = new AbortController()
  647. controller.abort(reason)
  648. let thrown: unknown
  649. try {
  650. void compact.compactNow(agent, controller.signal)
  651. } catch (error: unknown) {
  652. thrown = error
  653. }
  654. expect(thrown).toBe(reason)
  655. expect(reserve).not.toHaveBeenCalled()
  656. expect(measure).not.toHaveBeenCalled()
  657. expect(compact.calls).toHaveLength(0)
  658. expect(testCase.session.snapshotEvents()).toEqual(before)
  659. vi.restoreAllMocks()
  660. }
  661. })
  662. it('preserves the exact cancellation reason when the summarizer also rejects', async () => {
  663. const { compact, flushes } = detachedService()
  664. const controller = new AbortController()
  665. const reason = new Error('cancelled by the caller')
  666. let released = 0
  667. const session = closedConversation(2)
  668. const agent = fakeAgent(session, () => () => { released += 1 })
  669. compact.duringSummary = () => { controller.abort(reason) }
  670. compact.error = new Error('summarizer aborted')
  671. await expect(compact.compactNow(agent, controller.signal)).rejects.toBe(reason)
  672. expect(released).toBe(1)
  673. expect(flushes()).toBe(1)
  674. const events = compactEvents(session)
  675. expect(events.map(event => event.type)).toEqual(['compaction/start', 'compaction/end'])
  676. expect(events[1]?.type === 'compaction/end' && events[1].data.error)
  677. .toContain('summarizer aborted')
  678. })
  679. it('classifies agent cancellation during maintenance as an expected cancellation', async () => {
  680. const { compact } = detachedService()
  681. const controller = new AbortController()
  682. const reason = new Error('agent cancelled maintenance')
  683. const session = closedConversation(2)
  684. const agent = fakeAgent(session, () => () => undefined, controller.signal)
  685. compact.duringSummary = () => { controller.abort(reason) }
  686. compact.error = new Error('summarizer observed cancellation')
  687. const error = await rejection(compact.compactNow(agent, SIGNAL))
  688. expect(error.code).toBe('cancelled')
  689. expect(error.cause).toBe(reason)
  690. })
  691. it('aborts before committing when cancellation lands after summarization', async () => {
  692. const { compact } = detachedService()
  693. const controller = new AbortController()
  694. const reason = new Error('cancelled by the caller')
  695. const session = closedConversation(2)
  696. const agent = fakeAgent(session, () => () => undefined)
  697. compact.duringSummary = () => { controller.abort(reason) }
  698. await expect(compact.compactNow(agent, controller.signal)).rejects.toBe(reason)
  699. expect(compactEvents(session).map(event => event.type)).toEqual(['compaction/start', 'compaction/end'])
  700. expect(session.snapshotEvents().some(event => event.type === 'compaction/summary')).toBe(false)
  701. })
  702. it('waits for the durability checkpoint before cancellation wins and admission releases', async () => {
  703. const { ctx, compact } = detachedService()
  704. const controller = new AbortController()
  705. const reason = new Error('cancelled during flush')
  706. const flushGate = Promise.withResolvers<boolean>()
  707. const flush = vi.spyOn(ctx.sessions, 'flush').mockReturnValueOnce(flushGate.promise)
  708. const session = closedConversation(2)
  709. let released = 0
  710. const agent = fakeAgent(session, () => () => { released += 1 })
  711. const running = compact.compactNow(agent, controller.signal)
  712. let settled = false
  713. void running.then(
  714. () => { settled = true },
  715. () => { settled = true },
  716. )
  717. await vi.waitFor(() => {
  718. expect(flush).toHaveBeenCalledWith(session)
  719. })
  720. controller.abort(reason)
  721. await Promise.resolve()
  722. expect(settled).toBe(false)
  723. expect(released).toBe(0)
  724. flushGate.resolve(false)
  725. await expect(running).rejects.toBe(reason)
  726. expect(released).toBe(1)
  727. })
  728. it('preserves raw output and usage in the manual summary event', async () => {
  729. const { compact } = detachedService()
  730. const session = closedConversation(2)
  731. const agent = fakeAgent(session, () => () => undefined)
  732. compact.rawOutput = [
  733. { type: 'text', text: 'checkpoint' },
  734. { type: 'reasoning', text: 'hidden reasoning' },
  735. ]
  736. compact.usage = { inputTokens: 40, outputTokens: 5 }
  737. await compact.compactNow(agent, SIGNAL)
  738. const summary = session.snapshotEvents().find(event => event.type === 'compaction/summary')
  739. expect(summary?.type === 'compaction/summary' && summary.data.rawOutput).toEqual(compact.rawOutput)
  740. expect(summary?.type === 'compaction/summary' && summary.data.usage).toEqual(compact.usage)
  741. })
  742. it('makes duration derivable from the opening and closing marker times', async () => {
  743. const { compact } = detachedService()
  744. const session = closedConversation(2)
  745. const agent = fakeAgent(session, () => () => undefined)
  746. compact.gate = new Promise<undefined>((resolve) => {
  747. setTimeout(() => { resolve(undefined) }, 5)
  748. })
  749. await compact.compactNow(agent, SIGNAL)
  750. const start = session.snapshotEvents().findLast(event => event.type === 'compaction/start')
  751. const end = session.snapshotEvents().findLast(event => event.type === 'compaction/end')
  752. expect(start).toBeDefined()
  753. expect(end).toBeDefined()
  754. expect(end!.time - start!.time).toBeGreaterThan(0)
  755. })
  756. it('excludes concurrent automatic and manual compaction of one session', async () => {
  757. const { compact } = detachedService()
  758. const session = closedConversation(3)
  759. const agent = fakeAgent(session, () => () => undefined)
  760. const gate = deferred()
  761. compact.gate = gate.promise
  762. const manual = compact.compactNow(agent, SIGNAL)
  763. await Promise.resolve()
  764. const nodes = session.surface.nodes
  765. await expect(compact.compactRegion(
  766. nodes[0]!,
  767. nodes[1]!,
  768. agent,
  769. )).rejects.toThrow('compaction lock is already active')
  770. gate.resolve()
  771. compact.gate = undefined
  772. const result: CompactionResult | null = await manual
  773. expect(result).not.toBeNull()
  774. })
  775. it('excludes a manual request while an explicit region compaction runs', async () => {
  776. const { compact } = detachedService()
  777. const session = closedConversation(3)
  778. session.append('turn/start', { turn: 4 })
  779. const agent = fakeAgent(session, () => () => undefined)
  780. const gate = deferred()
  781. compact.gate = gate.promise
  782. const nodes = session.surface.nodes
  783. const region = compact.compactRegion(nodes[0]!, nodes[1]!, agent)
  784. await Promise.resolve()
  785. expect((await rejection(compact.compactNow(agent, SIGNAL))).code).toBe('busy')
  786. gate.resolve()
  787. compact.gate = undefined
  788. await expect(region).resolves.toMatchObject({ shadowedSeqs: nodes.slice(0, 2) })
  789. })
  790. })