compact-loop-repro.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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, resolveRetryPolicy } 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', {
  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. provenance: { provider: 'mock', model: 'mock' },
  187. turn,
  188. step: 1,
  189. content: [{ type: 'text', text: `historical response ${turn} ${'detail '.repeat(200)}` }],
  190. }, { surfaceOp: 'append' })
  191. session.append('step/end', { turn, step: 1 })
  192. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  193. }
  194. return [...session.events]
  195. }
  196. describe('CBR-001: a real-loop checkpoint is a valid boundary on both sides', () => {
  197. it('uses the model actually routed by agent/request for post-step pressure', async () => {
  198. const { ctx } = await harness(8)
  199. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => ({
  200. ...await next(), provider: 'mock', model: 'mock',
  201. }))
  202. try {
  203. const agent = ctx.agentLoop.create(SessionId('routed-pressure'), {
  204. provider: 'unconfigured-agent-fallback',
  205. model: 'unconfigured-agent-fallback',
  206. })
  207. agent.followup({ content: [{ type: 'text', text: 'do a routed multi-step task' }], source: { kind: 'user' } })
  208. await waitForIdle(ctx, agent)
  209. expect(agent.session.requestHeader()?.config.model).toBe('mock')
  210. expect(agent.session.events.some(event => event.type === 'compact/summary')).toBe(true)
  211. expect(agent.session.events.at(-1)).toMatchObject({
  212. type: 'turn/end',
  213. data: { reason: { kind: 'completed' } },
  214. })
  215. } finally {
  216. await ctx.fiber.dispose()
  217. }
  218. })
  219. it('runs automatic pressure between the completed tool step and the next step', async () => {
  220. const { ctx } = await harness(8)
  221. try {
  222. const agent = ctx.agentLoop.create(SessionId('post-step-order'), { provider: 'mock', model: 'mock' })
  223. agent.followup({ content: [{ type: 'text', text: 'do tool work' }], source: { kind: 'user' } })
  224. await waitForIdle(ctx, agent)
  225. const events = [...agent.session.events]
  226. const compactStart = events.find(event => event.type === 'compact/start')
  227. expect(compactStart).toBeDefined()
  228. const precedingResult = events.findLast(event =>
  229. event.type === 'tool/result' && event.seq < compactStart!.seq,
  230. )
  231. if (precedingResult?.type !== 'tool/result') throw new Error('expected a durable tool result before compaction')
  232. const precedingStepEnd = events.find(event =>
  233. event.type === 'step/end'
  234. && event.data.step === precedingResult.data.step
  235. && event.seq > precedingResult.seq,
  236. )
  237. const nextStepStart = events.find(event =>
  238. event.type === 'step/start'
  239. && event.data.step === precedingResult.data.step + 1
  240. && event.seq > compactStart!.seq,
  241. )
  242. expect(precedingResult.seq).toBeLessThan(compactStart!.seq)
  243. expect(precedingStepEnd!.seq).toBeLessThan(compactStart!.seq)
  244. expect(compactStart!.seq).toBeLessThan(nextStepStart!.seq)
  245. } finally {
  246. await ctx.fiber.dispose()
  247. }
  248. })
  249. it('the head checkpoint the loop lands is a balanced cut on both sides', async () => {
  250. const { ctx } = await harness(8)
  251. try {
  252. const agent = ctx.agentLoop.create(SessionId('repro'), { provider: 'mock', model: 'mock' })
  253. agent.followup({ content: [{ type: 'text', text: 'do a long multi-step task' }], source: { kind: 'user' } })
  254. await waitForIdle(ctx, agent)
  255. const events = [...agent.session.events]
  256. // A compaction ran: at least one checkpoint landed on the surface.
  257. const checkpoints = events.filter(
  258. (e): e is SurfaceEvent =>
  259. e.type === 'user/message'
  260. && typeof (e as SurfaceEvent).surfaceOp === 'object',
  261. )
  262. expect(checkpoints.length).toBeGreaterThan(0)
  263. // High log position does not make a text-only checkpoint mid-step; both
  264. // its start and end cuts are balanced in surface order.
  265. const nodes = agent.session.surface.nodes
  266. for (const cp of checkpoints) {
  267. const index = nodes.indexOf(cp.seq)
  268. if (index === -1) continue // shadowed by a later checkpoint — no longer an edge.
  269. expect(toolPairingBalancedBefore(agent.session, cp.seq),
  270. `checkpoint seq ${cp.seq} must be a balanced region START`).toBe(true)
  271. expect(toolPairingBalancedAfter(agent.session, cp.seq),
  272. `checkpoint seq ${cp.seq} must be a balanced region END`).toBe(true)
  273. }
  274. } finally {
  275. await ctx.fiber.dispose()
  276. }
  277. })
  278. })
  279. describe('context-overflow recovery across the real loop and compact-basic', () => {
  280. it.each(['thrown', 'in-band'] as const)(
  281. 'force-compacts a %s overflow between failed and retry steps',
  282. async (delivery) => {
  283. const ctx = new Context()
  284. const adapter = new OverflowRecoveryAdapter(delivery)
  285. await mountAgentLoopTestDependencies(ctx)
  286. await mountInvariants(ctx)
  287. await ctx.plugin(AgentLoop, { agents: [] })
  288. await ctx.plugin(TokenMeterService)
  289. ctx.llm.registerAdapter(['mock'], adapter)
  290. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => ({
  291. ...await next(), provider: 'mock', model: 'mock',
  292. }))
  293. await ctx.plugin(BasicCompactService, {
  294. thresholdRatio: 1,
  295. retainTokens: 100,
  296. maxTokens: 64,
  297. compactionRetries: 0,
  298. maxOverflowRetries: 1,
  299. })
  300. try {
  301. const { agent } = await ctx.agentLoop.createAgent(ctx, {
  302. sessionId: SessionId(`overflow-${delivery}`),
  303. seed: overflowHistorySeed(),
  304. agentOptions: {
  305. provider: 'unconfigured-agent-fallback',
  306. model: 'unconfigured-agent-fallback',
  307. },
  308. })
  309. agent.followup({ content: [{ type: 'text', text: 'continue from history' }], source: { kind: 'user' } })
  310. await agent.whenIdle()
  311. expect(adapter.conversationRequests).toHaveLength(2)
  312. expect(adapter.summaryRequests).toHaveLength(1)
  313. expect(JSON.stringify(adapter.conversationRequests[0]!.messages)).toContain('OLD HISTORY SENTINEL')
  314. const retry = JSON.stringify(adapter.conversationRequests[1]!.messages)
  315. expect(retry).toContain('RECOVERY CHECKPOINT')
  316. expect(retry).not.toContain('OLD HISTORY SENTINEL')
  317. const events = [...agent.session.events]
  318. const failedStepEnd = events.find(event =>
  319. event.type === 'step/end' && event.data.turn === 3 && event.data.step === 1,
  320. )!
  321. const failedEnd = events.find(event =>
  322. event.type === 'turn/end' && event.data.turn === 3,
  323. )!
  324. const retryStart = events.find(event =>
  325. event.type === 'turn/start' && event.data.turn === 4,
  326. )!
  327. const retryStep = events.find(event =>
  328. event.type === 'step/start' && event.data.turn === 4 && event.data.step === 1,
  329. )!
  330. const compaction = events.filter(event =>
  331. event.type === 'compact/start'
  332. || event.type === 'compact/summary'
  333. || event.type === 'compact/end',
  334. )
  335. expect(compaction.map(event => event.type)).toEqual([
  336. 'compact/start',
  337. 'compact/summary',
  338. 'compact/end',
  339. ])
  340. expect(retryStart.seq).toBeGreaterThan(failedEnd.seq)
  341. expect(compaction.every(event =>
  342. event.seq > failedStepEnd.seq && event.seq < failedEnd.seq,
  343. )).toBe(true)
  344. expect(retryStep.seq).toBeGreaterThan(retryStart.seq)
  345. expect(events.at(-1)).toMatchObject({
  346. type: 'turn/end',
  347. data: { reason: { kind: 'completed' } },
  348. })
  349. } finally {
  350. await ctx.fiber.dispose()
  351. }
  352. },
  353. )
  354. it('keeps context-overflow and transient retry budgets independent in one sequence', async () => {
  355. const ctx = new Context()
  356. const adapter = new OverflowRecoveryAdapter('thrown', true)
  357. await mountAgentLoopTestDependencies(ctx)
  358. await mountInvariants(ctx)
  359. await ctx.plugin(LlmRetry)
  360. await ctx.plugin(AgentLoop, { agents: [] })
  361. await ctx.plugin(TokenMeterService)
  362. ctx.llm.registerAdapter(['mock'], adapter)
  363. await ctx.plugin(BasicCompactService, {
  364. thresholdRatio: 1,
  365. retainTokens: 100,
  366. maxTokens: 64,
  367. compactionRetries: 0,
  368. maxOverflowRetries: 1,
  369. })
  370. try {
  371. const { agent } = await ctx.agentLoop.createAgent(ctx, {
  372. sessionId: SessionId('alternating-recovery'),
  373. seed: overflowHistorySeed(),
  374. agentOptions: { provider: 'mock', model: 'mock' },
  375. })
  376. agent.followup({ content: [{ type: 'text', text: 'continue from history' }], source: { kind: 'user' } })
  377. await agent.whenIdle()
  378. expect(adapter.conversationRequests).toHaveLength(3)
  379. expect(adapter.summaryRequests).toHaveLength(1)
  380. expect(agent.session.events.filter(event => event.type === 'llm/retry').map(event => event.data))
  381. .toEqual([expect.objectContaining({ turn: 4, step: 1, retry: 1, failure: { message: 'temporary provider outage', code: 'SERVER' } })])
  382. expect(agent.session.events.filter(event => event.type === 'turn/start').slice(-3).map(event => event.data.turn))
  383. .toEqual([3, 4, 5])
  384. expect(agent.session.events.at(-1)).toMatchObject({
  385. type: 'turn/end',
  386. data: { reason: { kind: 'completed' } },
  387. })
  388. } finally {
  389. await ctx.fiber.dispose()
  390. }
  391. })
  392. })