compact-loop-repro.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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, 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 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. constructor(
  66. private readonly delivery: 'thrown' | 'in-band',
  67. private readonly transientAfterOverflow = false,
  68. ) {
  69. super()
  70. }
  71. override resolveModelContext(): Promise<{ contextWindow: number }> {
  72. return Promise.resolve({ contextWindow: 128 })
  73. }
  74. override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  75. // The cache-reusing summarizer replays the conversation prefix and marks
  76. // its call only by the compaction instruction in the trailing user message.
  77. const trailing = options.messages.at(-1)?.content
  78. .map(block => (block.type === 'text' ? block.text : ''))
  79. .join('') ?? ''
  80. if (trailing.includes('acting as a compaction engine')) {
  81. this.summaryRequests.push(options)
  82. yield { type: 'block-start', index: 0, blockType: 'text' }
  83. yield { type: 'block-end', index: 0, block: { type: 'text', text: 'RECOVERY CHECKPOINT' } }
  84. yield { type: 'finish', reason: { kind: 'stop' } }
  85. return
  86. }
  87. this.conversationRequests.push(options)
  88. if (this.conversationRequests.length === 1) {
  89. if (this.delivery === 'thrown') {
  90. throw new LlmError('request too large for model context', CONTEXT_WINDOW_EXCEEDED_CODE)
  91. }
  92. yield {
  93. type: 'finish',
  94. reason: {
  95. kind: 'error',
  96. failure: {
  97. message: 'request too large for model context',
  98. code: CONTEXT_WINDOW_EXCEEDED_CODE,
  99. },
  100. },
  101. }
  102. return
  103. }
  104. if (this.transientAfterOverflow && this.conversationRequests.length === 2) {
  105. throw new LlmError('temporary provider outage', 'SERVER')
  106. }
  107. yield { type: 'block-start', index: 0, blockType: 'text' }
  108. yield { type: 'block-end', index: 0, block: { type: 'text', text: 'recovered' } }
  109. yield { type: 'finish', reason: { kind: 'stop' } }
  110. }
  111. }
  112. async function mountInvariants(ctx: Context): Promise<void> {
  113. await ctx.plugin(InvariantService)
  114. await ctx.plugin(SessionInvariant)
  115. await ctx.plugin(AgentInvariant)
  116. await ctx.plugin(AgentLoopInvariant)
  117. }
  118. async function harness(toolSteps: number): Promise<{ ctx: Context; compact: ReproCompactService }> {
  119. const ctx = new Context()
  120. await mountAgentLoopTestDependencies(ctx)
  121. await mountInvariants(ctx)
  122. await ctx.plugin(AgentLoop, { agents: [] })
  123. await ctx.plugin(TokenMeterService)
  124. ctx.llm.registerAdapter(['mock'], new StepwiseToolAdapter(toolSteps))
  125. ctx.tools.register(defineContentToolFixture({
  126. name: 'work',
  127. description: 'does work',
  128. parameters: { i: { type: 'number' } },
  129. async execute() {
  130. return [{ type: 'text', text: 'work result' }]
  131. },
  132. }))
  133. // Small window so several tool steps cross the threshold and compaction
  134. // fires within the runaway turn after enough history can shrink.
  135. const compact = new ReproCompactService(ctx, {
  136. auto: true,
  137. thresholdRatio: 0.5,
  138. retainTokens: 50,
  139. maxTokens: 8192,
  140. compactionRetries: 1,
  141. })
  142. return { ctx, compact }
  143. }
  144. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  145. return new Promise((resolve) => {
  146. const dispose = ctx.on('agent/status', (subject, status) => {
  147. if (subject === agent && status === 'idle') {
  148. dispose()
  149. resolve()
  150. }
  151. })
  152. })
  153. }
  154. function overflowHistorySeed(): SessionEvent[] {
  155. const session = new Session(SessionId('overflow-history-seed'))
  156. for (let turn = 1; turn <= 2; turn += 1) {
  157. const sentinel = turn === 1 ? 'OLD HISTORY SENTINEL' : 'RECENT HISTORY'
  158. session.append('turn/start', {
  159. turn,
  160. trigger: { kind: 'message', source: { kind: 'user' } },
  161. })
  162. session.append('user/message', {
  163. content: [{ type: 'text', text: `${sentinel} ${'old context '.repeat(200)}` }],
  164. source: { kind: 'user' },
  165. }, { surfaceOp: 'append' })
  166. session.append('step/start', { turn, step: 1 })
  167. session.append('assistant/message', {
  168. provenance: { provider: 'mock', model: 'mock' },
  169. turn,
  170. step: 1,
  171. content: [{ type: 'text', text: `historical response ${turn} ${'detail '.repeat(200)}` }],
  172. }, { surfaceOp: 'append' })
  173. session.append('step/end', { turn, step: 1 })
  174. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  175. }
  176. return [...session.events]
  177. }
  178. describe('CBR-001: a real-loop checkpoint is a valid boundary on both sides', () => {
  179. it('uses the model actually routed by agent/request for post-step pressure', async () => {
  180. const { ctx } = await harness(8)
  181. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => ({
  182. ...await next(), provider: 'mock', model: 'mock',
  183. }))
  184. try {
  185. const agent = ctx.agentLoop.create(SessionId('routed-pressure'), {
  186. provider: 'unconfigured-agent-fallback',
  187. model: 'unconfigured-agent-fallback',
  188. })
  189. agent.followup({ content: [{ type: 'text', text: 'do a routed multi-step task' }], source: { kind: 'user' } })
  190. await waitForIdle(ctx, agent)
  191. expect(agent.session.requestHeader()?.config.model).toBe('mock')
  192. expect(agent.session.events.some(event => event.type === 'compact/summary')).toBe(true)
  193. expect(agent.session.events.at(-1)).toMatchObject({
  194. type: 'turn/end',
  195. data: { reason: { kind: 'completed' } },
  196. })
  197. } finally {
  198. await ctx.fiber.dispose()
  199. }
  200. })
  201. it('runs automatic pressure between the completed tool step and the next step', async () => {
  202. const { ctx } = await harness(8)
  203. try {
  204. const agent = ctx.agentLoop.create(SessionId('post-step-order'), { provider: 'mock', model: 'mock' })
  205. agent.followup({ content: [{ type: 'text', text: 'do tool work' }], source: { kind: 'user' } })
  206. await waitForIdle(ctx, agent)
  207. const events = [...agent.session.events]
  208. const compactStart = events.find(event => event.type === 'compact/start')
  209. expect(compactStart).toBeDefined()
  210. const precedingResult = events.findLast(event =>
  211. event.type === 'tool/result' && event.seq < compactStart!.seq,
  212. )
  213. if (precedingResult?.type !== 'tool/result') throw new Error('expected a durable tool result before compaction')
  214. const precedingStepEnd = events.find(event =>
  215. event.type === 'step/end'
  216. && event.data.step === precedingResult.data.step
  217. && event.seq > precedingResult.seq,
  218. )
  219. const nextStepStart = events.find(event =>
  220. event.type === 'step/start'
  221. && event.data.step === precedingResult.data.step + 1
  222. && event.seq > compactStart!.seq,
  223. )
  224. expect(precedingResult.seq).toBeLessThan(compactStart!.seq)
  225. expect(precedingStepEnd!.seq).toBeLessThan(compactStart!.seq)
  226. expect(compactStart!.seq).toBeLessThan(nextStepStart!.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({ content: [{ type: 'text', text: 'do a long multi-step task' }], source: { kind: 'user' } })
  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, _signal, next) => ({
  273. ...await next(), provider: 'mock', model: 'mock',
  274. }))
  275. await ctx.plugin(BasicCompactService, {
  276. thresholdRatio: 1,
  277. retainTokens: 100,
  278. maxTokens: 64,
  279. compactionRetries: 0,
  280. maxOverflowRetries: 1,
  281. })
  282. try {
  283. const { agent } = await ctx.agentLoop.createAgent(ctx, {
  284. sessionId: SessionId(`overflow-${delivery}`),
  285. seed: overflowHistorySeed(),
  286. agentOptions: {
  287. provider: 'unconfigured-agent-fallback',
  288. model: 'unconfigured-agent-fallback',
  289. },
  290. })
  291. agent.followup({ content: [{ type: 'text', text: 'continue from history' }], source: { kind: 'user' } })
  292. await agent.whenIdle()
  293. expect(adapter.conversationRequests).toHaveLength(2)
  294. expect(adapter.summaryRequests).toHaveLength(1)
  295. expect(JSON.stringify(adapter.conversationRequests[0]!.messages)).toContain('OLD HISTORY SENTINEL')
  296. const retry = JSON.stringify(adapter.conversationRequests[1]!.messages)
  297. expect(retry).toContain('RECOVERY CHECKPOINT')
  298. expect(retry).not.toContain('OLD HISTORY SENTINEL')
  299. const events = [...agent.session.events]
  300. const failedStepEnd = events.find(event =>
  301. event.type === 'step/end' && event.data.turn === 3 && event.data.step === 1,
  302. )!
  303. const failedEnd = events.find(event =>
  304. event.type === 'turn/end' && event.data.turn === 3,
  305. )!
  306. const retryStart = events.find(event =>
  307. event.type === 'turn/start' && event.data.turn === 4,
  308. )!
  309. const retryStep = events.find(event =>
  310. event.type === 'step/start' && event.data.turn === 4 && event.data.step === 1,
  311. )!
  312. const compaction = events.filter(event =>
  313. event.type === 'compact/start'
  314. || event.type === 'compact/summary'
  315. || event.type === 'compact/end',
  316. )
  317. expect(compaction.map(event => event.type)).toEqual([
  318. 'compact/start',
  319. 'compact/summary',
  320. 'compact/end',
  321. ])
  322. expect(retryStart.seq).toBeGreaterThan(failedEnd.seq)
  323. expect(compaction.every(event =>
  324. event.seq > failedStepEnd.seq && event.seq < failedEnd.seq,
  325. )).toBe(true)
  326. expect(retryStep.seq).toBeGreaterThan(retryStart.seq)
  327. expect(events.at(-1)).toMatchObject({
  328. type: 'turn/end',
  329. data: { reason: { kind: 'completed' } },
  330. })
  331. } finally {
  332. await ctx.fiber.dispose()
  333. }
  334. },
  335. )
  336. it('keeps context-overflow and transient retry budgets independent in one sequence', async () => {
  337. const ctx = new Context()
  338. const adapter = new OverflowRecoveryAdapter('thrown', true)
  339. await mountAgentLoopTestDependencies(ctx)
  340. await mountInvariants(ctx)
  341. await ctx.plugin(LlmRetry, {
  342. maxTransientRetries: 1,
  343. initialDelayMs: 1,
  344. maxDelayMs: 1,
  345. jitterRatio: 0,
  346. })
  347. await ctx.plugin(AgentLoop, { agents: [] })
  348. await ctx.plugin(TokenMeterService)
  349. ctx.llm.registerAdapter(['mock'], adapter)
  350. await ctx.plugin(BasicCompactService, {
  351. thresholdRatio: 1,
  352. retainTokens: 100,
  353. maxTokens: 64,
  354. compactionRetries: 0,
  355. maxOverflowRetries: 1,
  356. })
  357. try {
  358. const { agent } = await ctx.agentLoop.createAgent(ctx, {
  359. sessionId: SessionId('alternating-recovery'),
  360. seed: overflowHistorySeed(),
  361. agentOptions: { provider: 'mock', model: 'mock' },
  362. })
  363. agent.followup({ content: [{ type: 'text', text: 'continue from history' }], source: { kind: 'user' } })
  364. await agent.whenIdle()
  365. expect(adapter.conversationRequests).toHaveLength(3)
  366. expect(adapter.summaryRequests).toHaveLength(1)
  367. expect(agent.session.events.filter(event => event.type === 'llm/retry').map(event => event.data))
  368. .toEqual([expect.objectContaining({ turn: 4, step: 1, retry: 1, failure: { message: 'temporary provider outage', code: 'SERVER' } })])
  369. expect(agent.session.events.filter(event => event.type === 'turn/start').slice(-3).map(event => event.data.turn))
  370. .toEqual([3, 4, 5])
  371. expect(agent.session.events.at(-1)).toMatchObject({
  372. type: 'turn/end',
  373. data: { reason: { kind: 'completed' } },
  374. })
  375. } finally {
  376. await ctx.fiber.dispose()
  377. }
  378. })
  379. })