compact-loop-repro.spec.ts 5.2 KB

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