test_subagent_recursion.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import asyncio
  2. import os
  3. import tempfile
  4. import unittest
  5. from unittest.mock import AsyncMock, patch
  6. from cyber_agent.tools.builtin.subagent import agent, evaluate
  7. from cyber_agent.trace.goal_models import Goal, GoalTree
  8. from cyber_agent.trace.models import Trace
  9. from cyber_agent.trace.store import FileSystemTraceStore
  10. class FakeToolRegistry:
  11. TOOL_NAMES = [
  12. "agent",
  13. "evaluate",
  14. "bash_command",
  15. "read_file",
  16. "grep_content",
  17. "glob_files",
  18. "goal",
  19. ]
  20. def get_tool_names(self):
  21. return list(self.TOOL_NAMES)
  22. class FakeRunner:
  23. def __init__(self, store):
  24. self.store = store
  25. self.tools = FakeToolRegistry()
  26. self.debug = False
  27. self.stdin_check = None
  28. self._cancel_events = {}
  29. self.configs = []
  30. async def run_result(self, messages, config, on_event=None):
  31. self.configs.append(config)
  32. await self.store.update_trace(config.trace_id, status="completed")
  33. return {
  34. "status": "completed",
  35. "summary": f"completed: {config.trace_id}",
  36. "saved_knowledge_ids": [],
  37. "stats": {
  38. "total_messages": 1,
  39. "total_tokens": 1,
  40. "total_cost": 0.0,
  41. },
  42. }
  43. class SubAgentRecursionTest(unittest.IsolatedAsyncioTestCase):
  44. async def asyncSetUp(self):
  45. self.temp_dir = tempfile.TemporaryDirectory()
  46. self.store = FileSystemTraceStore(self.temp_dir.name)
  47. self.runner = FakeRunner(self.store)
  48. self.previous_recursion_setting = os.environ.get("AGENT_RECURSION_ENABLED")
  49. os.environ["AGENT_RECURSION_ENABLED"] = "true"
  50. self.root_id = await self._create_root("root")
  51. async def asyncTearDown(self):
  52. if self.previous_recursion_setting is None:
  53. os.environ.pop("AGENT_RECURSION_ENABLED", None)
  54. else:
  55. os.environ["AGENT_RECURSION_ENABLED"] = self.previous_recursion_setting
  56. self.temp_dir.cleanup()
  57. async def _create_root(self, trace_id, uid="user-1"):
  58. trace = Trace(
  59. trace_id=trace_id,
  60. mode="agent",
  61. task=f"task-{trace_id}",
  62. uid=uid,
  63. model="fake-model",
  64. context={},
  65. )
  66. await self.store.create_trace(trace)
  67. await self.store.update_goal_tree(trace_id, GoalTree(mission=trace.task))
  68. return trace_id
  69. def _context(self, trace_id, goal_id=None):
  70. return {
  71. "store": self.store,
  72. "trace_id": trace_id,
  73. "goal_id": goal_id,
  74. "runner": self.runner,
  75. "knowledge_config": None,
  76. }
  77. async def _spawn_one(self, parent_id, task="child"):
  78. return await agent(task=task, context=self._context(parent_id))
  79. async def _local_children(self, parent_id):
  80. return await self.store.list_traces(
  81. parent_trace_id=parent_id,
  82. created_by_tool="agent",
  83. limit=20,
  84. )
  85. async def test_recursion_disabled_preserves_single_level_behavior(self):
  86. os.environ["AGENT_RECURSION_ENABLED"] = "false"
  87. first = await self._spawn_one(self.root_id)
  88. self.assertEqual("completed", first["status"])
  89. child_id = first["sub_trace_id"]
  90. child_config = self.runner.configs[-1]
  91. self.assertNotIn("agent", child_config.tools)
  92. blocked = await self._spawn_one(child_id, "grandchild")
  93. self.assertEqual("failed", blocked["status"])
  94. self.assertIn("recursion is disabled", blocked["error"])
  95. async def test_five_subagent_levels_and_sixth_level_rejected(self):
  96. parent_id = self.root_id
  97. for expected_depth in range(1, 6):
  98. result = await self._spawn_one(parent_id, f"depth-{expected_depth}")
  99. self.assertEqual("completed", result["status"])
  100. child_id = result["sub_trace_id"]
  101. child = await self.store.get_trace(child_id)
  102. self.assertEqual(parent_id, child.parent_trace_id)
  103. self.assertEqual(expected_depth, child.context["agent_depth"])
  104. self.assertEqual(self.root_id, child.context["root_trace_id"])
  105. tools = self.runner.configs[-1].tools
  106. if expected_depth < 5:
  107. self.assertIn("agent", tools)
  108. else:
  109. self.assertNotIn("agent", tools)
  110. self.assertNotIn("evaluate", tools)
  111. self.assertNotIn("bash_command", tools)
  112. parent_id = child_id
  113. blocked = await self._spawn_one(parent_id, "depth-6")
  114. self.assertEqual("failed", blocked["status"])
  115. self.assertIn("depth limit reached", blocked["error"])
  116. self.assertEqual([], await self._local_children(parent_id))
  117. async def test_six_children_allowed_and_seventh_rejected(self):
  118. tasks = [f"child-{index}" for index in range(6)]
  119. result = await agent(task=tasks, context=self._context(self.root_id))
  120. self.assertEqual("completed", result["status"])
  121. self.assertEqual(6, len(await self._local_children(self.root_id)))
  122. blocked = await self._spawn_one(self.root_id, "child-7")
  123. self.assertEqual("failed", blocked["status"])
  124. self.assertIn("child Agent limit exceeded", blocked["error"])
  125. self.assertEqual(6, len(await self._local_children(self.root_id)))
  126. async def test_child_batch_is_rejected_without_partial_creation(self):
  127. initial = [f"child-{index}" for index in range(5)]
  128. await agent(task=initial, context=self._context(self.root_id))
  129. blocked = await agent(
  130. task=["overflow-1", "overflow-2"],
  131. context=self._context(self.root_id),
  132. )
  133. self.assertEqual("failed", blocked["status"])
  134. self.assertEqual(5, len(await self._local_children(self.root_id)))
  135. async def test_mismatched_per_agent_messages_are_rejected_before_spawn(self):
  136. result = await agent(
  137. task=["first", "second"],
  138. messages=[[{"role": "user", "content": "only one message list"}]],
  139. context=self._context(self.root_id),
  140. )
  141. self.assertEqual("failed", result["status"])
  142. self.assertIn("exactly one message list per task", result["error"])
  143. self.assertEqual([], await self._local_children(self.root_id))
  144. async def test_goal_keeps_children_created_across_multiple_calls(self):
  145. tree = await self.store.get_goal_tree(self.root_id)
  146. tree.goals = [Goal(id="1", description="delegate twice")]
  147. await self.store.update_goal_tree(self.root_id, tree)
  148. context = self._context(self.root_id, goal_id="1")
  149. await agent(task="first", context=context)
  150. await agent(task="second", context=context)
  151. updated_tree = await self.store.get_goal_tree(self.root_id)
  152. sub_trace_ids = updated_tree.find("1").sub_trace_ids
  153. self.assertEqual(2, len(sub_trace_ids))
  154. self.assertEqual(2, len({entry["trace_id"] for entry in sub_trace_ids}))
  155. async def test_concurrent_batches_never_exceed_limit(self):
  156. results = await asyncio.gather(
  157. agent(
  158. task=[f"left-{index}" for index in range(4)],
  159. context=self._context(self.root_id),
  160. ),
  161. agent(
  162. task=[f"right-{index}" for index in range(4)],
  163. context=self._context(self.root_id),
  164. ),
  165. )
  166. self.assertEqual({"completed", "failed"}, {item["status"] for item in results})
  167. self.assertLessEqual(len(await self._local_children(self.root_id)), 6)
  168. async def test_continue_from_does_not_consume_child_slot(self):
  169. tasks = [f"child-{index}" for index in range(6)]
  170. created = await agent(task=tasks, context=self._context(self.root_id))
  171. child_id = created["sub_trace_ids"][0]["trace_id"]
  172. continued = await agent(
  173. task="continue existing child",
  174. continue_from=child_id,
  175. context=self._context(self.root_id),
  176. )
  177. self.assertEqual("completed", continued["status"])
  178. self.assertTrue(continued["continue_from"])
  179. self.assertEqual(6, len(await self._local_children(self.root_id)))
  180. async def test_continue_from_requires_direct_child_and_matching_owner(self):
  181. created = await self._spawn_one(self.root_id)
  182. child_id = created["sub_trace_id"]
  183. other_root = await self._create_root("other-root")
  184. wrong_parent = await agent(
  185. task="continue",
  186. continue_from=child_id,
  187. context=self._context(other_root),
  188. )
  189. self.assertEqual("failed", wrong_parent["status"])
  190. self.assertIn("direct child", wrong_parent["error"])
  191. await self.store.update_trace(child_id, uid="other-user")
  192. wrong_owner = await agent(
  193. task="continue",
  194. continue_from=child_id,
  195. context=self._context(self.root_id),
  196. )
  197. self.assertEqual("failed", wrong_owner["status"])
  198. self.assertIn("owner", wrong_owner["error"])
  199. async def test_evaluator_never_receives_recursive_or_shell_tools(self):
  200. await evaluate(messages=[], context=self._context(self.root_id))
  201. config = self.runner.configs[-1]
  202. self.assertEqual([], config.tool_groups)
  203. self.assertEqual(
  204. ["agent", "evaluate", "bash_command"],
  205. config.exclude_tools,
  206. )
  207. async def test_evaluator_traces_do_not_consume_local_child_slots(self):
  208. for _ in range(2):
  209. result = await evaluate(messages=[], context=self._context(self.root_id))
  210. self.assertEqual("completed", result["status"])
  211. result = await agent(
  212. task=[f"child-{index}" for index in range(6)],
  213. context=self._context(self.root_id),
  214. )
  215. self.assertEqual("completed", result["status"])
  216. self.assertEqual(6, len(await self._local_children(self.root_id)))
  217. async def test_legacy_trace_depth_is_recovered_from_parent_links(self):
  218. legacy_child_id = "legacy-child"
  219. await self.store.create_trace(
  220. Trace(
  221. trace_id=legacy_child_id,
  222. mode="agent",
  223. task="legacy child",
  224. parent_trace_id=self.root_id,
  225. uid="user-1",
  226. model="fake-model",
  227. context={"created_by_tool": "agent"},
  228. )
  229. )
  230. await self.store.update_goal_tree(
  231. legacy_child_id,
  232. GoalTree(mission="legacy child"),
  233. )
  234. result = await self._spawn_one(legacy_child_id, "grandchild")
  235. self.assertEqual("completed", result["status"])
  236. grandchild = await self.store.get_trace(result["sub_trace_id"])
  237. self.assertEqual(2, grandchild.context["agent_depth"])
  238. self.assertEqual(self.root_id, grandchild.context["root_trace_id"])
  239. async def test_remote_agent_is_not_counted_as_local_child(self):
  240. child = await self._spawn_one(self.root_id)
  241. before = len(await self._local_children(child["sub_trace_id"]))
  242. remote_result = {
  243. "mode": "remote",
  244. "agent_type": "remote_research",
  245. "status": "completed",
  246. "summary": "remote completed",
  247. "stats": {},
  248. }
  249. with patch(
  250. "cyber_agent.tools.builtin.subagent._run_remote_agent",
  251. new=AsyncMock(return_value=remote_result),
  252. ):
  253. result = await agent(
  254. task="remote task",
  255. agent_type="remote_research",
  256. context=self._context(child["sub_trace_id"]),
  257. )
  258. self.assertEqual("completed", result["status"])
  259. self.assertEqual(before, len(await self._local_children(child["sub_trace_id"])))
  260. if __name__ == "__main__":
  261. unittest.main()