compact-loop-repro.spec.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService from '@deepseek-ai/dsh-llm'
  4. import type { ContentBlock, GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
  5. import { CallId, LlmAdapter } from '@deepseek-ai/dsh-llm'
  6. import SessionStore from '@deepseek-ai/dsh-session'
  7. import { isToolPairingBalanced } from '@deepseek-ai/dsh-session'
  8. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  9. import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
  10. import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent'
  11. import AgentExecutionProvider from '@deepseek-ai/dsh-agent-execution'
  12. import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  13. import * as Invariants from '@deepseek-ai/dsh-invariants'
  14. import { BasicCompactService } from '@deepseek-ai/dsh-compact-basic'
  15. import type { SurfaceEvent } from '@deepseek-ai/dsh-session'
  16. /**
  17. * CBR-001 regression through the real loop. A replacement checkpoint has a high
  18. * log seq at the surface head and carries no tool pair, so both adjacent cuts
  19. * must be safe and re-compacting that checkpoint alone must succeed. This pins
  20. * surface-position semantics rather than raw-log scanning.
  21. */
  22. const TOKENS_PER_BLOCK = 10
  23. class ReproCompactService extends BasicCompactService {
  24. override estimateContentTokens(blocks: readonly ContentBlock[]): number {
  25. return blocks.length * TOKENS_PER_BLOCK
  26. }
  27. override async summarize(): Promise<{ summary: ContentBlock[]; model: string }> {
  28. return { summary: [{ type: 'text', text: 'CHECKPOINT SUMMARY' }], model: 'stub' }
  29. }
  30. }
  31. /** Each call emits one tool-call until exhausted, then a final text answer. */
  32. class StepwiseToolAdapter extends LlmAdapter {
  33. calls = 0
  34. constructor(private toolSteps: number) {
  35. super()
  36. }
  37. async * stream(_options: GenerateOptions): AsyncIterable<StreamChunk> {
  38. const n = this.calls
  39. this.calls += 1
  40. if (n < this.toolSteps) {
  41. const id = CallId(`c${n}`)
  42. const args = `{"i":${n}}`
  43. yield { type: 'block-start', index: 0, blockType: 'text' }
  44. yield { type: 'block-end', index: 0, block: { type: 'text', text: `step ${n}` } }
  45. yield { type: 'block-start', index: 1, blockType: 'tool-call' }
  46. yield { type: 'block-end', index: 1, block: { type: 'tool-call', id, name: 'work', arguments: args } }
  47. yield { type: 'finish', reason: { kind: 'tool-calls' } }
  48. return
  49. }
  50. yield { type: 'block-start', index: 0, blockType: 'text' }
  51. yield { type: 'block-end', index: 0, block: { type: 'text', text: 'all done' } }
  52. yield { type: 'finish', reason: { kind: 'stop' } }
  53. }
  54. }
  55. async function harness(toolSteps: number): Promise<{ ctx: Context; compact: ReproCompactService }> {
  56. const ctx = new Context()
  57. await ctx.plugin(LlmService)
  58. await ctx.plugin(SessionStore)
  59. await ctx.plugin(Invariants)
  60. await ctx.plugin(SystemPrompt)
  61. await ctx.plugin(ToolRegistry)
  62. await ctx.plugin(AgentRegistry)
  63. await ctx.plugin(AgentExecutionProvider)
  64. await ctx.plugin(AgentLoop, { agents: [] })
  65. ctx.llm.registerAdapter(['mock'], new StepwiseToolAdapter(toolSteps))
  66. ctx.tools.register(defineTool({
  67. name: 'work',
  68. description: 'does work',
  69. parameters: { i: { type: 'number' } },
  70. async execute() {
  71. return [{ type: 'text', text: 'work result' }]
  72. },
  73. }))
  74. // Tiny window so a couple of tool steps cross the threshold and compaction
  75. // fires within the runaway turn.
  76. const compact = new ReproCompactService(ctx, {
  77. auto: true,
  78. contextWindow: 64,
  79. thresholdRatio: 0.5,
  80. retainTokens: 20,
  81. summarizationModel: '',
  82. maxTokens: 8192,
  83. compactionRetries: 1,
  84. })
  85. return { ctx, compact }
  86. }
  87. function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  88. return new Promise((resolve) => {
  89. const dispose = ctx.on('agent/status', (subject, status) => {
  90. if (subject === agent && status === 'idle') {
  91. dispose()
  92. resolve()
  93. }
  94. })
  95. })
  96. }
  97. describe('CBR-001: a real-loop checkpoint is a valid boundary on both sides', () => {
  98. it('the head checkpoint the loop lands is a balanced cut on both sides', async () => {
  99. const { ctx } = await harness(8)
  100. try {
  101. const agent = ctx.agentLoop.create(AgentId('repro'), { model: 'mock' })
  102. agent.send([{ type: 'text', text: 'do a long multi-step task' }])
  103. await waitForIdle(ctx, agent)
  104. const events = [...agent.session.events]
  105. // A compaction ran: at least one checkpoint landed on the surface.
  106. const checkpoints = events.filter(
  107. (e): e is SurfaceEvent =>
  108. e.type === 'user/message'
  109. && typeof (e as SurfaceEvent).surfaceOp === 'object',
  110. )
  111. expect(checkpoints.length).toBeGreaterThan(0)
  112. // High log position does not make a text-only checkpoint mid-step; both
  113. // its start and end cuts are balanced in surface order.
  114. const nodes = agent.session.surface.nodes
  115. for (const cp of checkpoints) {
  116. const node = nodes.find(n => n.seq === cp.seq)
  117. if (!node) continue // shadowed by a later checkpoint — no longer an edge.
  118. expect(isToolPairingBalanced(nodes, events, node.seq),
  119. `checkpoint seq ${node.seq} must be a balanced region START`).toBe(true)
  120. expect(isToolPairingBalanced(nodes, events, node.next),
  121. `checkpoint seq ${node.seq} must be a balanced region END`).toBe(true)
  122. }
  123. } finally {
  124. await ctx.fiber.dispose()
  125. }
  126. })
  127. })