compact-loop-repro.spec.ts 15 KB

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