compact-loop-repro.spec.ts 5.0 KB

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