properties.spec.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /**
  2. * Property-based tests for the agent loop's inbox/turn scheduling (the
  3. * property-testing Agent Note). 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
  9. * idle→running→idle, while teardown is a registry lifecycle.
  10. */
  11. import { describe, expect, it } from 'vitest'
  12. import { Context } from '@deepseek-ai/cordis'
  13. import LlmRuntime from '@deepseek-ai/dsh-llm'
  14. import { createUserMessage, LlmAdapter } from '@deepseek-ai/dsh-llm'
  15. import type { GenerateOptions, StreamChunk } 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 ToolRuntime 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(LlmRuntime)
  37. await ctx.plugin(SessionStore)
  38. await ctx.plugin(SystemPrompt)
  39. await ctx.plugin(ToolRuntime)
  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', ({ agent: 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', ({ agent: 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.turn)
  74. }
  75. function turnEndNumbers(agent: Agent): number[] {
  76. return agent.session.events
  77. .filter(e => e.type === 'turn/end')
  78. .map(e => (e.data as { turn: number }).turn)
  79. }
  80. function userMessageCountsByTurn(agent: Agent): number[] {
  81. const counts: number[] = []
  82. for (const event of agent.session.events) {
  83. if (event.type === 'turn/start') counts.push(0)
  84. if (event.type === 'user/message') counts[counts.length - 1]! += 1
  85. }
  86. return counts
  87. }
  88. /** Assert a status trace is a legal run: idle/running alternating, ending idle. */
  89. function assertLegalStatusTrace(trace: string[]): void {
  90. for (let i = 1; i < trace.length; i++) {
  91. expect(trace[i]).not.toBe(trace[i - 1]) // no repeats (setStatus dedups)
  92. }
  93. for (const s of trace) expect(['idle', 'running']).toContain(s)
  94. }
  95. describe('agent loop scheduling properties', () => {
  96. it('a synchronous burst gives every message its own strictly increasing turn', async () => {
  97. await fc.assert(fc.asyncProperty(
  98. fc.array(fc.string({ minLength: 1 }), { minLength: 1, maxLength: 6 }),
  99. async (texts) => {
  100. const ctx = await harness()
  101. try {
  102. const agent = ctx.agentLoop.create(SessionId('a'), { provider: 'mock', model: 'mock' })
  103. const { seen: trace } = recordStatus(ctx, agent)
  104. const idle = nextIdle(ctx, agent)
  105. // Send all in one synchronous tick: they queue before the loop wakes.
  106. for (const text of texts) agent.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }))
  107. await idle
  108. // No message lost: every send appears as a user/message, in order.
  109. expect(userMessageTexts(agent)).toEqual(texts)
  110. // This failure-free fixture maps every item to an independent turn.
  111. expect(turnNumbers(agent)).toEqual(texts.map((_, i) => i + 1))
  112. expect(turnEndNumbers(agent)).toEqual(texts.map((_, i) => i + 1))
  113. expect(userMessageCountsByTurn(agent)).toEqual(texts.map(() => 1))
  114. expect(trace).toEqual(['running', 'idle'])
  115. assertLegalStatusTrace(trace)
  116. } finally {
  117. await ctx.fiber.dispose()
  118. }
  119. },
  120. ), { numRuns: 25, timeout: 2000 })
  121. })
  122. it('sequential sends each get their own turn with increasing numbers', async () => {
  123. await fc.assert(fc.asyncProperty(
  124. fc.array(fc.string({ minLength: 1 }), { minLength: 1, maxLength: 5 }),
  125. async (texts) => {
  126. const ctx = await harness()
  127. try {
  128. const agent = ctx.agentLoop.create(SessionId('a'), { provider: 'mock', model: 'mock' })
  129. for (const text of texts) {
  130. const idle = nextIdle(ctx, agent)
  131. agent.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }))
  132. await idle
  133. }
  134. // Each send was drained at a separate turn start: N turns, 1..N.
  135. expect(turnNumbers(agent)).toEqual(texts.map((_, i) => i + 1))
  136. expect(userMessageTexts(agent)).toEqual(texts)
  137. } finally {
  138. await ctx.fiber.dispose()
  139. }
  140. },
  141. ), { numRuns: 20, timeout: 2000 })
  142. })
  143. it('mixed settled and same-tick sends preserve one turn per message', async () => {
  144. // Each step optionally waits for idle before the next send; that scheduling
  145. // choice must not change the ordinary message-to-turn mapping.
  146. const stepArb = fc.record({ text: fc.string({ minLength: 1 }), settle: fc.boolean() })
  147. await fc.assert(fc.asyncProperty(
  148. fc.array(stepArb, { minLength: 1, maxLength: 6 }),
  149. async (steps) => {
  150. const ctx = await harness()
  151. try {
  152. const agent = ctx.agentLoop.create(SessionId('a'), { provider: 'mock', model: 'mock' })
  153. // Capture before each send; the last waiter covers the final turn, and
  154. // awaiting an already-settled earlier waiter is harmless.
  155. let lastIdle: Promise<void> | undefined
  156. for (const step of steps) {
  157. const idle = nextIdle(ctx, agent)
  158. lastIdle = idle
  159. agent.followup(createUserMessage({ content: [{ type: 'text', text: step.text }], source: { kind: 'user' } }))
  160. if (step.settle) await idle
  161. }
  162. await lastIdle
  163. // No message is lost or reordered, regardless of driver timing.
  164. expect(userMessageTexts(agent)).toEqual(steps.map(s => s.text))
  165. // Every item forms one FIFO-ordered turn containing only that message.
  166. const turns = turnNumbers(agent)
  167. expect(turns).toEqual(steps.map((_, i) => i + 1))
  168. expect(turnEndNumbers(agent)).toEqual(turns)
  169. expect(userMessageCountsByTurn(agent)).toEqual(steps.map(() => 1))
  170. } finally {
  171. await ctx.fiber.dispose()
  172. }
  173. },
  174. ), { numRuns: 25, timeout: 3000 })
  175. })
  176. })