compact-loop-repro.spec.ts 15 KB

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