manual-compaction.spec.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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(second[0]).toContain('checkpoint')
  257. expect(second.at(-1)).toBe('after compaction')
  258. expect(second.some(text => text.includes(PROMPT))).toBe(false)
  259. })
  260. it('keeps context injected during summarization pending for the next step', async () => {
  261. const harness = await loopHarness()
  262. const { agent, compact } = harness
  263. await seedHistory(harness)
  264. compact.duringSummary = () => {
  265. agent.inject(createUserMessage({
  266. content: [{ type: 'text', text: 'INJECTED CONTEXT' }],
  267. source: { kind: 'plugin', plugin: 'test' },
  268. }))
  269. }
  270. const result = await compact.compactNow(agent, SIGNAL)
  271. expect(result).not.toBeNull()
  272. const start = agent.session.snapshotEvents().findLast(event => event.type === 'compaction/start')
  273. const injected = agent.inbox.nextStep.find(message =>
  274. message.source.kind === 'plugin' && message.source.plugin === 'test')
  275. const end = agent.session.snapshotEvents().findLast(event => event.type === 'compaction/end')
  276. expect(start).toBeDefined()
  277. expect(injected).toBeDefined()
  278. expect(end).toBeDefined()
  279. expect(agent.session.snapshotEvents().some(event => event.type === 'user/message'
  280. && event.data.id === injected?.id)).toBe(false)
  281. agent.followup(createUserMessage({
  282. content: [{ type: 'text', text: 'after compaction' }],
  283. source: { kind: 'user' },
  284. }))
  285. await agent.whenIdle()
  286. const messages = derivedText(agent.session)
  287. expect(messages[0]).toContain('checkpoint')
  288. expect(messages.filter(text => text.includes('INJECTED CONTEXT'))).toHaveLength(1)
  289. })
  290. it('keeps the marker order when listeners attempt a re-entrant injection', async () => {
  291. const harness = await loopHarness()
  292. const { ctx, agent, compact } = harness
  293. await seedHistory(harness)
  294. const attempts: string[] = []
  295. ctx.on('session/event', (_session, event) => {
  296. if (event.type !== 'compaction/start' && event.type !== 'compaction/summary') return
  297. attempts.push(event.type)
  298. agent.inject(createUserMessage({
  299. content: [{ type: 'text', text: `from ${event.type}` }],
  300. source: { kind: 'plugin', plugin: 'listener' },
  301. }))
  302. })
  303. const result = await compact.compactNow(agent, SIGNAL)
  304. expect(attempts).toEqual(['compaction/start', 'compaction/summary'])
  305. expect(result).not.toBeNull()
  306. expect(derivedText(agent.session)[0]).toContain('checkpoint')
  307. expect(agent.session.snapshotEvents().filter(event => event.type === 'user/message'
  308. && event.data.source.kind === 'plugin' && event.data.source.plugin === 'listener')).toHaveLength(0)
  309. const types = compactEvents(agent.session).map(event => event.type)
  310. expect(types).toEqual(['compaction/start', 'compaction/summary', 'compaction/end'])
  311. })
  312. it('reports busy without summarizing when a prompt already owns the next turn', async () => {
  313. const harness = await loopHarness()
  314. const { agent, compact, adapter } = harness
  315. await seedHistory(harness)
  316. agent.followup(createUserMessage({
  317. content: [{ type: 'text', text: 'first in line' }],
  318. source: { kind: 'user' },
  319. }))
  320. expect((await rejection(() => compact.compactNow(agent, SIGNAL))).code).toBe('busy')
  321. expect(compact.calls).toHaveLength(0)
  322. await agent.whenIdle()
  323. expect(adapter.requests).toHaveLength(2)
  324. expect(agent.session.snapshotEvents().some(event => event.type === 'compaction/start')).toBe(false)
  325. })
  326. it('releases turn admission after a summarizer failure and records the failed attempt', async () => {
  327. const harness = await loopHarness()
  328. const { agent, compact, adapter } = harness
  329. await seedHistory(harness)
  330. compact.error = new Error('summarizer unavailable')
  331. const before = [...agent.session.surface.nodes]
  332. expect((await rejection(compact.compactNow(agent, SIGNAL))).code).toBe('summary')
  333. expect(agent.session.surface.nodes).toEqual(before)
  334. const markers = compactEvents(agent.session)
  335. expect(markers.map(event => event.type)).toEqual(['compaction/start', 'compaction/end'])
  336. expect(markers[1]?.type === 'compaction/end' && markers[1].data.error)
  337. .toContain('summarizer unavailable')
  338. agent.followup(createUserMessage({
  339. content: [{ type: 'text', text: 'runs after the failure' }],
  340. source: { kind: 'user' },
  341. }))
  342. await agent.whenIdle()
  343. expect(adapter.requests).toHaveLength(2)
  344. })
  345. })
  346. describe('compactNow transaction and failure classification', () => {
  347. it('returns null without writing a bracket for history that cannot be compacted', async () => {
  348. const { compact } = detachedService()
  349. const session = Session.create(SessionId('empty'))
  350. let released = 0
  351. const agent = fakeAgent(session, () => () => { released += 1 })
  352. expect(await compact.compactNow(agent, SIGNAL)).toBeNull()
  353. expect(released).toBe(1)
  354. expect(compact.calls).toHaveLength(0)
  355. expect(compactEvents(session)).toEqual([])
  356. })
  357. it('commits a standalone bracket without consuming a turn number and checkpoints durability', async () => {
  358. const { compact, flushes } = detachedService()
  359. const session = closedConversation(2, 7)
  360. const agent = fakeAgent(session, () => () => undefined)
  361. const commandId = CommandId('manual-compact-command')
  362. const result = await compact.compactNow(agent, SIGNAL, commandId)
  363. expect(result).not.toBeNull()
  364. expect(result?.sourceCommandId).toBe(commandId)
  365. expect(flushes()).toBe(1)
  366. expect(session.snapshotEvents().filter(event => event.type === 'turn/start').at(-1)?.data.turn).toBe(7)
  367. const start = session.snapshotEvents().findLast(event => event.type === 'compaction/start')
  368. const summaryEvent = session.snapshotEvents().findLast(event => event.type === 'compaction/summary')
  369. const checkpoint = session.snapshotEvents().findLast(
  370. (event): event is SessionEvent<'user/message'> => event.type === 'user/message'
  371. && isCompactCheckpointSource(event.data.source),
  372. )
  373. const end = session.snapshotEvents().findLast(event => event.type === 'compaction/end')
  374. const correlated = { compactionId: result?.compactionId, sourceCommandId: commandId }
  375. expect(start?.data).toEqual({ ...correlated, turn: null })
  376. expect(summaryEvent?.data.sourceCommandId).toBe(commandId)
  377. expect(checkpoint?.data.source).toMatchObject(correlated)
  378. expect(end?.data).toEqual({ ...correlated, turn: null })
  379. })
  380. it('reports a live unmatched bracket as busy without summarizing', async () => {
  381. const { compact } = detachedService()
  382. const session = closedConversation(2)
  383. session.append('compaction/start', {
  384. compactionId: CompactionId('live-manual-compaction'),
  385. turn: null,
  386. })
  387. const agent = fakeAgent(session, () => () => undefined)
  388. const error = await rejection(() => compact.compactNow(agent, SIGNAL))
  389. expect(error.code).toBe('busy')
  390. expect(error.message).toContain('compaction lock is already active')
  391. expect(compact.calls).toHaveLength(0)
  392. })
  393. it('ignores an unmatched bracket inherited before a later end-seed marker', async () => {
  394. const { compact } = detachedService()
  395. const original = closedConversation(2)
  396. original.append('compaction/start', {
  397. compactionId: CompactionId('stale-manual-compaction'),
  398. turn: null,
  399. })
  400. const reloaded = Session.create(SessionId('stale-orphan'), original.snapshotEvents())
  401. const boundary = reloaded.snapshotEvents().findLast(event => event.type === 'session/end-seed')
  402. const orphan = reloaded.snapshotEvents().find(event => event.type === 'compaction/start')
  403. const agent = fakeAgent(reloaded, () => () => undefined)
  404. expect(boundary?.seq).toBeGreaterThan(orphan?.seq ?? Number.MAX_SAFE_INTEGER)
  405. await expect(compact.compactNow(agent, SIGNAL)).resolves.not.toBeNull()
  406. expect(compact.calls).toHaveLength(1)
  407. })
  408. it('scans a stale orphan independently of later repaired turn state', async () => {
  409. const { compact } = detachedService()
  410. const original = closedConversation(2)
  411. original.append('compaction/start', {
  412. compactionId: CompactionId('reloaded-manual-compaction'),
  413. turn: null,
  414. })
  415. original.append('turn/start', { turn: 3 })
  416. original.append('turn/end', { turn: 3, reason: { kind: 'interrupted' } })
  417. const reloaded = Session.create(SessionId('reloaded-orphan'), original.snapshotEvents())
  418. const agent = fakeAgent(reloaded, () => () => undefined)
  419. await expect(compact.compactNow(agent, SIGNAL)).resolves.not.toBeNull()
  420. expect(compact.calls).toHaveLength(1)
  421. })
  422. it('refuses an open turn in the log', async () => {
  423. const { compact } = detachedService()
  424. const session = closedConversation(2)
  425. session.append('turn/start', { turn: 3 })
  426. const agent = fakeAgent(session, () => () => undefined)
  427. const error = await rejection(compact.compactNow(agent, SIGNAL))
  428. expect(error.code).toBe('busy')
  429. expect(error.message).toContain('already has an open turn')
  430. })
  431. it('reports busy and skips summarization when admission is unavailable', async () => {
  432. const { compact } = detachedService()
  433. const agent = fakeAgent(closedConversation(2), () => undefined)
  434. expect((await rejection(() => compact.compactNow(agent, SIGNAL))).code).toBe('busy')
  435. expect(compact.calls).toHaveLength(0)
  436. })
  437. it('rejects a selected span replaced during summarization and records an error close', async () => {
  438. const { compact, flushes } = detachedService()
  439. const session = closedConversation(2)
  440. let released = 0
  441. const agent = fakeAgent(session, () => () => { released += 1 })
  442. compact.duringSummary = () => {
  443. const [head] = session.surface.nodes
  444. session.append('user/message', createUserMessage({
  445. content: [{ type: 'text', text: 'competing replacement' }],
  446. source: { kind: 'plugin', plugin: 'rival' },
  447. }), {
  448. surfaceOp: { op: 'replace', start: head!, end: head! },
  449. sourceEventSeqs: [head!],
  450. })
  451. }
  452. expect((await rejection(compact.compactNow(agent, SIGNAL))).code).toBe('changed')
  453. expect(released).toBe(1)
  454. expect(flushes()).toBe(1)
  455. expect(compactEvents(session).map(event => event.type)).toEqual(['compaction/start', 'compaction/end'])
  456. })
  457. it('rejects a selected span whose middle node was replaced during summarization', async () => {
  458. const { compact } = detachedService()
  459. const session = closedConversation(3)
  460. const agent = fakeAgent(session, () => () => undefined)
  461. compact.duringSummary = () => {
  462. const middle = session.surface.nodes[1]
  463. session.append('user/message', createUserMessage({
  464. content: [{ type: 'text', text: 'rewritten middle node' }],
  465. source: { kind: 'plugin', plugin: 'rival' },
  466. }), {
  467. surfaceOp: { op: 'replace', start: middle!, end: middle! },
  468. sourceEventSeqs: [middle!],
  469. })
  470. }
  471. const error = await rejection(compact.compactNow(agent, SIGNAL))
  472. expect(error.code).toBe('changed')
  473. expect(causeOf(error).message).toContain('span changed during summarization')
  474. })
  475. it('revalidates the selected span after the summarizer continuation settles', async () => {
  476. const { compact, flushes } = detachedService()
  477. const session = closedConversation(2)
  478. const gate = deferred()
  479. compact.gate = gate.promise
  480. let released = 0
  481. const agent = fakeAgent(session, () => () => { released += 1 })
  482. const head = session.surface.nodes[0]!
  483. const generation = session.surface.replaceGeneration
  484. const running = compact.compactNow(agent, SIGNAL)
  485. await Promise.resolve()
  486. expect(compact.calls).toHaveLength(1)
  487. gate.resolve()
  488. queueMicrotask(() => {
  489. queueMicrotask(() => {
  490. session.append('user/message', createUserMessage({
  491. content: [{ type: 'text', text: 'late competing replacement' }],
  492. source: { kind: 'plugin', plugin: 'rival' },
  493. }), {
  494. surfaceOp: { op: 'replace', start: head, end: head },
  495. sourceEventSeqs: [head],
  496. })
  497. })
  498. })
  499. const error = await rejection(running)
  500. expect(error.code).toBe('changed')
  501. expect(causeOf(error).message).toContain('selected span')
  502. expect(released).toBe(1)
  503. expect(flushes()).toBe(1)
  504. expect(session.surface.replaceGeneration).toBe(generation + 1)
  505. expect(session.surface.nodes).not.toContain(head)
  506. expect(compactEvents(session).map(event => event.type)).toEqual(['compaction/start', 'compaction/end'])
  507. expect(session.snapshotEvents().some(event => event.type === 'user/message'
  508. && isCompactCheckpointSource(event.data.source))).toBe(false)
  509. })
  510. it('classifies a failing compaction/end as commit failure and leaves one orphan', async () => {
  511. const { compact, flushes } = detachedService()
  512. const session = closedConversation(2)
  513. const agent = fakeAgent(session, () => () => undefined)
  514. const append = session.append.bind(session)
  515. vi.spyOn(session, 'append').mockImplementation(((type: string, ...rest: never[]) => {
  516. if (type === 'compaction/end') throw new Error('boundary rejected')
  517. return (append as (...args: never[]) => unknown)(type as never, ...rest)
  518. }) as never)
  519. const error = await rejection(compact.compactNow(agent, SIGNAL))
  520. expect(error.code).toBe('commit')
  521. expect(causeOf(error).message).toBe('boundary rejected')
  522. vi.restoreAllMocks()
  523. expect(flushes()).toBe(0)
  524. expect(session.snapshotEvents().findLast(event => event.type.startsWith('compaction/'))?.type)
  525. .toBe('compaction/summary')
  526. expect(compactEvents(session).filter(event => event.type === 'compaction/start')).toHaveLength(1)
  527. const calls = compact.calls.length
  528. expect((await rejection(compact.compactNow(agent, SIGNAL))).code).toBe('busy')
  529. expect(compact.calls).toHaveLength(calls)
  530. })
  531. it('keeps a failed error-close as the commit failure and does not flush', async () => {
  532. const { compact, flushes } = detachedService()
  533. const session = closedConversation(2)
  534. let released = 0
  535. const agent = fakeAgent(session, () => () => { released += 1 })
  536. compact.error = new Error('summary rejected')
  537. const append = session.append.bind(session)
  538. vi.spyOn(session, 'append').mockImplementation(((type: string, ...rest: never[]) => {
  539. if (type === 'compaction/end') throw new Error('error boundary rejected')
  540. return (append as (...args: never[]) => unknown)(type as never, ...rest)
  541. }) as never)
  542. const error = await rejection(compact.compactNow(agent, SIGNAL))
  543. vi.restoreAllMocks()
  544. expect(error.code).toBe('commit')
  545. expect(causeOf(error).message).toBe('error boundary rejected')
  546. expect(released).toBe(1)
  547. expect(flushes()).toBe(0)
  548. expect(compactEvents(session).map(event => event.type)).toEqual(['compaction/start'])
  549. })
  550. it('rejects a selected span whose pricing changed during summarization', async () => {
  551. const { ctx, compact } = detachedService()
  552. const session = closedConversation(2)
  553. const agent = fakeAgent(session, () => () => undefined)
  554. const meter = ctx.tokenMeter
  555. const original = meter.measure.bind(meter)
  556. compact.duringSummary = () => {
  557. vi.spyOn(meter, 'measure').mockImplementationOnce((target) => {
  558. const measurement = original(target)
  559. return {
  560. ...measurement,
  561. nodes: measurement.nodes.map((node, index) =>
  562. index === 0 ? { ...node, tokens: node.tokens + 1 } : node),
  563. }
  564. })
  565. }
  566. expect((await rejection(compact.compactNow(agent, SIGNAL))).code).toBe('changed')
  567. vi.restoreAllMocks()
  568. })
  569. it('classifies a commit-body failure and still releases admission', async () => {
  570. const { compact } = detachedService()
  571. const session = closedConversation(2)
  572. let released = 0
  573. const agent = fakeAgent(session, () => () => { released += 1 })
  574. const append = session.append.bind(session)
  575. vi.spyOn(session, 'append').mockImplementation(((type: string, ...rest: never[]) => {
  576. if (type === 'compaction/summary') throw new Error('summary record rejected')
  577. return (append as (...args: never[]) => unknown)(type as never, ...rest)
  578. }) as never)
  579. const error = await rejection(compact.compactNow(agent, SIGNAL))
  580. vi.restoreAllMocks()
  581. expect(error.code).toBe('commit')
  582. expect(released).toBe(1)
  583. const end = session.snapshotEvents().findLast(event => event.type === 'compaction/end')
  584. expect(end?.type === 'compaction/end' && end.data.error).toContain('summary record rejected')
  585. expect(end?.type === 'compaction/end' && end.data.turn).toBeNull()
  586. })
  587. it('keeps a commit failure when the durability checkpoint also fails', async () => {
  588. const { ctx, compact } = detachedService()
  589. const session = closedConversation(2)
  590. const agent = fakeAgent(session, () => () => undefined)
  591. const append = session.append.bind(session)
  592. vi.spyOn(session, 'append').mockImplementation(((type: string, ...rest: never[]) => {
  593. if (type === 'compaction/summary') throw new Error('summary record rejected')
  594. return (append as (...args: never[]) => unknown)(type as never, ...rest)
  595. }) as never)
  596. vi.spyOn(ctx.sessions, 'flush').mockRejectedValueOnce(new Error('disk full'))
  597. const error = await rejection(compact.compactNow(agent, SIGNAL))
  598. expect(error.code).toBe('commit')
  599. expect(causeOf(error).message).toBe('summary record rejected')
  600. vi.restoreAllMocks()
  601. })
  602. it('compacts a session with no durable turn boundary without creating one', async () => {
  603. const { compact } = detachedService()
  604. const session = Session.create(SessionId('turnless'))
  605. for (const text of [PROMPT, 'recent tail']) {
  606. session.append('user/message', createUserMessage({
  607. content: [{ type: 'text', text }],
  608. source: { kind: 'user' },
  609. }), { surfaceOp: 'append' })
  610. }
  611. const agent = fakeAgent(session, () => () => undefined)
  612. const result = await compact.compactNow(agent, SIGNAL)
  613. expect(result).not.toBeNull()
  614. expect(session.snapshotEvents().some(event => event.type === 'turn/start')).toBe(false)
  615. expect(session.snapshotEvents().find(event => event.type === 'compaction/start')?.data)
  616. .toEqual({ compactionId: result?.compactionId, turn: null })
  617. })
  618. it('classifies a durability failure after the standalone bracket committed', async () => {
  619. const { ctx, compact } = detachedService()
  620. const session = closedConversation(2)
  621. const agent = fakeAgent(session, () => () => undefined)
  622. vi.spyOn(ctx.sessions, 'flush').mockRejectedValueOnce(new Error('disk full'))
  623. expect((await rejection(compact.compactNow(agent, SIGNAL))).code).toBe('persistence')
  624. vi.restoreAllMocks()
  625. expect(session.snapshotEvents().some(event => event.type === 'compaction/summary')).toBe(true)
  626. const start = session.snapshotEvents().findLast(event => event.type === 'compaction/start')
  627. const end = session.snapshotEvents().findLast(event => event.type === 'compaction/end')
  628. expect(end?.data).toEqual({ compactionId: start?.data.compactionId, turn: null })
  629. })
  630. it('lets a pre-aborted signal win before reservation, measurement, or summarization', async () => {
  631. const cases = [
  632. { name: 'busy', session: closedConversation(2), release: undefined },
  633. { name: 'empty', session: Session.create(SessionId('pre-aborted-empty')), release: () => undefined },
  634. { name: 'compactable', session: closedConversation(2, 9), release: () => undefined },
  635. ] as const
  636. for (const testCase of cases) {
  637. const { ctx, compact } = detachedService()
  638. const reserve = vi.fn(() => testCase.release)
  639. const measure = vi.spyOn(ctx.tokenMeter, 'measure')
  640. const agent = fakeAgent(testCase.session, reserve)
  641. const before = testCase.session.snapshotEvents()
  642. const reason = Object.freeze({ kind: 'cancelled', case: testCase.name })
  643. const controller = new AbortController()
  644. controller.abort(reason)
  645. let thrown: unknown
  646. try {
  647. void compact.compactNow(agent, controller.signal)
  648. } catch (error: unknown) {
  649. thrown = error
  650. }
  651. expect(thrown).toBe(reason)
  652. expect(reserve).not.toHaveBeenCalled()
  653. expect(measure).not.toHaveBeenCalled()
  654. expect(compact.calls).toHaveLength(0)
  655. expect(testCase.session.snapshotEvents()).toEqual(before)
  656. vi.restoreAllMocks()
  657. }
  658. })
  659. it('preserves the exact cancellation reason when the summarizer also rejects', async () => {
  660. const { compact, flushes } = detachedService()
  661. const controller = new AbortController()
  662. const reason = new Error('cancelled by the caller')
  663. let released = 0
  664. const session = closedConversation(2)
  665. const agent = fakeAgent(session, () => () => { released += 1 })
  666. compact.duringSummary = () => { controller.abort(reason) }
  667. compact.error = new Error('summarizer aborted')
  668. await expect(compact.compactNow(agent, controller.signal)).rejects.toBe(reason)
  669. expect(released).toBe(1)
  670. expect(flushes()).toBe(1)
  671. const events = compactEvents(session)
  672. expect(events.map(event => event.type)).toEqual(['compaction/start', 'compaction/end'])
  673. expect(events[1]?.type === 'compaction/end' && events[1].data.error)
  674. .toContain('summarizer aborted')
  675. })
  676. it('classifies agent cancellation during maintenance as an expected cancellation', async () => {
  677. const { compact } = detachedService()
  678. const controller = new AbortController()
  679. const reason = new Error('agent cancelled maintenance')
  680. const session = closedConversation(2)
  681. const agent = fakeAgent(session, () => () => undefined, controller.signal)
  682. compact.duringSummary = () => { controller.abort(reason) }
  683. compact.error = new Error('summarizer observed cancellation')
  684. const error = await rejection(compact.compactNow(agent, SIGNAL))
  685. expect(error.code).toBe('cancelled')
  686. expect(error.cause).toBe(reason)
  687. })
  688. it('aborts before committing when cancellation lands after summarization', async () => {
  689. const { compact } = detachedService()
  690. const controller = new AbortController()
  691. const reason = new Error('cancelled by the caller')
  692. const session = closedConversation(2)
  693. const agent = fakeAgent(session, () => () => undefined)
  694. compact.duringSummary = () => { controller.abort(reason) }
  695. await expect(compact.compactNow(agent, controller.signal)).rejects.toBe(reason)
  696. expect(compactEvents(session).map(event => event.type)).toEqual(['compaction/start', 'compaction/end'])
  697. expect(session.snapshotEvents().some(event => event.type === 'compaction/summary')).toBe(false)
  698. })
  699. it('waits for the durability checkpoint before cancellation wins and admission releases', async () => {
  700. const { ctx, compact } = detachedService()
  701. const controller = new AbortController()
  702. const reason = new Error('cancelled during flush')
  703. const flushGate = Promise.withResolvers<boolean>()
  704. const flush = vi.spyOn(ctx.sessions, 'flush').mockReturnValueOnce(flushGate.promise)
  705. const session = closedConversation(2)
  706. let released = 0
  707. const agent = fakeAgent(session, () => () => { released += 1 })
  708. const running = compact.compactNow(agent, controller.signal)
  709. let settled = false
  710. void running.then(
  711. () => { settled = true },
  712. () => { settled = true },
  713. )
  714. await vi.waitFor(() => {
  715. expect(flush).toHaveBeenCalledWith(session)
  716. })
  717. controller.abort(reason)
  718. await Promise.resolve()
  719. expect(settled).toBe(false)
  720. expect(released).toBe(0)
  721. flushGate.resolve(false)
  722. await expect(running).rejects.toBe(reason)
  723. expect(released).toBe(1)
  724. })
  725. it('preserves raw output and usage in the manual summary event', async () => {
  726. const { compact } = detachedService()
  727. const session = closedConversation(2)
  728. const agent = fakeAgent(session, () => () => undefined)
  729. compact.rawOutput = [
  730. { type: 'text', text: 'checkpoint' },
  731. { type: 'reasoning', text: 'hidden reasoning' },
  732. ]
  733. compact.usage = { inputTokens: 40, outputTokens: 5 }
  734. await compact.compactNow(agent, SIGNAL)
  735. const summary = session.snapshotEvents().find(event => event.type === 'compaction/summary')
  736. expect(summary?.type === 'compaction/summary' && summary.data.rawOutput).toEqual(compact.rawOutput)
  737. expect(summary?.type === 'compaction/summary' && summary.data.usage).toEqual(compact.usage)
  738. })
  739. it('makes duration derivable from the opening and closing marker times', async () => {
  740. const { compact } = detachedService()
  741. const session = closedConversation(2)
  742. const agent = fakeAgent(session, () => () => undefined)
  743. compact.gate = new Promise<undefined>((resolve) => {
  744. setTimeout(() => { resolve(undefined) }, 5)
  745. })
  746. await compact.compactNow(agent, SIGNAL)
  747. const start = session.snapshotEvents().findLast(event => event.type === 'compaction/start')
  748. const end = session.snapshotEvents().findLast(event => event.type === 'compaction/end')
  749. expect(start).toBeDefined()
  750. expect(end).toBeDefined()
  751. expect(end!.time - start!.time).toBeGreaterThan(0)
  752. })
  753. it('excludes concurrent automatic and manual compaction of one session', async () => {
  754. const { compact } = detachedService()
  755. const session = closedConversation(3)
  756. const agent = fakeAgent(session, () => () => undefined)
  757. const gate = deferred()
  758. compact.gate = gate.promise
  759. const manual = compact.compactNow(agent, SIGNAL)
  760. await Promise.resolve()
  761. const nodes = session.surface.nodes
  762. await expect(compact.compactRegion(
  763. nodes[0]!,
  764. nodes[1]!,
  765. agent,
  766. )).rejects.toThrow('compaction lock is already active')
  767. gate.resolve()
  768. compact.gate = undefined
  769. const result: CompactionResult | null = await manual
  770. expect(result).not.toBeNull()
  771. })
  772. it('excludes a manual request while an explicit region compaction runs', async () => {
  773. const { compact } = detachedService()
  774. const session = closedConversation(3)
  775. session.append('turn/start', { turn: 4 })
  776. const agent = fakeAgent(session, () => () => undefined)
  777. const gate = deferred()
  778. compact.gate = gate.promise
  779. const nodes = session.surface.nodes
  780. const region = compact.compactRegion(nodes[0]!, nodes[1]!, agent)
  781. await Promise.resolve()
  782. expect((await rejection(compact.compactNow(agent, SIGNAL))).code).toBe('busy')
  783. gate.resolve()
  784. compact.gate = undefined
  785. await expect(region).resolves.toMatchObject({ shadowedSeqs: nodes.slice(0, 2) })
  786. })
  787. })