test_application_reference.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. from copy import deepcopy
  2. import json
  3. import tempfile
  4. import unittest
  5. from unittest.mock import patch
  6. from cyber_agent.application import (
  7. ApplicationRegistry,
  8. ApplicationRuntime,
  9. CandidateReviewAction,
  10. )
  11. from cyber_agent.application.candidate import CandidateLedger, CandidatePointer
  12. from cyber_agent.core.artifacts import ArtifactRef
  13. from cyber_agent.core.run_snapshot import (
  14. RunConfigSnapshotV2,
  15. persist_run_config_snapshot,
  16. )
  17. from cyber_agent.core.runner import RunConfig
  18. from cyber_agent.core.task_protocol import (
  19. Finding,
  20. Hypothesis,
  21. Question,
  22. TaskBrief,
  23. TaskProgress,
  24. WorkItem,
  25. initialize_task_progress,
  26. new_task_protocol,
  27. )
  28. from cyber_agent.trace.models import Message, Trace
  29. from cyber_agent.trace.store import FileSystemTraceStore
  30. from examples.application_reference import build_reference_components
  31. class ApplicationReferenceEndToEndTest(unittest.IsolatedAsyncioTestCase):
  32. async def test_local_candidate_retry_preserves_fact_and_peer_validation(self):
  33. with tempfile.TemporaryDirectory() as temp_dir:
  34. store = FileSystemTraceStore(temp_dir)
  35. components = build_reference_components()
  36. registry = ApplicationRegistry()
  37. binding = registry.register(
  38. components.application,
  39. components.services,
  40. )
  41. llm_calls = 0
  42. async def llm_call(**kwargs):
  43. nonlocal llm_calls
  44. llm_calls += 1
  45. packet = json.loads(kwargs["messages"][-1]["content"])
  46. scope = packet["validation_scope"]
  47. return {
  48. "content": json.dumps({
  49. "scope": scope,
  50. "outcome": "passed",
  51. "checks": [
  52. {
  53. "check_id": item["check_id"],
  54. "status": "passed",
  55. "evidence_refs": [],
  56. "issue": None,
  57. }
  58. for item in packet["validation_plan"]["checks"]
  59. ],
  60. "reason": "reference candidate is complete",
  61. "retry_from": None,
  62. }),
  63. "tool_calls": [],
  64. }
  65. runtime = ApplicationRuntime(
  66. registry=registry,
  67. trace_store=store,
  68. llm_call=llm_call,
  69. )
  70. runner, config = runtime.new_run(
  71. "application_reference",
  72. "1",
  73. uid="reference-user",
  74. root_task_anchor={
  75. "objective": "Create an evidence-grounded explanation",
  76. "completion_criteria": ["Use verified facts and finished copy"],
  77. "constraints": ["Do not publish placeholder text"],
  78. },
  79. )
  80. with patch.dict("os.environ", {"AGENT_MODE": "recursive"}, clear=False):
  81. root, _goal, _sequence = await runner._prepare_new_trace(
  82. [{"role": "user", "content": "write the explanation"}],
  83. config,
  84. )
  85. await store.add_message(Message.create(
  86. trace_id=root.trace_id,
  87. role="user",
  88. sequence=1,
  89. content="write the explanation",
  90. ))
  91. await store.add_message(Message.create(
  92. trace_id=root.trace_id,
  93. role="assistant",
  94. sequence=2,
  95. parent_sequence=1,
  96. content="drafting",
  97. ))
  98. await store.update_trace(root.trace_id, head_sequence=2)
  99. async def create_child(trace_id, role_id, brief):
  100. context = deepcopy(root.context)
  101. context.pop("run_config_snapshot", None)
  102. context["application_role_id"] = role_id
  103. context["application_role_hash"] = binding.role(role_id).role_hash
  104. context["agent_depth"] = 1
  105. state = new_task_protocol(brief)
  106. initialize_task_progress(state, effective_at_sequence=1)
  107. context["task_protocol"] = state
  108. child_config = RunConfig(
  109. trace_id=trace_id,
  110. uid=root.uid,
  111. parent_trace_id=root.trace_id,
  112. context=context,
  113. enable_research_flow=False,
  114. )
  115. binding.configure_run_config(child_config, role_id)
  116. context["effective_run_limits"] = dict(
  117. child_config.effective_run_limits
  118. )
  119. child_config.context = context
  120. persist_run_config_snapshot(
  121. context,
  122. RunConfigSnapshotV2.from_run_config(
  123. child_config,
  124. memory_identity=None,
  125. ),
  126. )
  127. child = Trace(
  128. trace_id=trace_id,
  129. mode="agent",
  130. agent_type=role_id,
  131. uid=root.uid,
  132. model=binding.role(role_id).role.model,
  133. parent_trace_id=root.trace_id,
  134. context=context,
  135. )
  136. await store.create_trace(child)
  137. return child
  138. fact_child = await create_child(
  139. "reference-fact",
  140. "fact_checker",
  141. TaskBrief(
  142. objective="Verify what an agent framework supplies",
  143. reason="The content needs one traceable fact",
  144. completion_criteria=["Return one sourced finding"],
  145. expected_outputs=["fact artifact"],
  146. validation_scopes=["evidence"],
  147. ),
  148. )
  149. raw_fact_result = await binding.tool_registry.execute(
  150. "verify_fact",
  151. {"question": "What does an agent framework supply?"},
  152. uid=root.uid,
  153. context={
  154. "trace_id": fact_child.trace_id,
  155. "store": store,
  156. },
  157. allowed_tool_names={"verify_fact"},
  158. )
  159. fact_ref = ArtifactRef.model_validate(
  160. json.loads(raw_fact_result)["artifact_ref"]
  161. )
  162. await runner.task_protocol_service.update_progress(
  163. fact_child.trace_id,
  164. expected_revision=1,
  165. progress=TaskProgress(
  166. phase="ready_to_submit",
  167. questions=[Question(
  168. item_id="fact-question",
  169. text="What does the framework supply?",
  170. state="answered",
  171. answer="Reusable execution contracts",
  172. artifact_refs=[fact_ref],
  173. )],
  174. findings=[Finding(
  175. item_id="fact-finding",
  176. statement="The framework supplies reusable execution contracts.",
  177. basis="reference fixture",
  178. artifact_refs=[fact_ref],
  179. )],
  180. hypotheses=[Hypothesis(
  181. item_id="fact-hypothesis",
  182. statement="The explanation can distinguish framework from business code.",
  183. state="supported",
  184. rationale="The verified definition supports the distinction.",
  185. artifact_refs=[fact_ref],
  186. )],
  187. work_items=[WorkItem(
  188. item_id="fact-work",
  189. description="verify the definition",
  190. state="done",
  191. result_summary="one fact artifact recorded",
  192. artifact_refs=[fact_ref],
  193. )],
  194. decision_rationale="The question is answered by one stable fixture.",
  195. ),
  196. effective_at_sequence=2,
  197. )
  198. writer = await create_child(
  199. "reference-writer",
  200. "writer",
  201. TaskBrief(
  202. objective="Produce two candidate explanations",
  203. reason="The editor needs alternatives",
  204. completion_criteria=["Both candidates use the verified fact"],
  205. expected_outputs=["candidate A", "candidate B"],
  206. validation_scopes=["output"],
  207. ),
  208. )
  209. candidate_a = await runner.candidate_service.manage(
  210. writer.trace_id,
  211. operation="create",
  212. content={"text": "A finished explanation of reusable contracts."},
  213. parent_refs=[],
  214. effective_at_sequence=4,
  215. )
  216. candidate_b = await runner.candidate_service.manage(
  217. writer.trace_id,
  218. operation="create",
  219. content={"text": "B says {{placeholder}}."},
  220. parent_refs=[],
  221. effective_at_sequence=5,
  222. )
  223. await runner.task_protocol_service.update_progress(
  224. writer.trace_id,
  225. expected_revision=1,
  226. progress=TaskProgress(
  227. phase="ready_to_submit",
  228. findings=[Finding(
  229. item_id="writer-finding",
  230. statement="Both candidates derive from the verified definition.",
  231. basis="fact artifact",
  232. artifact_refs=[fact_ref],
  233. )],
  234. work_items=[WorkItem(
  235. item_id="writer-work",
  236. description="draft two alternatives",
  237. state="done",
  238. result_summary="A and B registered",
  239. )],
  240. decision_rationale="Both candidate revisions are ready for validation.",
  241. ),
  242. effective_at_sequence=6,
  243. )
  244. validation_a = await runner.validate_recursive_trace(
  245. writer.trace_id,
  246. candidate_ref=candidate_a,
  247. )
  248. validation_b = await runner.validate_recursive_trace(
  249. writer.trace_id,
  250. candidate_ref=candidate_b,
  251. )
  252. self.assertEqual("passed", validation_a.result.outcome)
  253. self.assertEqual("failed", validation_b.result.outcome)
  254. self.assertEqual(1, components.facts.calls)
  255. self.assertEqual(
  256. 1,
  257. binding.tool_registry.get_stats("verify_fact")[
  258. "verify_fact"
  259. ]["call_count"],
  260. )
  261. self.assertEqual(1, llm_calls)
  262. frozen_a = validation_a.result.model_dump(mode="json")
  263. await runner._mark_trace_stopped(root.trace_id, root.head_sequence)
  264. await runner._mark_trace_stopped(writer.trace_id, writer.head_sequence)
  265. restarted_components = build_reference_components(
  266. artifacts=components.artifacts,
  267. candidates=components.candidates,
  268. projector=components.projector,
  269. )
  270. restarted_registry = ApplicationRegistry()
  271. restarted_registry.register(
  272. restarted_components.application,
  273. restarted_components.services,
  274. )
  275. restarted_runtime = ApplicationRuntime(
  276. registry=restarted_registry,
  277. trace_store=store,
  278. llm_call=llm_call,
  279. )
  280. restored_runner, restored_config = await restarted_runtime.restore(
  281. writer.trace_id
  282. )
  283. self.assertEqual("writer", restored_config.role_id)
  284. self.assertEqual(0, restarted_components.context.list_calls)
  285. self.assertEqual(0, restarted_components.context.resolve_calls)
  286. await restored_runner.candidate_service.apply_review_actions(
  287. root.trace_id,
  288. writer.trace_id,
  289. report_refs=[candidate_a, candidate_b],
  290. actions=[CandidateReviewAction(
  291. action="revise",
  292. candidate_ref=candidate_b,
  293. reason="remove the placeholder without repeating fact research",
  294. )],
  295. effective_at_sequence=7,
  296. )
  297. candidate_b2 = await restored_runner.candidate_service.manage(
  298. writer.trace_id,
  299. operation="fork",
  300. content={"text": "B2 is a finished explanation of reusable contracts."},
  301. parent_refs=[CandidatePointer(
  302. candidate_id=candidate_b.candidate_id,
  303. revision=candidate_b.revision,
  304. )],
  305. effective_at_sequence=8,
  306. )
  307. validation_b2 = await restored_runner.validate_recursive_trace(
  308. writer.trace_id,
  309. candidate_ref=candidate_b2,
  310. )
  311. self.assertEqual("passed", validation_b2.result.outcome)
  312. self.assertEqual(2, llm_calls)
  313. self.assertEqual(
  314. 1,
  315. components.facts.calls + restarted_components.facts.calls,
  316. )
  317. self.assertEqual(
  318. frozen_a,
  319. (await restored_runner.validate_recursive_trace(
  320. writer.trace_id,
  321. candidate_ref=candidate_a,
  322. )).result.model_dump(mode="json"),
  323. )
  324. self.assertEqual(2, llm_calls)
  325. messages = await store.get_trace_messages(root.trace_id)
  326. cutoff = min(item.sequence for item in messages)
  327. await restored_runner._rewind(root.trace_id, cutoff, None)
  328. await restored_runner.candidate_service.apply_review_actions(
  329. root.trace_id,
  330. writer.trace_id,
  331. report_refs=[candidate_a, candidate_b2],
  332. actions=[CandidateReviewAction(
  333. action="adopt",
  334. candidate_ref=candidate_b2,
  335. reason="publish the corrected exact revision",
  336. )],
  337. effective_at_sequence=20,
  338. )
  339. self.assertEqual(1, components.candidates.adoption_calls)
  340. self.assertEqual(1, len(components.candidates.adoptions))
  341. await restored_runner.event_service.try_pump(root.trace_id)
  342. before_replay = dict(components.projector.rows)
  343. await restarted_runtime.reconcile_events(root.trace_id)
  344. await restarted_runtime.reconcile_events(root.trace_id)
  345. self.assertEqual(before_replay, components.projector.rows)
  346. adopted_keys = [
  347. key for key in components.projector.rows
  348. if key.endswith(":adopted")
  349. ]
  350. self.assertEqual(1, len(adopted_keys))
  351. with self.assertRaisesRegex(ValueError, "committed candidate adoption"):
  352. await restored_runner._rewind(root.trace_id, cutoff, None)
  353. ledger = CandidateLedger.model_validate(
  354. await store.get_candidate_ledger(root.trace_id)
  355. )
  356. self.assertEqual(3, len(ledger.candidates))
  357. self.assertEqual(3, len(ledger.validations))
  358. self.assertEqual(
  359. [(candidate_b.candidate_id, candidate_b.revision)],
  360. [
  361. (item.candidate_id, item.revision)
  362. for item in candidate_b2.parent_refs
  363. ],
  364. )