compact-loop-repro.spec.ts 14 KB

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