compaction-loop-repro.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import { toolPairingBalancedAfter, toolPairingBalancedBefore } from '@deepseek-ai/dsh-compaction'
  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 InvariantRegistry 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 { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic'
  16. import TokenMeter 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 ReproCompactionEngine extends BasicCompactionEngine {
  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(InvariantRegistry)
  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: ReproCompactionEngine }> {
  137. const ctx = new Context()
  138. await mountAgentLoopTestDependencies(ctx)
  139. await mountInvariants(ctx)
  140. await ctx.plugin(AgentLoop, { agents: [] })
  141. await ctx.plugin(TokenMeter)
  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 ReproCompactionEngine(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', ({ agent: subject, status }) => {
  165. if (subject === agent && status === 'idle') {
  166. dispose()
  167. resolve()
  168. }
  169. })
  170. })
  171. }
  172. function overflowHistorySeed(): SessionEvent[] {
  173. const session = Session.create(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. })
  179. session.append('user/message', createUserMessage({
  180. content: [{ type: 'text', text: `${sentinel} ${'old context '.repeat(200)}` }],
  181. source: { kind: 'user' },
  182. }), { surfaceOp: 'append' })
  183. session.append('step/start', { turn, step: 1 })
  184. session.append('assistant/message', {
  185. turn,
  186. step: 1,
  187. message: createMessage({
  188. role: 'assistant',
  189. content: [{ type: 'text', text: `historical response ${turn} ${'detail '.repeat(200)}` }],
  190. source: {
  191. kind: 'model',
  192. ...{ provider: 'mock', model: 'mock' },
  193. },
  194. }),
  195. }, { surfaceOp: 'append' })
  196. session.append('step/end', { turn, step: 1 })
  197. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  198. }
  199. return [...session.events]
  200. }
  201. describe('CBR-001: a real-loop checkpoint is a valid boundary on both sides', () => {
  202. it('uses the model actually routed by agent/request for post-step pressure', async () => {
  203. const { ctx } = await harness(8)
  204. ctx.on('agent/request', async (_payload, next) => ({
  205. ...await next(), provider: 'mock', model: 'mock',
  206. }))
  207. try {
  208. const agent = ctx.agentLoop.create(SessionId('routed-pressure'), {
  209. provider: 'unconfigured-agent-fallback',
  210. model: 'unconfigured-agent-fallback',
  211. })
  212. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'do a routed multi-step task' }], source: { kind: 'user' } }))
  213. await waitForIdle(ctx, agent)
  214. expect(agent.session.requestHeader()?.config.model).toBe('mock')
  215. expect(agent.session.events.some(event => event.type === 'compaction/summary')).toBe(true)
  216. expect(agent.session.events.at(-1)).toMatchObject({
  217. type: 'turn/end',
  218. data: { reason: { kind: 'completed' } },
  219. })
  220. } finally {
  221. await ctx.fiber.dispose()
  222. }
  223. })
  224. it('runs automatic pressure between the completed tool step and the next step', async () => {
  225. const { ctx } = await harness(8)
  226. try {
  227. const agent = ctx.agentLoop.create(SessionId('post-step-order'), { provider: 'mock', model: 'mock' })
  228. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'do tool work' }], source: { kind: 'user' } }))
  229. await waitForIdle(ctx, agent)
  230. const events = [...agent.session.events]
  231. const compactStart = events.find(event => event.type === 'compaction/start')
  232. expect(compactStart).toBeDefined()
  233. const precedingResult = events.findLast(event =>
  234. event.type === 'tool/result' && event.seq < compactStart!.seq,
  235. )
  236. if (precedingResult?.type !== 'tool/result') throw new Error('expected a durable tool result before compaction')
  237. const precedingStepEnd = events.find(event =>
  238. event.type === 'step/end'
  239. && event.data.step === precedingResult.data.step
  240. && event.seq > precedingResult.seq,
  241. )
  242. const nextStepStart = events.find(event =>
  243. event.type === 'step/start'
  244. && event.data.step === precedingResult.data.step + 1
  245. && event.seq > compactStart!.seq,
  246. )
  247. expect(precedingResult.seq).toBeLessThan(compactStart!.seq)
  248. expect(precedingStepEnd!.seq).toBeLessThan(compactStart!.seq)
  249. expect(compactStart!.seq).toBeLessThan(nextStepStart!.seq)
  250. } finally {
  251. await ctx.fiber.dispose()
  252. }
  253. })
  254. it('the head checkpoint the loop lands is a balanced cut on both sides', async () => {
  255. const { ctx } = await harness(8)
  256. try {
  257. const agent = ctx.agentLoop.create(SessionId('repro'), { provider: 'mock', model: 'mock' })
  258. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'do a long multi-step task' }], source: { kind: 'user' } }))
  259. await waitForIdle(ctx, agent)
  260. const events = [...agent.session.events]
  261. // A compaction ran: at least one checkpoint landed on the surface.
  262. const checkpoints = events.filter(
  263. (e): e is SurfaceEvent =>
  264. e.type === 'user/message'
  265. && typeof (e as SurfaceEvent).surfaceOp === 'object',
  266. )
  267. expect(checkpoints.length).toBeGreaterThan(0)
  268. // High log position does not make a text-only checkpoint mid-step; both
  269. // its start and end cuts are balanced in surface order.
  270. const nodes = agent.session.surface.nodes
  271. for (const cp of checkpoints) {
  272. const index = nodes.indexOf(cp.seq)
  273. if (index === -1) continue // shadowed by a later checkpoint — no longer an edge.
  274. expect(toolPairingBalancedBefore(agent.session, cp.seq),
  275. `checkpoint seq ${cp.seq} must be a balanced region START`).toBe(true)
  276. expect(toolPairingBalancedAfter(agent.session, cp.seq),
  277. `checkpoint seq ${cp.seq} must be a balanced region END`).toBe(true)
  278. }
  279. } finally {
  280. await ctx.fiber.dispose()
  281. }
  282. })
  283. })
  284. describe('context-overflow recovery across the real loop and compaction-basic', () => {
  285. it.each(['thrown', 'in-band'] as const)(
  286. 'force-compacts a %s overflow within the retried step',
  287. async (delivery) => {
  288. const ctx = new Context()
  289. const adapter = new OverflowRecoveryAdapter(delivery)
  290. await mountAgentLoopTestDependencies(ctx)
  291. await mountInvariants(ctx)
  292. await ctx.plugin(AgentLoop, { agents: [] })
  293. await ctx.plugin(TokenMeter)
  294. ctx.llm.registerAdapter(['mock'], adapter)
  295. ctx.on('agent/request', async (_payload, next) => ({
  296. ...await next(), provider: 'mock', model: 'mock',
  297. }))
  298. await ctx.plugin(BasicCompactionEngine, {
  299. thresholdRatio: 1,
  300. retainTokens: 100,
  301. maxTokens: 64,
  302. compactionRetries: 0,
  303. maxOverflowRetries: 1,
  304. })
  305. try {
  306. const { agent } = await ctx.agentLoop.createAgent(ctx, {
  307. sessionId: SessionId(`overflow-${delivery}`),
  308. seed: overflowHistorySeed(),
  309. agentOptions: {
  310. provider: 'unconfigured-agent-fallback',
  311. model: 'unconfigured-agent-fallback',
  312. },
  313. })
  314. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'continue from history' }], source: { kind: 'user' } }))
  315. await agent.whenIdle()
  316. expect(adapter.conversationRequests).toHaveLength(2)
  317. expect(adapter.summaryRequests).toHaveLength(1)
  318. const instruction = adapter.summaryRequests[0]!.messages.at(-1)?.content
  319. .map(block => (block.type === 'text' ? block.text : ''))
  320. .join('') ?? ''
  321. expect(instruction).toContain('Write concise English engineering prose.')
  322. expect(instruction).toContain('numeric values, function signatures, and syntax fragments.')
  323. expect(JSON.stringify(adapter.conversationRequests[0]!.messages)).toContain('OLD HISTORY SENTINEL')
  324. const retry = JSON.stringify(adapter.conversationRequests[1]!.messages)
  325. expect(retry).toContain('RECOVERY CHECKPOINT')
  326. expect(retry).not.toContain('OLD HISTORY SENTINEL')
  327. const events = [...agent.session.events]
  328. const stepStart = events.find(event =>
  329. event.type === 'step/start' && event.data.turn === 3 && event.data.step === 1,
  330. )!
  331. const stepEnd = events.find(event =>
  332. event.type === 'step/end' && event.data.turn === 3 && event.data.step === 1,
  333. )!
  334. const compaction = events.filter(event =>
  335. event.type === 'compaction/start'
  336. || event.type === 'compaction/summary'
  337. || event.type === 'compaction/end',
  338. )
  339. expect(compaction.map(event => event.type)).toEqual([
  340. 'compaction/start',
  341. 'compaction/summary',
  342. 'compaction/end',
  343. ])
  344. expect(compaction.every(event =>
  345. event.seq > stepStart.seq && event.seq < stepEnd.seq,
  346. )).toBe(true)
  347. expect(events.filter(event => event.type === 'turn/start').slice(-1).map(event => event.data.turn))
  348. .toEqual([3])
  349. expect(events.filter(event => event.type === 'step/start' && event.data.turn === 3))
  350. .toHaveLength(1)
  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(TokenMeter)
  368. ctx.llm.registerAdapter(['mock'], adapter)
  369. await ctx.plugin(BasicCompactionEngine, {
  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: 3, step: 1, retry: 1, failure: { message: 'temporary provider outage', code: 'SERVER' } })])
  388. expect(agent.session.events.filter(event => event.type === 'turn/start').slice(-1).map(event => event.data.turn))
  389. .toEqual([3])
  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. })