compact-loop-repro.spec.ts 5.2 KB

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