python-snapshot-workflow-order.spec.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import { getEventListeners } from 'node:events'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import { agentEvents, type Agent, type PreStepDecision } from '@deepseek-ai/dsh-agent'
  4. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  5. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  6. import { WorkflowRunId } from '@deepseek-ai/dsh-workflow'
  7. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  8. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  9. import SubagentRuntime from '@deepseek-ai/dsh-subagent'
  10. import * as spawn from '@deepseek-ai/dsh-subagent-spawn-in-process'
  11. import { MockAdapter, textResponse } from '../packages/core/agent-loop/tests/mock-adapter.ts'
  12. import type {} from '@deepseek-ai/dsh-tool-workflow'
  13. import { afterEach, describe, expect, it, vi } from 'vitest'
  14. // @ts-expect-error Scenario plugins are runtime JavaScript without declaration artifacts.
  15. import * as fixtureModule from './fixtures/python-snapshot-workflow-order.mjs'
  16. const config = { parentSessionId: 'advanced-parent', prompt: 'workflow child prompt' }
  17. const fixture = fixtureModule as unknown as {
  18. name: string
  19. apply(ctx: Context, config: { parentSessionId: string; prompt: string }): void
  20. }
  21. const cleanups: (() => Promise<unknown>)[] = []
  22. afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup() })
  23. async function harness() {
  24. const ctx = new Context()
  25. const store = ctx.plugin(SessionStore)
  26. await store
  27. cleanups.push(() => store.dispose())
  28. const fiber = ctx.plugin(fixture, config)
  29. await fiber
  30. cleanups.push(() => fiber.dispose())
  31. const parent = ctx.sessions.create(SessionId(config.parentSessionId))
  32. const other = ctx.sessions.create(SessionId('other-parent'))
  33. const session = ctx.sessions.create(SessionId('workflow-child'), { meta: { parentSession: parent.id } })
  34. // The dispatcher needs only the subject identity; the fixture reads its Session.
  35. const agent = { id: session.id, session } as Agent
  36. const controller = new AbortController()
  37. const messages = [createUserMessage({ content: [{ type: 'text', text: config.prompt }], source: { kind: 'user' } })]
  38. const decision: PreStepDecision = { kind: 'enter', messages }
  39. const next = vi.fn(async () => decision)
  40. const start = (owner = parent, childId = agent.id) => owner.append('tool-workflow/agent-start', {
  41. runId: WorkflowRunId('run'), seq: 1, label: 'workflow-child', childId,
  42. })
  43. const step = (overrides = {}) => agentEvents(ctx, agent).waterfall('agent/pre-step', {
  44. turn: 1, step: 1, messages, signal: controller.signal, ...overrides,
  45. }, next)
  46. return { ctx, fiber, parent, other, session, agent, controller, decision, next, start, step }
  47. }
  48. describe('advanced Python snapshot workflow ordering', () => {
  49. it('blocks a real spawned child before its descriptor and first model request', async () => {
  50. const ctx = new Context()
  51. const entered = Promise.withResolvers<Agent>()
  52. const order: string[] = []
  53. const adapter = new MockAdapter([textResponse('child complete')])
  54. const assembly = ctx.plugin({
  55. name: 'workflow-order-driver-test',
  56. async apply(inner: Context) {
  57. await mountAgentLoopTestDependencies(inner)
  58. await inner.plugin(AgentLoop, { agents: [] })
  59. await inner.plugin(SubagentRuntime)
  60. await inner.plugin(spawn, { providerName: 'spawn' })
  61. inner.on('agent/pre-step', ({ agent }, next) => {
  62. if (agent.session.header.parentSession === config.parentSessionId) entered.resolve(agent)
  63. return next()
  64. })
  65. inner.on('session/event', (_session, event) => {
  66. if (event.type === 'tool-workflow/agent-start' || event.type === 'subagent/descriptor') order.push(event.type)
  67. })
  68. await inner.plugin(fixture, config)
  69. },
  70. })
  71. cleanups.push(() => assembly.dispose())
  72. await assembly
  73. ctx.llm.registerAdapter(['mock'], adapter)
  74. const parent = await ctx.agentLoop.create(SessionId(config.parentSessionId), { provider: 'mock', model: 'mock' })
  75. const run = await ctx.subagents.start('spawn', {
  76. parent, prompt: [{ type: 'text', text: config.prompt }], signal: new AbortController().signal,
  77. })
  78. cleanups.push(() => run.dispose())
  79. const child = await entered.promise
  80. expect(child.id).toBe(run.id)
  81. expect(adapter.requests).toHaveLength(0)
  82. expect(child.session.snapshotEvents().some(event => event.type === 'subagent/descriptor')).toBe(false)
  83. parent.session.append('tool-workflow/agent-start', {
  84. runId: WorkflowRunId('run'), seq: 1, label: 'workflow-child', childId: child.id,
  85. })
  86. expect((await run.result).output).toEqual([{ type: 'text', text: 'child complete' }])
  87. expect(adapter.requests).toHaveLength(1)
  88. expect(order).toEqual(['tool-workflow/agent-start', 'subagent/descriptor'])
  89. })
  90. it('holds the child until the exact parent records the exact member', async () => {
  91. const h = await harness()
  92. const pending = h.step()
  93. expect(h.next).not.toHaveBeenCalled()
  94. expect(getEventListeners(h.controller.signal, 'abort')).toHaveLength(1)
  95. h.start(h.other)
  96. h.start(h.parent, SessionId('other-child'))
  97. h.parent.append('tool-workflow/run-start', { runId: WorkflowRunId('run'), name: 'workflow' })
  98. await Promise.resolve()
  99. expect(h.next).not.toHaveBeenCalled()
  100. h.start()
  101. expect(await pending).toBe(h.decision)
  102. expect(h.next).toHaveBeenCalledOnce()
  103. expect(getEventListeners(h.controller.signal, 'abort')).toHaveLength(0)
  104. })
  105. it('retains a start recorded before the child reaches its first step', async () => {
  106. const h = await harness()
  107. h.start()
  108. expect(await h.step()).toBe(h.decision)
  109. expect(h.next).toHaveBeenCalledOnce()
  110. expect(getEventListeners(h.controller.signal, 'abort')).toHaveLength(0)
  111. })
  112. it.each(['prompt', 'parent', 'turn', 'step'])('does not hold an unrelated %s', async (difference) => {
  113. const h = await harness()
  114. const overrides = difference === 'prompt' ? { messages: [] }
  115. : difference === 'turn' ? { turn: 2 }
  116. : difference === 'step' ? { step: 2 } : {}
  117. if (difference === 'parent') {
  118. const session = h.ctx.sessions.create(SessionId('unrelated-child'), { meta: { parentSession: h.other.id } })
  119. Object.assign(h.agent, { session })
  120. }
  121. expect(await h.step(overrides)).toBe(h.decision)
  122. expect(h.next).toHaveBeenCalledOnce()
  123. })
  124. it.each([false, true])('rejects cancellation and detaches the waiter (already aborted: %s)', async (alreadyAborted) => {
  125. const h = await harness()
  126. const reason = new Error('cancelled child')
  127. if (alreadyAborted) h.controller.abort(reason)
  128. const pending = h.step()
  129. const rejected = expect(pending).rejects.toBe(reason)
  130. h.controller.abort(reason)
  131. await rejected
  132. h.start()
  133. expect(h.next).not.toHaveBeenCalled()
  134. expect(getEventListeners(h.controller.signal, 'abort')).toHaveLength(0)
  135. })
  136. it('does not admit a cancelled child when start and cancellation share a tick', async () => {
  137. const h = await harness()
  138. const reason = new Error('cancelled after membership')
  139. const pending = h.step()
  140. const rejected = expect(pending).rejects.toBe(reason)
  141. h.start()
  142. h.controller.abort(reason)
  143. await rejected
  144. expect(h.next).not.toHaveBeenCalled()
  145. expect(getEventListeners(h.controller.signal, 'abort')).toHaveLength(0)
  146. })
  147. it('settles pending waits before disposal completes and removes both listeners', async () => {
  148. const h = await harness()
  149. const pending = h.step()
  150. const rejected = expect(pending).rejects.toThrow('workflow snapshot barrier disposed')
  151. await h.fiber.dispose()
  152. await rejected
  153. h.start()
  154. expect(h.next).not.toHaveBeenCalled()
  155. expect(getEventListeners(h.controller.signal, 'abort')).toHaveLength(0)
  156. expect(await h.step()).toBe(h.decision)
  157. })
  158. })