compact-loop-repro.spec.ts 17 KB

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