test_subagent_recursion.py 15 KB

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