compact-loop-repro.spec.ts 15 KB

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