compact-loop-repro.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { toolPairingBalancedAfter, toolPairingBalancedBefore } from '@deepseek-ai/dsh-compact'
  4. import { CONTEXT_WINDOW_EXCEEDED_CODE, LlmError } from '@deepseek-ai/dsh-llm'
  5. import type { ContentBlock, GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
  6. import { CallId, LlmAdapter } from '@deepseek-ai/dsh-llm'
  7. import { defineTool } from '@deepseek-ai/dsh-tools'
  8. import type { Agent } from '@deepseek-ai/dsh-agent'
  9. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  10. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  11. import * as Invariants from '@deepseek-ai/dsh-invariants'
  12. import { BasicCompactService } from '@deepseek-ai/dsh-compact-basic'
  13. import TokenMeterService from '@deepseek-ai/dsh-token-meter'
  14. import { SessionId, type SurfaceEvent } from '@deepseek-ai/dsh-session'
  15. /**
  16. * CBR-001 regression through the real loop. A replacement checkpoint has a high
  17. * log seq at the surface head and carries no tool pair, so both adjacent cuts
  18. * must be safe and re-compacting that checkpoint alone must succeed. This pins
  19. * surface-position semantics rather than raw-log scanning.
  20. */
  21. class ReproCompactService extends BasicCompactService {
  22. override async summarize(): Promise<{ summary: ContentBlock[]; provider: string; model: string }> {
  23. return {
  24. summary: [{ type: 'text', text: 'CHECKPOINT SUMMARY' }],
  25. provider: 'mock',
  26. model: 'stub',
  27. }
  28. }
  29. }
  30. /** Each call emits one tool-call until exhausted, then a final text answer. */
  31. class StepwiseToolAdapter extends LlmAdapter {
  32. calls = 0
  33. constructor(private toolSteps: number) {
  34. super()
  35. }
  36. async * stream(_options: GenerateOptions): AsyncIterable<StreamChunk> {
  37. const n = this.calls
  38. this.calls += 1
  39. if (n < this.toolSteps) {
  40. const id = CallId(`c${n}`)
  41. const args = `{"i":${n}}`
  42. yield { type: 'block-start', index: 0, blockType: 'text' }
  43. yield { type: 'block-end', index: 0, block: { type: 'text', text: `step ${n}` } }
  44. yield { type: 'block-start', index: 1, blockType: 'tool-call' }
  45. yield { type: 'block-end', index: 1, block: { type: 'tool-call', id, name: 'work', arguments: args } }
  46. yield { type: 'finish', reason: { kind: 'tool-calls' } }
  47. return
  48. }
  49. yield { type: 'block-start', index: 0, blockType: 'text' }
  50. yield { type: 'block-end', index: 0, block: { type: 'text', text: 'all done' } }
  51. yield { type: 'finish', reason: { kind: 'stop' } }
  52. }
  53. }
  54. /** First conversation request overflows, then the rebuilt retry succeeds. */
  55. class OverflowRecoveryAdapter extends LlmAdapter {
  56. readonly conversationRequests: GenerateOptions[] = []
  57. readonly summaryRequests: GenerateOptions[] = []
  58. constructor(private readonly delivery: 'thrown' | 'in-band') {
  59. super()
  60. }
  61. override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  62. if (options.system?.includes('You are a compaction engine')) {
  63. this.summaryRequests.push(options)
  64. yield { type: 'block-start', index: 0, blockType: 'text' }
  65. yield { type: 'block-end', index: 0, block: { type: 'text', text: 'RECOVERY CHECKPOINT' } }
  66. yield { type: 'finish', reason: { kind: 'stop' } }
  67. return
  68. }
  69. this.conversationRequests.push(options)
  70. if (this.conversationRequests.length === 1) {
  71. if (this.delivery === 'thrown') {
  72. throw new LlmError('request too large for model context', CONTEXT_WINDOW_EXCEEDED_CODE)
  73. }
  74. yield {
  75. type: 'finish',
  76. reason: {
  77. kind: 'error',
  78. message: 'request too large for model context',
  79. code: CONTEXT_WINDOW_EXCEEDED_CODE,
  80. },
  81. }
  82. return
  83. }
  84. yield { type: 'block-start', index: 0, blockType: 'text' }
  85. yield { type: 'block-end', index: 0, block: { type: 'text', text: 'recovered' } }
  86. yield { type: 'finish', reason: { kind: 'stop' } }
  87. }
  88. }
  89. async function harness(toolSteps: number): Promise<{ ctx: Context; compact: ReproCompactService }> {
  90. const ctx = new Context()
  91. await mountAgentLoopTestDependencies(ctx)
  92. await ctx.plugin(Invariants)
  93. await ctx.plugin(AgentLoop, { agents: [] })
  94. await ctx.plugin(TokenMeterService, { contextWindow: 400 })
  95. ctx.llm.registerAdapter(['mock'], new StepwiseToolAdapter(toolSteps))
  96. ctx.tools.register(defineTool({
  97. name: 'work',
  98. description: 'does work',
  99. parameters: { i: { type: 'number' } },
  100. async execute() {
  101. return [{ type: 'text', text: 'work result' }]
  102. },
  103. }))
  104. // Small window so several tool steps cross the threshold and compaction
  105. // fires within the runaway turn after enough history can shrink.
  106. const compact = new ReproCompactService(ctx, {
  107. auto: true,
  108. thresholdRatio: 0.5,
  109. retainTokens: 50,
  110. summarizationModel: '',
  111. maxTokens: 8192,
  112. compactionRetries: 1,
  113. })
  114. return { ctx, compact }
  115. }
  116. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  117. return new Promise((resolve) => {
  118. const dispose = ctx.on('agent/status', (subject, status) => {
  119. if (subject === agent && status === 'idle') {
  120. dispose()
  121. resolve()
  122. }
  123. })
  124. })
  125. }
  126. describe('CBR-001: a real-loop checkpoint is a valid boundary on both sides', () => {
  127. it('uses the model actually routed by agent/request for post-step pressure', async () => {
  128. const { ctx } = await harness(8)
  129. ctx.on('agent/request', async (_agent, _turn, _step, config) => ({ ...config, provider: 'mock', model: 'mock' }))
  130. try {
  131. const agent = ctx.agentLoop.create(SessionId('routed-pressure'), {
  132. provider: 'unconfigured-agent-fallback',
  133. model: 'unconfigured-agent-fallback',
  134. })
  135. agent.send([{ type: 'text', text: 'do a routed multi-step task' }])
  136. await waitForIdle(ctx, agent)
  137. expect(agent.session.requestHeader()?.config.model).toBe('mock')
  138. expect(agent.session.events.some(event => event.type === 'compact/summary')).toBe(true)
  139. expect(agent.session.events.at(-1)).toMatchObject({
  140. type: 'turn/end',
  141. data: { reason: { kind: 'completed' } },
  142. })
  143. } finally {
  144. await ctx.fiber.dispose()
  145. }
  146. })
  147. it('runs automatic pressure after the current tool result and before step/end', async () => {
  148. const { ctx } = await harness(8)
  149. try {
  150. const agent = ctx.agentLoop.create(SessionId('post-step-order'), { provider: 'mock', model: 'mock' })
  151. agent.send([{ type: 'text', text: 'do tool work' }])
  152. await waitForIdle(ctx, agent)
  153. const events = [...agent.session.events]
  154. const compactStart = events.find(event => event.type === 'compact/start')
  155. expect(compactStart).toBeDefined()
  156. const precedingResult = events.findLast(event =>
  157. event.type === 'tool/result' && event.seq < compactStart!.seq,
  158. )
  159. if (precedingResult?.type !== 'tool/result') throw new Error('expected a durable tool result before compaction')
  160. const stepEnd = events.find(event =>
  161. event.type === 'step/end'
  162. && event.data.step === precedingResult.data.step
  163. && event.seq > compactStart!.seq,
  164. )
  165. expect(precedingResult.seq).toBeLessThan(compactStart!.seq)
  166. expect(compactStart!.seq).toBeLessThan(stepEnd!.seq)
  167. } finally {
  168. await ctx.fiber.dispose()
  169. }
  170. })
  171. it('the head checkpoint the loop lands is a balanced cut on both sides', async () => {
  172. const { ctx } = await harness(8)
  173. try {
  174. const agent = ctx.agentLoop.create(SessionId('repro'), { provider: 'mock', model: 'mock' })
  175. agent.send([{ type: 'text', text: 'do a long multi-step task' }])
  176. await waitForIdle(ctx, agent)
  177. const events = [...agent.session.events]
  178. // A compaction ran: at least one checkpoint landed on the surface.
  179. const checkpoints = events.filter(
  180. (e): e is SurfaceEvent =>
  181. e.type === 'user/message'
  182. && typeof (e as SurfaceEvent).surfaceOp === 'object',
  183. )
  184. expect(checkpoints.length).toBeGreaterThan(0)
  185. // High log position does not make a text-only checkpoint mid-step; both
  186. // its start and end cuts are balanced in surface order.
  187. const nodes = agent.session.surface.nodes
  188. for (const cp of checkpoints) {
  189. const index = nodes.indexOf(cp.seq)
  190. if (index === -1) continue // shadowed by a later checkpoint — no longer an edge.
  191. expect(toolPairingBalancedBefore(agent.session, cp.seq),
  192. `checkpoint seq ${cp.seq} must be a balanced region START`).toBe(true)
  193. expect(toolPairingBalancedAfter(agent.session, cp.seq),
  194. `checkpoint seq ${cp.seq} must be a balanced region END`).toBe(true)
  195. }
  196. } finally {
  197. await ctx.fiber.dispose()
  198. }
  199. })
  200. })
  201. describe('context-overflow recovery across the real loop and compact-basic', () => {
  202. it.each(['thrown', 'in-band'] as const)(
  203. 'force-compacts a %s overflow between failed and retry steps',
  204. async (delivery) => {
  205. const ctx = new Context()
  206. const adapter = new OverflowRecoveryAdapter(delivery)
  207. await mountAgentLoopTestDependencies(ctx)
  208. await ctx.plugin(Invariants)
  209. await ctx.plugin(AgentLoop, { agents: [] })
  210. await ctx.plugin(TokenMeterService, { contextWindow: 128 })
  211. ctx.llm.registerAdapter(['mock'], adapter)
  212. ctx.on('agent/request', async (_agent, _turn, _step, config) => ({ ...config, provider: 'mock', model: 'mock' }))
  213. await ctx.plugin(BasicCompactService, {
  214. thresholdRatio: 1,
  215. retainTokens: 100,
  216. maxTokens: 64,
  217. compactionRetries: 0,
  218. maxOverflowRetries: 1,
  219. })
  220. try {
  221. const agent = ctx.agentLoop.create(SessionId(`overflow-${delivery}`), {
  222. provider: 'unconfigured-agent-fallback',
  223. model: 'unconfigured-agent-fallback',
  224. })
  225. for (let turn = 1; turn <= 2; turn += 1) {
  226. const sentinel = turn === 1 ? 'OLD HISTORY SENTINEL' : 'RECENT HISTORY'
  227. agent.session.append('turn/start', {
  228. turn,
  229. trigger: { kind: 'message', source: { kind: 'user' } },
  230. })
  231. agent.session.append('user/message', {
  232. content: [{ type: 'text', text: `${sentinel} ${'old context '.repeat(200)}` }],
  233. source: { kind: 'user' },
  234. }, { surfaceOp: 'append' })
  235. agent.session.append('step/start', { turn, step: 1 })
  236. agent.session.append('assistant/message', {
  237. provenance: { provider: 'mock', model: 'mock' },
  238. turn,
  239. step: 1,
  240. content: [{ type: 'text', text: `historical response ${turn} ${'detail '.repeat(200)}` }],
  241. }, { surfaceOp: 'append' })
  242. agent.session.append('step/end', { turn, step: 1 })
  243. agent.session.append('turn/end', { turn, reason: { kind: 'completed' } })
  244. }
  245. agent.send([{ type: 'text', text: 'continue from history' }])
  246. await agent.whenIdle()
  247. expect(adapter.conversationRequests).toHaveLength(2)
  248. expect(adapter.summaryRequests).toHaveLength(1)
  249. expect(JSON.stringify(adapter.conversationRequests[0]!.messages)).toContain('OLD HISTORY SENTINEL')
  250. const retry = JSON.stringify(adapter.conversationRequests[1]!.messages)
  251. expect(retry).toContain('RECOVERY CHECKPOINT')
  252. expect(retry).not.toContain('OLD HISTORY SENTINEL')
  253. const events = [...agent.session.events]
  254. const failedEnd = events.find(event =>
  255. event.type === 'step/end' && event.data.turn === 3 && event.data.step === 1,
  256. )!
  257. const retryStart = events.find(event =>
  258. event.type === 'step/start' && event.data.turn === 3 && event.data.step === 2,
  259. )!
  260. const compaction = events.filter(event =>
  261. event.type === 'compact/start'
  262. || event.type === 'compact/summary'
  263. || event.type === 'compact/end',
  264. )
  265. expect(compaction.map(event => event.type)).toEqual([
  266. 'compact/start',
  267. 'compact/summary',
  268. 'compact/end',
  269. ])
  270. expect(compaction.every(event => event.seq > failedEnd.seq && event.seq < retryStart.seq)).toBe(true)
  271. expect(events.at(-1)).toMatchObject({
  272. type: 'turn/end',
  273. data: { reason: { kind: 'completed' } },
  274. })
  275. } finally {
  276. await ctx.fiber.dispose()
  277. }
  278. },
  279. )
  280. })