properties.spec.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. /**
  2. * Deterministic property tests for inbox scheduling: every sent message logs
  3. * once, turn numbers increase, and status follows idle→running→idle/disposed.
  4. * Schedules advance on status events rather than wall-clock sleeps.
  5. */
  6. import { describe, expect, it } from 'vitest'
  7. import { Context } from 'cordis'
  8. import LlmService from '@deepseek-ai/dsh-llm'
  9. import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
  10. import { LlmAdapter } from '@deepseek-ai/dsh-llm'
  11. import SessionStore from '@deepseek-ai/dsh-session'
  12. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  13. import ToolRegistry from '@deepseek-ai/dsh-tools'
  14. import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent'
  15. import AgentLoop, { type ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  16. import fc from 'fast-check'
  17. /** A never-exhausting adapter: every model call returns the same short reply. */
  18. class EchoAdapter extends LlmAdapter {
  19. async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  20. if (options.signal?.aborted) throw new Error('aborted')
  21. const text = 'ok'
  22. yield { type: 'block-start', index: 0, blockType: 'text' }
  23. yield { type: 'text-delta', index: 0, text }
  24. yield { type: 'block-end', index: 0, block: { type: 'text', text } }
  25. yield { type: 'usage', usage: { inputTokens: 1, outputTokens: 1 } }
  26. yield { type: 'finish', reason: { kind: 'stop' } }
  27. }
  28. }
  29. async function harness() {
  30. const ctx = new Context()
  31. await ctx.plugin(LlmService)
  32. await ctx.plugin(SessionStore)
  33. await ctx.plugin(SystemPrompt)
  34. await ctx.plugin(ToolRegistry)
  35. await ctx.plugin(AgentRegistry)
  36. await ctx.plugin(AgentLoop, { agents: [] })
  37. ctx.llm.registerAdapter(['mock'], new EchoAdapter())
  38. return ctx
  39. }
  40. /** Resolve on the agent's next transition to idle (event-based, not polled). */
  41. function nextIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  42. return new Promise((resolve) => {
  43. const dispose = ctx.on('agent/status', (subject, status) => {
  44. if (subject === agent && status === 'idle') {
  45. dispose()
  46. resolve()
  47. }
  48. })
  49. })
  50. }
  51. /** Record every status transition for the legal-machine assertion. Returns
  52. * the seen list plus a disposer for the listener (per the registry convention). */
  53. function recordStatus(ctx: Context, agent: ReactLoopAgent): { seen: string[]; dispose: () => void } {
  54. const seen: string[] = []
  55. const dispose = ctx.on('agent/status', (subject, status) => {
  56. if (subject === agent) seen.push(status)
  57. })
  58. return { seen, dispose }
  59. }
  60. function userMessageTexts(agent: ReactLoopAgent): string[] {
  61. return agent.session.events
  62. .filter(e => e.type === 'user/message')
  63. .map(e => (e.data as { content: { type: string; text?: string }[] }).content.map(b => b.text ?? '').join(''))
  64. }
  65. function turnNumbers(agent: ReactLoopAgent): number[] {
  66. return agent.session.events
  67. .filter(e => e.type === 'turn/start')
  68. .map(e => (e.data as { turn: number }).turn)
  69. }
  70. /** Assert a status trace is a legal run: idle/running alternating, ending idle. */
  71. function assertLegalStatusTrace(trace: string[]): void {
  72. for (let i = 1; i < trace.length; i++) {
  73. expect(trace[i]).not.toBe(trace[i - 1]) // no repeats (setStatus dedups)
  74. }
  75. for (const s of trace) expect(['idle', 'running']).toContain(s)
  76. }
  77. describe('agent loop scheduling properties', () => {
  78. it('a synchronous burst loses no message and uses strictly increasing turns', async () => {
  79. await fc.assert(fc.asyncProperty(
  80. fc.array(fc.string({ minLength: 1 }), { minLength: 1, maxLength: 6 }),
  81. async (texts) => {
  82. const ctx = await harness()
  83. try {
  84. const agent = ctx.agentLoop.create(AgentId('a'), { model: 'mock' })
  85. const { seen: trace } = recordStatus(ctx, agent)
  86. const idle = nextIdle(ctx, agent)
  87. // Send all in one synchronous tick: they queue before the loop wakes.
  88. for (const text of texts) agent.send([{ type: 'text', text }])
  89. await idle
  90. // No message lost: every send appears as a user/message, in order.
  91. expect(userMessageTexts(agent)).toEqual(texts)
  92. // A synchronous burst batches into exactly one turn.
  93. expect(turnNumbers(agent)).toEqual([1])
  94. assertLegalStatusTrace(trace)
  95. } finally {
  96. await ctx.fiber.dispose()
  97. }
  98. },
  99. ), { numRuns: 25, timeout: 2000 })
  100. })
  101. it('sequential sends each get their own turn with increasing numbers', async () => {
  102. await fc.assert(fc.asyncProperty(
  103. fc.array(fc.string({ minLength: 1 }), { minLength: 1, maxLength: 5 }),
  104. async (texts) => {
  105. const ctx = await harness()
  106. try {
  107. const agent = ctx.agentLoop.create(AgentId('a'), { model: 'mock' })
  108. for (const text of texts) {
  109. const idle = nextIdle(ctx, agent)
  110. agent.send([{ type: 'text', text }])
  111. await idle
  112. }
  113. // Each send was drained at a separate turn start: N turns, 1..N.
  114. expect(turnNumbers(agent)).toEqual(texts.map((_, i) => i + 1))
  115. expect(userMessageTexts(agent)).toEqual(texts)
  116. } finally {
  117. await ctx.fiber.dispose()
  118. }
  119. },
  120. ), { numRuns: 20, timeout: 2000 })
  121. })
  122. it('mixed schedule (send, optionally settle) loses no message and orders turns', async () => {
  123. // Each step is a (text, settle?) pair: settle=true awaits idle before the
  124. // next send (own turn); settle=false sends in the same tick (batches).
  125. const stepArb = fc.record({ text: fc.string({ minLength: 1 }), settle: fc.boolean() })
  126. await fc.assert(fc.asyncProperty(
  127. fc.array(stepArb, { minLength: 1, maxLength: 6 }),
  128. async (steps) => {
  129. const ctx = await harness()
  130. try {
  131. const agent = ctx.agentLoop.create(AgentId('a'), { model: 'mock' })
  132. // Capture before each send; the last waiter covers the final turn, and
  133. // awaiting an already-settled earlier waiter is harmless.
  134. let lastIdle: Promise<void> | undefined
  135. for (const step of steps) {
  136. const idle = nextIdle(ctx, agent)
  137. lastIdle = idle
  138. agent.send([{ type: 'text', text: step.text }])
  139. if (step.settle) await idle
  140. }
  141. await lastIdle
  142. // No message lost or reordered, regardless of batching.
  143. expect(userMessageTexts(agent)).toEqual(steps.map(s => s.text))
  144. // Turn numbers are a strictly increasing 1..N prefix (N = turn count).
  145. const turns = turnNumbers(agent)
  146. expect(turns).toEqual(turns.map((_, i) => i + 1))
  147. // Every message landed in some turn; turns never exceed messages.
  148. expect(turns.length).toBeLessThanOrEqual(steps.length)
  149. expect(turns.length).toBeGreaterThanOrEqual(1)
  150. } finally {
  151. await ctx.fiber.dispose()
  152. }
  153. },
  154. ), { numRuns: 25, timeout: 3000 })
  155. })
  156. })