compact-loop-repro.spec.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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 type { Agent } from '@deepseek-ai/dsh-agent'
  8. import AgentLoop 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 { SessionId, 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[]; provider: string; model: string }> {
  22. return {
  23. summary: [{ type: 'text', text: 'CHECKPOINT SUMMARY' }],
  24. provider: 'mock',
  25. model: 'stub',
  26. }
  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 mountAgentLoopTestDependencies(ctx)
  56. await ctx.plugin(Invariants)
  57. await ctx.plugin(AgentLoop, { agents: [] })
  58. await ctx.plugin(TokenMeterService, { contextWindow: 400 })
  59. ctx.llm.registerAdapter(['mock'], new StepwiseToolAdapter(toolSteps))
  60. ctx.tools.register(defineTool({
  61. name: 'work',
  62. description: 'does work',
  63. parameters: { i: { type: 'number' } },
  64. async execute() {
  65. return [{ type: 'text', text: 'work result' }]
  66. },
  67. }))
  68. // Small window so several tool steps cross the threshold and compaction
  69. // fires within the runaway turn after enough history can shrink.
  70. const compact = new ReproCompactService(ctx, {
  71. auto: true,
  72. thresholdRatio: 0.5,
  73. retainTokens: 50,
  74. summarizationModel: '',
  75. maxTokens: 8192,
  76. compactionRetries: 1,
  77. })
  78. return { ctx, compact }
  79. }
  80. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  81. return new Promise((resolve) => {
  82. const dispose = ctx.on('agent/status', (subject, status) => {
  83. if (subject === agent && status === 'idle') {
  84. dispose()
  85. resolve()
  86. }
  87. })
  88. })
  89. }
  90. describe('CBR-001: a real-loop checkpoint is a valid boundary on both sides', () => {
  91. it('the head checkpoint the loop lands is a balanced cut on both sides', async () => {
  92. const { ctx } = await harness(8)
  93. try {
  94. const agent = ctx.agentLoop.create(SessionId('repro'), { provider: 'mock', model: 'mock' })
  95. agent.send([{ type: 'text', text: 'do a long multi-step task' }])
  96. await waitForIdle(ctx, agent)
  97. const events = [...agent.session.events]
  98. // A compaction ran: at least one checkpoint landed on the surface.
  99. const checkpoints = events.filter(
  100. (e): e is SurfaceEvent =>
  101. e.type === 'user/message'
  102. && typeof (e as SurfaceEvent).surfaceOp === 'object',
  103. )
  104. expect(checkpoints.length).toBeGreaterThan(0)
  105. // High log position does not make a text-only checkpoint mid-step; both
  106. // its start and end cuts are balanced in surface order.
  107. const nodes = agent.session.surface.nodes
  108. for (const cp of checkpoints) {
  109. const index = nodes.indexOf(cp.seq)
  110. if (index === -1) continue // shadowed by a later checkpoint — no longer an edge.
  111. expect(toolPairingBalancedBefore(agent.session, cp.seq),
  112. `checkpoint seq ${cp.seq} must be a balanced region START`).toBe(true)
  113. expect(toolPairingBalancedAfter(agent.session, cp.seq),
  114. `checkpoint seq ${cp.seq} must be a balanced region END`).toBe(true)
  115. }
  116. } finally {
  117. await ctx.fiber.dispose()
  118. }
  119. })
  120. })