compact-loop-repro.spec.ts 14 KB

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