compact-loop-repro.spec.ts 15 KB

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