manual-compact.spec.ts 35 KB

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