compact-loop-repro.spec.ts 12 KB

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