compaction-loop-repro.spec.ts 17 KB

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