compact-loop-repro.spec.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import type { ContentBlock, GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
  4. import { CallId, LlmAdapter } from '@deepseek-ai/dsh-llm'
  5. import { isToolPairingBalanced } from '@deepseek-ai/dsh-session'
  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 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. const TOKENS_PER_BLOCK = 10
  20. class ReproCompactService extends BasicCompactService {
  21. override estimateContentTokens(blocks: readonly ContentBlock[]): number {
  22. return blocks.length * TOKENS_PER_BLOCK
  23. }
  24. override async summarize(): Promise<{ summary: ContentBlock[]; provider: string; model: string }> {
  25. return { summary: [{ type: 'text', text: 'CHECKPOINT SUMMARY' }], provider: 'mock', model: 'stub' }
  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. ctx.llm.registerAdapter(['mock'], new StepwiseToolAdapter(toolSteps))
  58. ctx.tools.register(defineTool({
  59. name: 'work',
  60. description: 'does work',
  61. parameters: { i: { type: 'number' } },
  62. async execute() {
  63. return [{ type: 'text', text: 'work result' }]
  64. },
  65. }))
  66. // Tiny window so a couple of tool steps cross the threshold and compaction
  67. // fires within the runaway turn.
  68. const compact = new ReproCompactService(ctx, {
  69. auto: true,
  70. contextWindow: 64,
  71. thresholdRatio: 0.5,
  72. retainTokens: 20,
  73. summarizationProvider: '',
  74. summarizationModel: '',
  75. maxTokens: 8192,
  76. compactionRetries: 1,
  77. })
  78. return { ctx, compact }
  79. }
  80. function waitForIdle(ctx: Context, agent: ReactLoopAgent): 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(AgentId('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 node = nodes.find(n => n.seq === cp.seq)
  110. if (!node) continue // shadowed by a later checkpoint — no longer an edge.
  111. expect(isToolPairingBalanced(nodes, events, node.seq),
  112. `checkpoint seq ${node.seq} must be a balanced region START`).toBe(true)
  113. expect(isToolPairingBalanced(nodes, events, node.next),
  114. `checkpoint seq ${node.seq} must be a balanced region END`).toBe(true)
  115. }
  116. } finally {
  117. await ctx.fiber.dispose()
  118. }
  119. })
  120. })