properties.spec.ts 7.1 KB

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