compact-loop-repro.spec.ts 5.3 KB

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