compact-loop-repro.spec.ts 5.2 KB

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