compact-loop-repro.spec.ts 5.1 KB

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