compact-loop-repro.spec.ts 14 KB

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