compact-loop-repro.spec.ts 16 KB

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