test_candidate_service.py 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880
  1. import asyncio
  2. import json
  3. import tempfile
  4. import unittest
  5. from unittest.mock import patch
  6. from pydantic import ValidationError
  7. from cyber_agent.application import (
  8. AgentApplication,
  9. AgentRole,
  10. ApplicationRegistry,
  11. ApplicationServices,
  12. ProviderRef,
  13. )
  14. from cyber_agent.application.candidate import (
  15. CandidateAdoptionReceipt,
  16. CandidateLedger,
  17. CandidateOperationRecord,
  18. CandidatePointer,
  19. CandidateRepositoryRejected,
  20. CandidateReviewAction,
  21. MAX_CANDIDATES_PER_ROOT,
  22. MAX_CANDIDATE_OPERATIONS_PER_ROOT,
  23. )
  24. from cyber_agent.application.quality import CandidateValidationRecord
  25. from cyber_agent.application.candidate_service import (
  26. CandidateService,
  27. CandidateStateError,
  28. )
  29. from cyber_agent.core.runner import AgentRunner, RunConfig
  30. from cyber_agent.core.artifacts import (
  31. ArtifactRef,
  32. ValidationMaterial,
  33. material_content_hash,
  34. )
  35. from cyber_agent.core.task_protocol import TaskBrief, new_task_protocol
  36. from cyber_agent.core.validation import (
  37. ScopeValidationResult,
  38. ValidationCheck,
  39. ValidationResult,
  40. )
  41. from cyber_agent.tools import get_tool_registry
  42. from cyber_agent.tools.errors import RecoverableToolExecutionError
  43. from cyber_agent.tools.registry import ToolRegistry
  44. from cyber_agent.trace.models import Message as TraceMessage, Trace
  45. from cyber_agent.trace.store import (
  46. FileSystemTraceStore,
  47. TraceStoreCorruptionError,
  48. )
  49. class MemoryCandidateRepository:
  50. def __init__(self):
  51. self.contents = {}
  52. self.put_calls = 0
  53. self.merge_calls = 0
  54. self.bad_artifact = False
  55. self.adoptions = {}
  56. self.adoption_calls = 0
  57. async def put_version(self, request):
  58. self.put_calls += 1
  59. return self._save(request)
  60. async def merge(self, request):
  61. self.merge_calls += 1
  62. return self._save(request)
  63. def _save(self, request):
  64. key = request.operation_id
  65. self.contents.setdefault(key, request)
  66. persisted = self.contents[key]
  67. digest = material_content_hash(persisted.content)
  68. if self.bad_artifact:
  69. digest = "0" * 64
  70. return ArtifactRef(
  71. artifact_id=(
  72. f"candidate:{persisted.candidate_id}:{persisted.revision}"
  73. ),
  74. version=str(persisted.revision),
  75. content_hash=digest,
  76. kind="candidate.output",
  77. mime_type="application/json",
  78. )
  79. async def resolve(self, ref, root_trace_id, uid):
  80. request = next(
  81. item
  82. for item in self.contents.values()
  83. if (
  84. ref.artifact_id
  85. == f"candidate:{item.candidate_id}:{item.revision}"
  86. )
  87. )
  88. return ValidationMaterial(
  89. **ref.model_dump(),
  90. root_trace_id=root_trace_id,
  91. uid=uid,
  92. content=request.content,
  93. )
  94. async def load_version(self, candidate_ref):
  95. return next(
  96. item.content
  97. for item in self.contents.values()
  98. if item.candidate_id == candidate_ref.candidate_id
  99. and item.revision == candidate_ref.revision
  100. )
  101. async def commit_adoption(self, request):
  102. self.adoption_calls += 1
  103. self.adoptions.setdefault(request.operation_id, request.candidate_ref)
  104. return CandidateAdoptionReceipt(
  105. operation_id=request.operation_id,
  106. external_id=f"published:{request.candidate_ref.candidate_id}",
  107. )
  108. def application():
  109. return AgentApplication(
  110. application_id="candidate.test",
  111. application_version="1",
  112. root_role="writer",
  113. roles=(AgentRole(
  114. role_id="writer",
  115. model="fake",
  116. system_prompt="write",
  117. ),),
  118. artifact_resolver_ref=ProviderRef(
  119. provider_id="artifacts",
  120. provider_version="1",
  121. ),
  122. candidate_repository_ref=ProviderRef(
  123. provider_id="candidates",
  124. provider_version="1",
  125. ),
  126. )
  127. class CandidateServiceTest(unittest.IsolatedAsyncioTestCase):
  128. async def asyncSetUp(self):
  129. self.temp = tempfile.TemporaryDirectory()
  130. self.store = FileSystemTraceStore(self.temp.name)
  131. self.repository = MemoryCandidateRepository()
  132. self.binding = ApplicationRegistry().register(
  133. application(),
  134. ApplicationServices(
  135. tool_registry=ToolRegistry(),
  136. artifact_resolver=self.repository,
  137. candidate_repository=self.repository,
  138. ),
  139. )
  140. self.service = CandidateService(
  141. store=self.store,
  142. application_binding=self.binding,
  143. repository=self.repository,
  144. artifact_resolver=self.repository,
  145. )
  146. await self._create_root("root-a")
  147. async def asyncTearDown(self):
  148. self.temp.cleanup()
  149. def _context(self, root_trace_id, *, task_brief=None):
  150. return {
  151. "agent_mode": "recursive",
  152. "agent_mode_revision": 3,
  153. "root_trace_id": root_trace_id,
  154. "root_task_anchor_hash": "a" * 64,
  155. "application_ref": self.binding.application_ref.model_dump(mode="json"),
  156. "application_role_id": "writer",
  157. "application_role_hash": self.binding.role("writer").role_hash,
  158. "task_protocol": new_task_protocol(task_brief),
  159. }
  160. async def _create_root(self, trace_id, *, uid="user-1"):
  161. await self.store.create_trace(Trace(
  162. trace_id=trace_id,
  163. mode="agent",
  164. agent_type="writer",
  165. uid=uid,
  166. context=self._context(trace_id),
  167. ))
  168. async def _create_child(self, trace_id, root_trace_id="root-a"):
  169. await self.store.create_trace(Trace(
  170. trace_id=trace_id,
  171. mode="agent",
  172. agent_type="writer",
  173. uid="user-1",
  174. parent_trace_id=root_trace_id,
  175. context=self._context(
  176. root_trace_id,
  177. task_brief=TaskBrief(
  178. objective="write candidate",
  179. reason="the root needs an option",
  180. completion_criteria=["candidate is complete"],
  181. expected_outputs=["one candidate"],
  182. ),
  183. ),
  184. ))
  185. async def _record_validation(self, trace_id, candidate, outcome="passed"):
  186. plan_hash = material_content_hash({
  187. "candidate": candidate.model_dump(mode="json"),
  188. "outcome": outcome,
  189. })
  190. status = "passed" if outcome == "passed" else "failed"
  191. scope = ScopeValidationResult(
  192. validator_trace_id=f"{trace_id}@validator",
  193. scope="output",
  194. outcome=outcome,
  195. checks=[ValidationCheck(
  196. check_id="quality.rule",
  197. status=status,
  198. issue=None if status == "passed" else "needs revision",
  199. )],
  200. reason="checked",
  201. retry_from=None if outcome == "passed" else "output",
  202. plan_hash=plan_hash,
  203. )
  204. result = ValidationResult(
  205. evaluated_trace_id=trace_id,
  206. outcome=outcome,
  207. scope_results=[scope],
  208. issues=[] if outcome == "passed" else ["needs revision"],
  209. retry_from=None if outcome == "passed" else "output",
  210. plan_hash=plan_hash,
  211. )
  212. await self.service.record_validation(
  213. trace_id,
  214. CandidateValidationRecord(
  215. candidate_ref=candidate,
  216. plan_hash=plan_hash,
  217. validation_result=result.model_dump(mode="json"),
  218. validated_at_sequence=candidate.created_at_sequence,
  219. ),
  220. )
  221. async def test_create_fork_merge_and_idempotent_recovery(self):
  222. first, duplicate = await asyncio.gather(
  223. self.service.manage(
  224. "root-a",
  225. operation="create",
  226. content={"text": "A"},
  227. parent_refs=[],
  228. effective_at_sequence=1,
  229. ),
  230. self.service.manage(
  231. "root-a",
  232. operation="create",
  233. content={"text": "A"},
  234. parent_refs=[],
  235. effective_at_sequence=1,
  236. ),
  237. )
  238. self.assertEqual(first, duplicate)
  239. self.assertEqual(1, self.repository.put_calls)
  240. second = await self.service.manage(
  241. "root-a",
  242. operation="create",
  243. content={"text": "B"},
  244. parent_refs=[],
  245. effective_at_sequence=2,
  246. )
  247. fork = await self.service.manage(
  248. "root-a",
  249. operation="fork",
  250. content={"text": "A2"},
  251. parent_refs=[CandidatePointer(
  252. candidate_id=first.candidate_id,
  253. revision=first.revision,
  254. )],
  255. effective_at_sequence=3,
  256. )
  257. self.assertEqual(first.candidate_id, fork.candidate_id)
  258. self.assertEqual(2, fork.revision)
  259. merged = await self.service.manage(
  260. "root-a",
  261. operation="merge",
  262. content={"text": "AB"},
  263. parent_refs=[
  264. CandidatePointer(
  265. candidate_id=fork.candidate_id,
  266. revision=fork.revision,
  267. ),
  268. CandidatePointer(
  269. candidate_id=second.candidate_id,
  270. revision=second.revision,
  271. ),
  272. ],
  273. effective_at_sequence=4,
  274. )
  275. self.assertNotIn(
  276. merged.candidate_id,
  277. {first.candidate_id, second.candidate_id},
  278. )
  279. self.assertEqual(2, len(merged.parent_refs))
  280. ledger = CandidateLedger.model_validate(
  281. await self.store.get_candidate_ledger("root-a")
  282. )
  283. self.assertEqual(4, len(ledger.candidates))
  284. self.assertTrue(all(
  285. ledger.current_state(item) == "proposed"
  286. for item in ledger.candidates
  287. ))
  288. async def test_finalize_crash_retries_same_semantic_command_identity(self):
  289. original_replace = self.store.replace_candidate_ledger
  290. writes = 0
  291. async def fail_completed_publish(root_trace_id, ledger):
  292. nonlocal writes
  293. writes += 1
  294. if writes == 2:
  295. raise OSError("simulated ledger finalize crash")
  296. await original_replace(root_trace_id, ledger)
  297. with patch.object(
  298. self.store,
  299. "replace_candidate_ledger",
  300. side_effect=fail_completed_publish,
  301. ):
  302. with self.assertRaisesRegex(
  303. RecoverableToolExecutionError,
  304. "original command ID",
  305. ):
  306. await self.service.manage(
  307. "root-a",
  308. operation="create",
  309. content={"text": "survives retry"},
  310. parent_refs=[],
  311. effective_at_sequence=2,
  312. command_id="candidate-crash-call",
  313. )
  314. pending = CandidateLedger.model_validate(
  315. await self.store.get_candidate_ledger("root-a")
  316. )
  317. self.assertEqual("pending", pending.operations[0].status)
  318. operation_id = pending.operations[0].operation_id
  319. recovered = await self.service.manage(
  320. "root-a",
  321. operation="create",
  322. content={"text": "survives retry"},
  323. parent_refs=[],
  324. effective_at_sequence=99,
  325. command_id="candidate-crash-call",
  326. )
  327. ledger = CandidateLedger.model_validate(
  328. await self.store.get_candidate_ledger("root-a")
  329. )
  330. self.assertEqual(operation_id, ledger.operations[0].operation_id)
  331. self.assertEqual("completed", ledger.operations[0].status)
  332. self.assertEqual(1, len(ledger.candidates))
  333. self.assertEqual(1, len(self.repository.contents))
  334. self.assertEqual(
  335. recovered,
  336. ledger.candidate(ledger.operations[0].candidate),
  337. )
  338. async def test_distinct_tool_calls_with_identical_payload_create_versions(self):
  339. first = await self.service.manage(
  340. "root-a",
  341. operation="create",
  342. content={"text": "same payload"},
  343. parent_refs=[],
  344. effective_at_sequence=10,
  345. command_id="candidate-call-one",
  346. )
  347. await self.store.add_message(TraceMessage.create(
  348. trace_id="root-a",
  349. role="tool",
  350. sequence=10,
  351. tool_call_id="candidate-call-one",
  352. content={"tool_name": "manage_candidate", "result": "registered"},
  353. ))
  354. await self.store.update_trace("root-a", head_sequence=10)
  355. second = await self.service.manage(
  356. "root-a",
  357. operation="create",
  358. content={"text": "same payload"},
  359. parent_refs=[],
  360. effective_at_sequence=20,
  361. command_id="candidate-call-two",
  362. )
  363. await self.store.add_message(TraceMessage.create(
  364. trace_id="root-a",
  365. role="tool",
  366. sequence=20,
  367. parent_sequence=10,
  368. tool_call_id="candidate-call-two",
  369. content={"tool_name": "manage_candidate", "result": "registered"},
  370. ))
  371. await self.store.update_trace("root-a", head_sequence=20)
  372. self.assertNotEqual(first, second)
  373. self.assertEqual(2, self.repository.put_calls)
  374. ledger = CandidateLedger.model_validate(
  375. await self.store.get_candidate_ledger("root-a")
  376. )
  377. self.assertEqual(2, len(ledger.candidates))
  378. self.assertEqual(2, len(ledger.operations))
  379. async def test_rewind_makes_future_branch_candidate_unreportable(self):
  380. await self.store.add_message(TraceMessage.create(
  381. trace_id="root-a",
  382. role="user",
  383. sequence=1,
  384. content="before candidate",
  385. ))
  386. await self.store.update_trace("root-a", head_sequence=1)
  387. candidate = await self.service.manage(
  388. "root-a",
  389. operation="create",
  390. content={"text": "future branch"},
  391. parent_refs=[],
  392. effective_at_sequence=10,
  393. command_id="future-candidate-call",
  394. )
  395. await self.store.add_message(TraceMessage.create(
  396. trace_id="root-a",
  397. role="tool",
  398. sequence=10,
  399. parent_sequence=1,
  400. tool_call_id="future-candidate-call",
  401. content={"tool_name": "manage_candidate", "result": "registered"},
  402. ))
  403. await self.store.update_trace("root-a", head_sequence=10)
  404. await self.service.validate_report_refs("root-a", [candidate])
  405. await self.store.update_trace("root-a", head_sequence=1)
  406. with self.assertRaisesRegex(
  407. CandidateStateError,
  408. "current owner Trace branch",
  409. ):
  410. await self.service.validate_report_refs("root-a", [candidate])
  411. async def test_checkpoint_update_cannot_mutate_identity_or_sequence(self):
  412. candidate = await self.service.manage(
  413. "root-a",
  414. operation="create",
  415. content={"text": "checkpoint"},
  416. parent_refs=[],
  417. effective_at_sequence=3,
  418. )
  419. plan_hash = "a" * 64
  420. await self.service.begin_validation_checkpoint(
  421. "root-a",
  422. candidate,
  423. plan={"checks": []},
  424. plan_hash=plan_hash,
  425. validated_at_sequence=3,
  426. material_usage_recorded=False,
  427. )
  428. with self.assertRaisesRegex(
  429. CandidateStateError,
  430. "fields are immutable",
  431. ):
  432. await self.service.update_validation_checkpoint(
  433. "root-a",
  434. candidate,
  435. plan_hash,
  436. validated_at_sequence=-1,
  437. )
  438. ledger = CandidateLedger.model_validate(
  439. await self.store.get_candidate_ledger("root-a")
  440. )
  441. self.assertEqual(
  442. 3,
  443. ledger.validation_checkpoints[0]["validated_at_sequence"],
  444. )
  445. async def test_cross_root_and_cross_task_parent_access_is_rejected(self):
  446. first = await self.service.manage(
  447. "root-a",
  448. operation="create",
  449. content={"text": "A"},
  450. parent_refs=[],
  451. effective_at_sequence=1,
  452. )
  453. await self._create_root("root-b")
  454. with self.assertRaisesRegex(CandidateStateError, "not found"):
  455. await self.service.manage(
  456. "root-b",
  457. operation="fork",
  458. content={"text": "stolen"},
  459. parent_refs=[CandidatePointer(
  460. candidate_id=first.candidate_id,
  461. revision=first.revision,
  462. )],
  463. effective_at_sequence=2,
  464. )
  465. await self._create_child("child-a")
  466. with self.assertRaisesRegex(CandidateStateError, "another application, root, or Task"):
  467. await self.service.manage(
  468. "child-a",
  469. operation="fork",
  470. content={"text": "stolen"},
  471. parent_refs=[CandidatePointer(
  472. candidate_id=first.candidate_id,
  473. revision=first.revision,
  474. )],
  475. effective_at_sequence=3,
  476. )
  477. async def test_bad_artifact_fails_without_registering_candidate(self):
  478. self.repository.bad_artifact = True
  479. with self.assertRaisesRegex(CandidateStateError, "invalid ArtifactRef"):
  480. await self.service.manage(
  481. "root-a",
  482. operation="create",
  483. content={"text": "bad"},
  484. parent_refs=[],
  485. effective_at_sequence=1,
  486. )
  487. ledger = CandidateLedger.model_validate(
  488. await self.store.get_candidate_ledger("root-a")
  489. )
  490. self.assertEqual(0, len(ledger.candidates))
  491. self.assertEqual("failed", ledger.operations[0].status)
  492. async def test_report_validation_rejects_tamper_and_wrong_owner(self):
  493. candidate = await self.service.manage(
  494. "root-a",
  495. operation="create",
  496. content={"text": "A"},
  497. parent_refs=[],
  498. effective_at_sequence=1,
  499. )
  500. await self.service.validate_report_refs("root-a", [candidate])
  501. tampered = candidate.model_copy(update={
  502. "artifact_ref": candidate.artifact_ref.model_copy(update={
  503. "version": "tampered",
  504. }),
  505. })
  506. with self.assertRaisesRegex(CandidateStateError, "does not match"):
  507. await self.service.validate_report_refs("root-a", [tampered])
  508. await self._create_child("child-a")
  509. with self.assertRaisesRegex(CandidateStateError, "another application, root, or Task"):
  510. await self.service.validate_report_refs("child-a", [candidate])
  511. async def test_ledger_rejects_future_lineage_and_store_reports_corruption(self):
  512. candidate = await self.service.manage(
  513. "root-a",
  514. operation="create",
  515. content={"text": "A"},
  516. parent_refs=[],
  517. effective_at_sequence=1,
  518. )
  519. raw = (await self.store.get_candidate_ledger("root-a"))
  520. future = candidate.model_copy(update={
  521. "revision": 2,
  522. "parent_refs": (CandidatePointer(
  523. candidate_id=candidate.candidate_id,
  524. revision=3,
  525. ),),
  526. })
  527. raw["candidates"].append(future.model_dump(mode="json"))
  528. with self.assertRaisesRegex(ValidationError, "unknown parent"):
  529. CandidateLedger.model_validate(raw)
  530. ledger_path = self.store._get_candidate_ledger_file("root-a")
  531. ledger_path.write_text("{broken", encoding="utf-8")
  532. with self.assertRaisesRegex(TraceStoreCorruptionError, "candidate ledger"):
  533. await self.store.get_candidate_ledger("root-a")
  534. async def test_cyclic_lineage_is_rejected_before_repository_side_effect(self):
  535. first = await self.service.manage(
  536. "root-a",
  537. operation="create",
  538. content={"text": "A"},
  539. parent_refs=[],
  540. effective_at_sequence=1,
  541. )
  542. raw = await self.store.get_candidate_ledger("root-a")
  543. second = first.model_copy(update={
  544. "candidate_id": "candidate-b",
  545. "parent_refs": (CandidatePointer(
  546. candidate_id=first.candidate_id,
  547. revision=first.revision,
  548. ),),
  549. })
  550. raw["candidates"][0]["parent_refs"] = [{
  551. "candidate_id": second.candidate_id,
  552. "revision": second.revision,
  553. }]
  554. raw["candidates"].append(second.model_dump(mode="json"))
  555. ledger_path = self.store._get_candidate_ledger_file("root-a")
  556. ledger_path.write_text(json.dumps(raw), encoding="utf-8")
  557. put_calls = self.repository.put_calls
  558. with self.assertRaisesRegex(ValidationError, "lineage cycle"):
  559. await self.service.manage(
  560. "root-a",
  561. operation="create",
  562. content={"text": "must not be persisted"},
  563. parent_refs=[],
  564. effective_at_sequence=2,
  565. )
  566. self.assertEqual(put_calls, self.repository.put_calls)
  567. async def test_review_adoption_is_idempotent_and_creates_rewind_barrier(self):
  568. await self._create_child("child-a")
  569. candidate = await self.service.manage(
  570. "child-a",
  571. operation="create",
  572. content={"text": "A"},
  573. parent_refs=[],
  574. effective_at_sequence=4,
  575. )
  576. await self._record_validation("child-a", candidate)
  577. action = CandidateReviewAction(
  578. action="adopt",
  579. candidate_ref=candidate,
  580. reason="selected exact revision",
  581. )
  582. first = await self.service.apply_review_actions(
  583. "root-a",
  584. "child-a",
  585. report_refs=[candidate],
  586. actions=[action],
  587. effective_at_sequence=9,
  588. )
  589. second = await self.service.apply_review_actions(
  590. "root-a",
  591. "child-a",
  592. report_refs=[candidate],
  593. actions=[action],
  594. effective_at_sequence=9,
  595. )
  596. self.assertEqual(first, second)
  597. self.assertEqual(1, self.repository.adoption_calls)
  598. self.assertEqual(1, len(self.repository.adoptions))
  599. with self.assertRaisesRegex(CandidateStateError, "committed"):
  600. await self.service.assert_rewind_allowed("root-a", 8)
  601. await self.service.assert_rewind_allowed("root-a", 9)
  602. with self.assertRaisesRegex(CandidateStateError, "terminal"):
  603. await self.service.apply_review_actions(
  604. "root-a",
  605. "child-a",
  606. report_refs=[candidate],
  607. actions=[CandidateReviewAction(
  608. action="discard",
  609. candidate_ref=candidate,
  610. reason="too late",
  611. )],
  612. effective_at_sequence=10,
  613. )
  614. async def test_adoption_retry_uses_same_command_after_parent_sequence_changes(self):
  615. await self._create_child("child-a")
  616. candidate = await self.service.manage(
  617. "child-a",
  618. operation="create",
  619. content={"text": "publish once"},
  620. parent_refs=[],
  621. effective_at_sequence=4,
  622. )
  623. await self._record_validation("child-a", candidate)
  624. peer = await self.service.manage(
  625. "child-a",
  626. operation="create",
  627. content={"text": "peer"},
  628. parent_refs=[],
  629. effective_at_sequence=5,
  630. )
  631. await self._record_validation("child-a", peer)
  632. action = CandidateReviewAction(
  633. action="adopt",
  634. candidate_ref=candidate,
  635. reason="stable parent decision",
  636. )
  637. first = await self.service.apply_review_actions(
  638. "root-a",
  639. "child-a",
  640. report_refs=[candidate, peer],
  641. actions=[action],
  642. effective_at_sequence=10,
  643. command_id="adoption-review-call",
  644. )
  645. recovered = await self.service.apply_review_actions(
  646. "root-a",
  647. "child-a",
  648. report_refs=[candidate, peer],
  649. actions=[action],
  650. effective_at_sequence=999,
  651. command_id="adoption-review-call",
  652. )
  653. self.assertEqual(first, recovered)
  654. self.assertEqual(1, self.repository.adoption_calls)
  655. self.assertEqual(1, len(self.repository.adoptions))
  656. with self.assertRaisesRegex(
  657. CandidateStateError,
  658. "review batch payload changed",
  659. ):
  660. await self.service.apply_review_actions(
  661. "root-a",
  662. "child-a",
  663. report_refs=[candidate, peer],
  664. actions=[action.model_copy(update={
  665. "reason": "tampered decision payload",
  666. })],
  667. effective_at_sequence=1_000,
  668. command_id="adoption-review-call",
  669. )
  670. self.assertEqual(1, self.repository.adoption_calls)
  671. with self.assertRaisesRegex(
  672. CandidateStateError,
  673. "review batch payload changed",
  674. ):
  675. await self.service.apply_review_actions(
  676. "root-a",
  677. "child-a",
  678. report_refs=[candidate, peer],
  679. actions=[
  680. action,
  681. CandidateReviewAction(
  682. action="discard",
  683. candidate_ref=peer,
  684. reason="injected tail action",
  685. ),
  686. ],
  687. effective_at_sequence=1_001,
  688. command_id="adoption-review-call",
  689. )
  690. self.assertEqual("proposed", (
  691. CandidateLedger.model_validate(
  692. await self.store.get_candidate_ledger("root-a")
  693. ).current_state(peer)
  694. ))
  695. with self.assertRaisesRegex(
  696. CandidateStateError,
  697. "review batch payload changed",
  698. ):
  699. await self.service.apply_review_actions(
  700. "root-a",
  701. "child-a",
  702. report_refs=[candidate, peer],
  703. actions=[],
  704. effective_at_sequence=1_002,
  705. command_id="adoption-review-call",
  706. )
  707. async def test_review_batch_replay_rejects_deleted_and_reordered_actions(self):
  708. await self._create_child("child-a")
  709. candidates = []
  710. for sequence, text in ((4, "A"), (5, "B")):
  711. candidate = await self.service.manage(
  712. "child-a",
  713. operation="create",
  714. content={"text": text},
  715. parent_refs=[],
  716. effective_at_sequence=sequence,
  717. )
  718. await self._record_validation("child-a", candidate)
  719. candidates.append(candidate)
  720. actions = [
  721. CandidateReviewAction(
  722. action="discard",
  723. candidate_ref=candidate,
  724. reason=f"discard {candidate.candidate_id}",
  725. )
  726. for candidate in candidates
  727. ]
  728. await self.service.apply_review_actions(
  729. "root-a",
  730. "child-a",
  731. report_refs=candidates,
  732. actions=actions,
  733. effective_at_sequence=10,
  734. command_id="two-action-review",
  735. )
  736. for altered in (actions[:1], list(reversed(actions))):
  737. with self.assertRaisesRegex(
  738. CandidateStateError,
  739. "review batch payload changed",
  740. ):
  741. await self.service.apply_review_actions(
  742. "root-a",
  743. "child-a",
  744. report_refs=candidates,
  745. actions=altered,
  746. effective_at_sequence=999,
  747. command_id="two-action-review",
  748. )
  749. async def test_empty_review_batch_cannot_gain_an_action_during_replay(self):
  750. await self._create_child("child-a")
  751. candidate = await self.service.manage(
  752. "child-a",
  753. operation="create",
  754. content={"text": "A"},
  755. parent_refs=[],
  756. effective_at_sequence=4,
  757. )
  758. await self._record_validation("child-a", candidate)
  759. self.assertEqual([], await self.service.apply_review_actions(
  760. "root-a",
  761. "child-a",
  762. report_refs=[candidate],
  763. actions=[],
  764. effective_at_sequence=10,
  765. command_id="empty-review-batch",
  766. ))
  767. with self.assertRaisesRegex(
  768. CandidateStateError,
  769. "review batch payload changed",
  770. ):
  771. await self.service.apply_review_actions(
  772. "root-a",
  773. "child-a",
  774. report_refs=[candidate],
  775. actions=[CandidateReviewAction(
  776. action="discard",
  777. candidate_ref=candidate,
  778. reason="injected after empty batch",
  779. )],
  780. effective_at_sequence=999,
  781. command_id="empty-review-batch",
  782. )
  783. self.assertEqual(
  784. "proposed",
  785. CandidateLedger.model_validate(
  786. await self.store.get_candidate_ledger("root-a")
  787. ).current_state(candidate),
  788. )
  789. async def test_review_capacity_rejects_before_envelope_or_repository_write(self):
  790. await self._create_child("child-a")
  791. candidate = await self.service.manage(
  792. "child-a",
  793. operation="create",
  794. content={"text": "capacity"},
  795. parent_refs=[],
  796. effective_at_sequence=4,
  797. )
  798. await self._record_validation("child-a", candidate)
  799. ledger = CandidateLedger.model_validate(
  800. await self.store.get_candidate_ledger("root-a")
  801. )
  802. fillers = [
  803. CandidateOperationRecord(
  804. operation_id=f"capacity-filler-{index}",
  805. operation="review_batch",
  806. input_hash="0" * 64,
  807. status="completed",
  808. )
  809. for index in range(
  810. MAX_CANDIDATE_OPERATIONS_PER_ROOT - len(ledger.operations)
  811. )
  812. ]
  813. saturated = CandidateLedger.model_validate({
  814. **ledger.model_dump(mode="json"),
  815. "operations": [
  816. *[item.model_dump(mode="json") for item in ledger.operations],
  817. *[item.model_dump(mode="json") for item in fillers],
  818. ],
  819. })
  820. await self.store.replace_candidate_ledger(
  821. "root-a",
  822. saturated.model_dump(mode="json"),
  823. )
  824. before = await self.store.get_candidate_ledger("root-a")
  825. with self.assertRaisesRegex(
  826. CandidateStateError,
  827. "operation limit exceeded before execution",
  828. ):
  829. await self.service.apply_review_actions(
  830. "root-a",
  831. "child-a",
  832. report_refs=[candidate],
  833. actions=[CandidateReviewAction(
  834. action="adopt",
  835. candidate_ref=candidate,
  836. reason="must not reach repository",
  837. )],
  838. effective_at_sequence=10,
  839. command_id="capacity-overflow-review",
  840. )
  841. self.assertEqual(0, self.repository.adoption_calls)
  842. self.assertEqual(before, await self.store.get_candidate_ledger("root-a"))
  843. async def test_review_capacity_allows_exact_envelope_and_action_boundary(self):
  844. await self._create_child("child-a")
  845. candidate = await self.service.manage(
  846. "child-a",
  847. operation="create",
  848. content={"text": "exact capacity"},
  849. parent_refs=[],
  850. effective_at_sequence=4,
  851. )
  852. await self._record_validation("child-a", candidate)
  853. ledger = CandidateLedger.model_validate(
  854. await self.store.get_candidate_ledger("root-a")
  855. )
  856. target = MAX_CANDIDATE_OPERATIONS_PER_ROOT - 2
  857. fillers = [
  858. CandidateOperationRecord(
  859. operation_id=f"exact-filler-{index}",
  860. operation="review_batch",
  861. input_hash="1" * 64,
  862. status="completed",
  863. )
  864. for index in range(target - len(ledger.operations))
  865. ]
  866. near_limit = CandidateLedger.model_validate({
  867. **ledger.model_dump(mode="json"),
  868. "operations": [
  869. *[item.model_dump(mode="json") for item in ledger.operations],
  870. *[item.model_dump(mode="json") for item in fillers],
  871. ],
  872. })
  873. await self.store.replace_candidate_ledger(
  874. "root-a",
  875. near_limit.model_dump(mode="json"),
  876. )
  877. await self.service.apply_review_actions(
  878. "root-a",
  879. "child-a",
  880. report_refs=[candidate],
  881. actions=[CandidateReviewAction(
  882. action="discard",
  883. candidate_ref=candidate,
  884. reason="fits exact operation boundary",
  885. )],
  886. effective_at_sequence=10,
  887. command_id="exact-capacity-review",
  888. )
  889. completed = CandidateLedger.model_validate(
  890. await self.store.get_candidate_ledger("root-a")
  891. )
  892. self.assertEqual(MAX_CANDIDATE_OPERATIONS_PER_ROOT, len(completed.operations))
  893. self.assertEqual("discarded", completed.current_state(candidate))
  894. async def test_review_batch_reserves_action_slot_across_crash_recovery(self):
  895. await self._create_child("child-a")
  896. candidate = await self.service.manage(
  897. "child-a",
  898. operation="create",
  899. content={"text": "reserved review"},
  900. parent_refs=[],
  901. effective_at_sequence=4,
  902. )
  903. await self._record_validation("child-a", candidate)
  904. ledger = CandidateLedger.model_validate(
  905. await self.store.get_candidate_ledger("root-a")
  906. )
  907. target = MAX_CANDIDATE_OPERATIONS_PER_ROOT - 2
  908. fillers = [
  909. CandidateOperationRecord(
  910. operation_id=f"review-reservation-filler-{index}",
  911. operation="review_batch",
  912. input_hash="2" * 64,
  913. status="completed",
  914. )
  915. for index in range(target - len(ledger.operations))
  916. ]
  917. near_limit = CandidateLedger.model_validate({
  918. **ledger.model_dump(mode="json"),
  919. "operations": [
  920. *[item.model_dump(mode="json") for item in ledger.operations],
  921. *[item.model_dump(mode="json") for item in fillers],
  922. ],
  923. })
  924. await self.store.replace_candidate_ledger(
  925. "root-a",
  926. near_limit.model_dump(mode="json"),
  927. )
  928. action = CandidateReviewAction(
  929. action="adopt",
  930. candidate_ref=candidate,
  931. reason="reserve the complete review batch",
  932. )
  933. original_replace = self.store.replace_candidate_ledger
  934. writes = 0
  935. async def crash_after_batch_reservation(root_trace_id, raw_ledger):
  936. nonlocal writes
  937. writes += 1
  938. if writes == 2:
  939. raise OSError("crash after review reservation")
  940. await original_replace(root_trace_id, raw_ledger)
  941. with patch.object(
  942. self.store,
  943. "replace_candidate_ledger",
  944. side_effect=crash_after_batch_reservation,
  945. ):
  946. with self.assertRaisesRegex(OSError, "review reservation"):
  947. await self.service.apply_review_actions(
  948. "root-a",
  949. "child-a",
  950. report_refs=[candidate],
  951. actions=[action],
  952. effective_at_sequence=10,
  953. command_id="capacity-reserved-review",
  954. )
  955. reserved = CandidateLedger.model_validate(
  956. await self.store.get_candidate_ledger("root-a")
  957. )
  958. self.assertEqual(MAX_CANDIDATE_OPERATIONS_PER_ROOT, len(reserved.operations))
  959. self.assertEqual(2, sum(
  960. item.status == "pending" for item in reserved.operations
  961. ))
  962. repository_version_calls = self.repository.put_calls
  963. with self.assertRaisesRegex(
  964. CandidateStateError,
  965. "operation limit exceeded before execution",
  966. ):
  967. await self.service.manage(
  968. "child-a",
  969. operation="create",
  970. content={"text": "must not steal review capacity"},
  971. parent_refs=[],
  972. effective_at_sequence=11,
  973. command_id="sibling-after-review-reservation",
  974. )
  975. self.assertEqual(repository_version_calls, self.repository.put_calls)
  976. records = await self.service.apply_review_actions(
  977. "root-a",
  978. "child-a",
  979. report_refs=[candidate],
  980. actions=[action],
  981. effective_at_sequence=999,
  982. command_id="capacity-reserved-review",
  983. )
  984. self.assertEqual("adopted", records[0].state)
  985. self.assertEqual(1, self.repository.adoption_calls)
  986. completed = CandidateLedger.model_validate(
  987. await self.store.get_candidate_ledger("root-a")
  988. )
  989. self.assertEqual(MAX_CANDIDATE_OPERATIONS_PER_ROOT, len(completed.operations))
  990. self.assertTrue(all(
  991. item.status == "completed"
  992. for item in completed.operations
  993. if item.command_id == "capacity-reserved-review"
  994. ))
  995. async def test_candidate_capacity_rejects_before_repository_or_intent_write(self):
  996. await self._create_child("child-a")
  997. candidate = await self.service.manage(
  998. "child-a",
  999. operation="create",
  1000. content={"text": "seed"},
  1001. parent_refs=[],
  1002. effective_at_sequence=4,
  1003. )
  1004. ledger = CandidateLedger.model_validate(
  1005. await self.store.get_candidate_ledger("root-a")
  1006. )
  1007. saturated_candidates = [candidate]
  1008. saturated_candidates.extend(
  1009. candidate.model_copy(update={
  1010. "candidate_id": f"capacity-candidate-{index}",
  1011. })
  1012. for index in range(1, MAX_CANDIDATES_PER_ROOT)
  1013. )
  1014. saturated = CandidateLedger.model_validate({
  1015. **ledger.model_dump(mode="json"),
  1016. "candidates": [
  1017. item.model_dump(mode="json") for item in saturated_candidates
  1018. ],
  1019. })
  1020. await self.store.replace_candidate_ledger(
  1021. "root-a",
  1022. saturated.model_dump(mode="json"),
  1023. )
  1024. before = await self.store.get_candidate_ledger("root-a")
  1025. repository_calls = self.repository.put_calls
  1026. with self.assertRaisesRegex(
  1027. CandidateStateError,
  1028. "candidate limit exceeded before execution",
  1029. ):
  1030. await self.service.manage(
  1031. "child-a",
  1032. operation="create",
  1033. content={"text": "must remain external-orphan free"},
  1034. parent_refs=[],
  1035. effective_at_sequence=5,
  1036. command_id="candidate-capacity-overflow",
  1037. )
  1038. self.assertEqual(repository_calls, self.repository.put_calls)
  1039. self.assertEqual(before, await self.store.get_candidate_ledger("root-a"))
  1040. async def test_pending_candidate_reserves_capacity_until_recovery(self):
  1041. await self._create_child("child-a")
  1042. seed = await self.service.manage(
  1043. "child-a",
  1044. operation="create",
  1045. content={"text": "seed"},
  1046. parent_refs=[],
  1047. effective_at_sequence=4,
  1048. )
  1049. ledger = CandidateLedger.model_validate(
  1050. await self.store.get_candidate_ledger("root-a")
  1051. )
  1052. near_limit_candidates = [seed]
  1053. near_limit_candidates.extend(
  1054. seed.model_copy(update={
  1055. "candidate_id": f"reserved-candidate-{index}",
  1056. })
  1057. for index in range(1, MAX_CANDIDATES_PER_ROOT - 1)
  1058. )
  1059. near_limit = CandidateLedger.model_validate({
  1060. **ledger.model_dump(mode="json"),
  1061. "candidates": [
  1062. item.model_dump(mode="json") for item in near_limit_candidates
  1063. ],
  1064. })
  1065. await self.store.replace_candidate_ledger(
  1066. "root-a",
  1067. near_limit.model_dump(mode="json"),
  1068. )
  1069. original_replace = self.store.replace_candidate_ledger
  1070. writes = 0
  1071. async def crash_after_repository(root_trace_id, raw_ledger):
  1072. nonlocal writes
  1073. writes += 1
  1074. if writes == 2:
  1075. raise OSError("crash before candidate publish")
  1076. await original_replace(root_trace_id, raw_ledger)
  1077. with patch.object(
  1078. self.store,
  1079. "replace_candidate_ledger",
  1080. side_effect=crash_after_repository,
  1081. ):
  1082. with self.assertRaisesRegex(
  1083. RecoverableToolExecutionError,
  1084. "original command ID",
  1085. ):
  1086. await self.service.manage(
  1087. "child-a",
  1088. operation="create",
  1089. content={"text": "reserved A"},
  1090. parent_refs=[],
  1091. effective_at_sequence=5,
  1092. command_id="reserved-candidate-A",
  1093. )
  1094. pending = CandidateLedger.model_validate(
  1095. await self.store.get_candidate_ledger("root-a")
  1096. )
  1097. self.assertEqual(MAX_CANDIDATES_PER_ROOT - 1, len(pending.candidates))
  1098. self.assertEqual(
  1099. 1,
  1100. sum(
  1101. item.status == "pending" and item.operation == "create"
  1102. for item in pending.operations
  1103. ),
  1104. )
  1105. calls_after_a = self.repository.put_calls
  1106. with self.assertRaisesRegex(
  1107. CandidateStateError,
  1108. "candidate limit exceeded before execution",
  1109. ):
  1110. await self.service.manage(
  1111. "child-a",
  1112. operation="create",
  1113. content={"text": "must not steal A's slot"},
  1114. parent_refs=[],
  1115. effective_at_sequence=6,
  1116. command_id="reserved-candidate-B",
  1117. )
  1118. self.assertEqual(calls_after_a, self.repository.put_calls)
  1119. recovered = await self.service.manage(
  1120. "child-a",
  1121. operation="create",
  1122. content={"text": "reserved A"},
  1123. parent_refs=[],
  1124. effective_at_sequence=99,
  1125. command_id="reserved-candidate-A",
  1126. )
  1127. completed = CandidateLedger.model_validate(
  1128. await self.store.get_candidate_ledger("root-a")
  1129. )
  1130. self.assertEqual(MAX_CANDIDATES_PER_ROOT, len(completed.candidates))
  1131. self.assertEqual(recovered, completed.candidate(recovered))
  1132. async def test_runner_replays_pending_candidate_with_original_tool_call_id(self):
  1133. await self._create_child("child-a")
  1134. registry = get_tool_registry().clone(["manage_candidate"])
  1135. runner = AgentRunner(
  1136. trace_store=self.store,
  1137. tool_registry=registry,
  1138. llm_call=lambda **_kwargs: None,
  1139. application_binding=self.binding,
  1140. candidate_service=self.service,
  1141. )
  1142. config = RunConfig(
  1143. tools=["manage_candidate"],
  1144. tool_groups=[],
  1145. auto_execute_tools=True,
  1146. )
  1147. request = {
  1148. "request": {
  1149. "operation": "create",
  1150. "content": {"text": "recover with the original command"},
  1151. "parent_refs": [],
  1152. },
  1153. }
  1154. assistant = TraceMessage.create(
  1155. trace_id="child-a",
  1156. role="assistant",
  1157. sequence=4,
  1158. content={
  1159. "text": "",
  1160. "tool_calls": [{
  1161. "id": "recoverable-candidate-call",
  1162. "type": "function",
  1163. "function": {
  1164. "name": "manage_candidate",
  1165. "arguments": json.dumps(request),
  1166. },
  1167. }],
  1168. },
  1169. )
  1170. await self.store.add_message(assistant)
  1171. await self.store.update_trace(
  1172. "child-a",
  1173. head_sequence=4,
  1174. last_sequence=4,
  1175. )
  1176. trace = await self.store.get_trace("child-a")
  1177. original_replace = self.store.replace_candidate_ledger
  1178. writes = 0
  1179. async def fail_first_publish(root_trace_id, raw_ledger):
  1180. nonlocal writes
  1181. writes += 1
  1182. if writes == 2:
  1183. raise OSError("candidate publish interrupted")
  1184. await original_replace(root_trace_id, raw_ledger)
  1185. with patch.object(
  1186. self.store,
  1187. "replace_candidate_ledger",
  1188. side_effect=fail_first_publish,
  1189. ):
  1190. with self.assertRaises(RecoverableToolExecutionError):
  1191. await registry.execute(
  1192. "manage_candidate",
  1193. request,
  1194. context=runner._build_tool_context(
  1195. config=config,
  1196. trace=trace,
  1197. trace_id=trace.trace_id,
  1198. goal_id=None,
  1199. goal_tree=None,
  1200. sequence=5,
  1201. head_sequence=4,
  1202. tool_call_id="recoverable-candidate-call",
  1203. side_branch_ctx=None,
  1204. trigger_event=None,
  1205. ),
  1206. allowed_tool_names={"manage_candidate"},
  1207. tool_call_id="recoverable-candidate-call",
  1208. )
  1209. pending = CandidateLedger.model_validate(
  1210. await self.store.get_candidate_ledger("root-a")
  1211. )
  1212. self.assertEqual("pending", pending.operations[-1].status)
  1213. self.assertEqual(1, len(self.repository.contents))
  1214. self.assertFalse(any(
  1215. item.role == "tool"
  1216. for item in await self.store.get_trace_messages("child-a")
  1217. ))
  1218. healed, next_sequence = await runner._heal_orphaned_tool_calls(
  1219. [assistant],
  1220. await self.store.get_trace("child-a"),
  1221. None,
  1222. config,
  1223. 5,
  1224. )
  1225. self.assertEqual(6, next_sequence)
  1226. self.assertEqual("tool", healed[-1].role)
  1227. self.assertEqual(
  1228. "recoverable-candidate-call",
  1229. healed[-1].tool_call_id,
  1230. )
  1231. self.assertEqual(1, len(self.repository.contents))
  1232. completed = CandidateLedger.model_validate(
  1233. await self.store.get_candidate_ledger("root-a")
  1234. )
  1235. matching = [
  1236. item for item in completed.operations
  1237. if item.command_id == "recoverable-candidate-call"
  1238. ]
  1239. self.assertEqual(1, len(matching))
  1240. self.assertEqual("completed", matching[0].status)
  1241. self.assertEqual(1, len(completed.candidates))
  1242. async def test_approved_candidate_publish_failure_keeps_original_grant(self):
  1243. await self._create_child("child-a")
  1244. registry = get_tool_registry().clone(["manage_candidate"])
  1245. runner = AgentRunner(
  1246. trace_store=self.store,
  1247. tool_registry=registry,
  1248. llm_call=lambda **_kwargs: None,
  1249. application_binding=self.binding,
  1250. candidate_service=self.service,
  1251. )
  1252. request = {
  1253. "request": {
  1254. "operation": "create",
  1255. "content": {"text": "approved durable candidate"},
  1256. "parent_refs": [],
  1257. },
  1258. }
  1259. assistant = TraceMessage.create(
  1260. trace_id="child-a",
  1261. role="assistant",
  1262. sequence=4,
  1263. content={
  1264. "text": "",
  1265. "tool_calls": [{
  1266. "id": "approved-recoverable-candidate",
  1267. "type": "function",
  1268. "function": {
  1269. "name": "manage_candidate",
  1270. "arguments": json.dumps(request),
  1271. },
  1272. }],
  1273. },
  1274. )
  1275. await self.store.add_message(assistant)
  1276. await self.store.update_trace("child-a", head_sequence=4, last_sequence=4)
  1277. batch = runner._create_tool_approval_batch(
  1278. trace_id="child-a",
  1279. assistant_msg=assistant,
  1280. tool_calls=assistant.content["tool_calls"],
  1281. auto_execute_tools=False,
  1282. )
  1283. batch.calls[0].decision = "approved"
  1284. batch.status = "decided"
  1285. await self.store.replace_tool_approval_batch("child-a", batch)
  1286. config = RunConfig(
  1287. trace_id="child-a",
  1288. uid="user-1",
  1289. tools=["manage_candidate"],
  1290. tool_groups=[],
  1291. auto_execute_tools=False,
  1292. approval_batch_id=batch.batch_id,
  1293. )
  1294. original_replace = self.store.replace_candidate_ledger
  1295. writes = 0
  1296. async def fail_first_terminal_publish(root_trace_id, raw_ledger):
  1297. nonlocal writes
  1298. writes += 1
  1299. if writes == 2:
  1300. raise OSError("approved candidate terminal publish interrupted")
  1301. await original_replace(root_trace_id, raw_ledger)
  1302. trace = await self.store.get_trace("child-a")
  1303. original_approval_replace = self.store.replace_tool_approval_batch
  1304. approval_writes = 0
  1305. async def fail_recoverable_approval_publish(trace_id, raw_batch):
  1306. nonlocal approval_writes
  1307. approval_writes += 1
  1308. if approval_writes == 3:
  1309. raise OSError("recoverable approval state publish interrupted")
  1310. await original_approval_replace(trace_id, raw_batch)
  1311. with patch.object(
  1312. self.store,
  1313. "replace_candidate_ledger",
  1314. side_effect=fail_first_terminal_publish,
  1315. ), patch.object(
  1316. self.store,
  1317. "replace_tool_approval_batch",
  1318. side_effect=fail_recoverable_approval_publish,
  1319. ):
  1320. with self.assertRaisesRegex(
  1321. OSError,
  1322. "recoverable approval state publish interrupted",
  1323. ):
  1324. await runner._resume_approved_tool_batch(
  1325. trace=trace,
  1326. history=[assistant.to_llm_dict()],
  1327. goal_tree=None,
  1328. config=config,
  1329. sequence=5,
  1330. head_seq=4,
  1331. side_branch_ctx=None,
  1332. runtime_tool_names={"manage_candidate"},
  1333. )
  1334. interrupted = await self.store.get_tool_approval_batch("child-a")
  1335. self.assertEqual("executing", interrupted.status)
  1336. self.assertEqual("executing", interrupted.calls[0].execution_status)
  1337. self.assertFalse(
  1338. await runner._mark_approval_execution_unknown("child-a")
  1339. )
  1340. recoverable = await self.store.get_tool_approval_batch("child-a")
  1341. self.assertEqual("recoverable_candidate_command", recoverable.status)
  1342. self.assertEqual("approved", recoverable.calls[0].decision)
  1343. self.assertEqual("not_started", recoverable.calls[0].execution_status)
  1344. self.assertEqual(
  1345. "approved-recoverable-candidate",
  1346. recoverable.calls[0].tool_call_id,
  1347. )
  1348. with self.assertRaisesRegex(
  1349. ValueError,
  1350. "recoverable_candidate_command_must_resume_first",
  1351. ):
  1352. await runner._prepare_trace(
  1353. [{"role": "user", "content": "change direction"}],
  1354. RunConfig(trace_id="child-a"),
  1355. )
  1356. with self.assertRaisesRegex(
  1357. ValueError,
  1358. "recoverable_candidate_command_must_resume_first",
  1359. ):
  1360. await runner._prepare_trace(
  1361. [],
  1362. RunConfig(trace_id="child-a", after_sequence=3),
  1363. )
  1364. from cyber_agent.trace import run_api
  1365. async def restore_for_api(**_kwargs):
  1366. return runner, RunConfig(
  1367. trace_id="child-a",
  1368. approval_batch_id=recoverable.batch_id,
  1369. )
  1370. with patch.object(run_api, "_get_runner", return_value=runner), patch.object(
  1371. run_api,
  1372. "_restore_runner_and_config",
  1373. side_effect=restore_for_api,
  1374. ):
  1375. with self.assertRaisesRegex(
  1376. run_api.HTTPException,
  1377. "recoverable_candidate_command_must_resume_first",
  1378. ) as blocked_api:
  1379. await run_api.run_trace(
  1380. "child-a",
  1381. run_api.TraceRunRequest(messages=[{
  1382. "role": "user",
  1383. "content": "must wait for candidate recovery",
  1384. }]),
  1385. )
  1386. self.assertEqual(409, blocked_api.exception.status_code)
  1387. resumed_config = config
  1388. resumed_config.approval_batch_id = recoverable.batch_id
  1389. _history, next_sequence, head_sequence = (
  1390. await runner._resume_approved_tool_batch(
  1391. trace=await self.store.get_trace("child-a"),
  1392. history=[assistant.to_llm_dict()],
  1393. goal_tree=None,
  1394. config=resumed_config,
  1395. sequence=5,
  1396. head_seq=4,
  1397. side_branch_ctx=None,
  1398. runtime_tool_names={"manage_candidate"},
  1399. )
  1400. )
  1401. completed_batch = await self.store.get_tool_approval_batch("child-a")
  1402. completed_ledger = CandidateLedger.model_validate(
  1403. await self.store.get_candidate_ledger("root-a")
  1404. )
  1405. self.assertEqual("completed", completed_batch.status)
  1406. self.assertEqual(6, next_sequence)
  1407. self.assertEqual(5, head_sequence)
  1408. self.assertEqual(1, len(completed_ledger.candidates))
  1409. self.assertEqual(1, len(self.repository.contents))
  1410. self.assertEqual(2, self.repository.put_calls)
  1411. # Crash window: the Tool Result is durable, while the last approval
  1412. # update still shows the call as executing. Recovery must finalize the
  1413. # existing message instead of replaying the candidate command.
  1414. completed_batch.status = "executing"
  1415. completed_batch.calls[0].execution_status = "executing"
  1416. completed_batch.calls[0].result_message_id = None
  1417. await self.store.replace_tool_approval_batch("child-a", completed_batch)
  1418. await self.store.update_trace("child-a", head_sequence=4)
  1419. self.assertTrue(
  1420. await runner._recover_candidate_approval_if_durable(
  1421. "child-a",
  1422. completed_batch,
  1423. )
  1424. )
  1425. reconciled = await self.store.get_tool_approval_batch("child-a")
  1426. trace_after_reconcile = await self.store.get_trace("child-a")
  1427. matching_results = [
  1428. message
  1429. for message in await self.store.get_trace_messages("child-a")
  1430. if message.role == "tool"
  1431. and message.tool_call_id == "approved-recoverable-candidate"
  1432. ]
  1433. self.assertEqual("completed", reconciled.status)
  1434. self.assertEqual("executed", reconciled.calls[0].execution_status)
  1435. self.assertEqual(
  1436. matching_results[0].message_id,
  1437. reconciled.calls[0].result_message_id,
  1438. )
  1439. self.assertEqual(
  1440. matching_results[0].sequence,
  1441. trace_after_reconcile.head_sequence,
  1442. )
  1443. self.assertEqual(1, len(matching_results))
  1444. self.assertEqual(2, self.repository.put_calls)
  1445. async def test_failed_outcome_publish_failure_remains_orphan_replayable(self):
  1446. await self._create_child("child-a")
  1447. self.repository.bad_artifact = True
  1448. registry = get_tool_registry().clone(["manage_candidate"])
  1449. runner = AgentRunner(
  1450. trace_store=self.store,
  1451. tool_registry=registry,
  1452. llm_call=lambda **_kwargs: None,
  1453. application_binding=self.binding,
  1454. candidate_service=self.service,
  1455. )
  1456. config = RunConfig(
  1457. tools=["manage_candidate"],
  1458. tool_groups=[],
  1459. auto_execute_tools=True,
  1460. )
  1461. request = {
  1462. "request": {
  1463. "operation": "create",
  1464. "content": {"text": "invalid artifact candidate"},
  1465. "parent_refs": [],
  1466. },
  1467. }
  1468. assistant = TraceMessage.create(
  1469. trace_id="child-a",
  1470. role="assistant",
  1471. sequence=4,
  1472. content={
  1473. "text": "",
  1474. "tool_calls": [{
  1475. "id": "failed-publish-candidate",
  1476. "type": "function",
  1477. "function": {
  1478. "name": "manage_candidate",
  1479. "arguments": json.dumps(request),
  1480. },
  1481. }],
  1482. },
  1483. )
  1484. await self.store.add_message(assistant)
  1485. await self.store.update_trace("child-a", head_sequence=4, last_sequence=4)
  1486. trace = await self.store.get_trace("child-a")
  1487. original_replace = self.store.replace_candidate_ledger
  1488. writes = 0
  1489. async def fail_first_failed_publish(root_trace_id, raw_ledger):
  1490. nonlocal writes
  1491. writes += 1
  1492. if writes == 2:
  1493. raise OSError("failed outcome publish interrupted")
  1494. await original_replace(root_trace_id, raw_ledger)
  1495. with patch.object(
  1496. self.store,
  1497. "replace_candidate_ledger",
  1498. side_effect=fail_first_failed_publish,
  1499. ):
  1500. with self.assertRaises(RecoverableToolExecutionError):
  1501. await registry.execute(
  1502. "manage_candidate",
  1503. request,
  1504. context=runner._build_tool_context(
  1505. config=config,
  1506. trace=trace,
  1507. trace_id=trace.trace_id,
  1508. goal_id=None,
  1509. goal_tree=None,
  1510. sequence=5,
  1511. head_sequence=4,
  1512. tool_call_id="failed-publish-candidate",
  1513. side_branch_ctx=None,
  1514. trigger_event=None,
  1515. ),
  1516. allowed_tool_names={"manage_candidate"},
  1517. tool_call_id="failed-publish-candidate",
  1518. )
  1519. pending = CandidateLedger.model_validate(
  1520. await self.store.get_candidate_ledger("root-a")
  1521. )
  1522. self.assertEqual("pending", pending.operations[-1].status)
  1523. self.assertFalse(any(
  1524. item.role == "tool"
  1525. for item in await self.store.get_trace_messages("child-a")
  1526. ))
  1527. healed, next_sequence = await runner._heal_orphaned_tool_calls(
  1528. [assistant],
  1529. await self.store.get_trace("child-a"),
  1530. None,
  1531. config,
  1532. 5,
  1533. )
  1534. terminal = CandidateLedger.model_validate(
  1535. await self.store.get_candidate_ledger("root-a")
  1536. )
  1537. self.assertEqual(6, next_sequence)
  1538. self.assertEqual("tool", healed[-1].role)
  1539. self.assertEqual("failed-publish-candidate", healed[-1].tool_call_id)
  1540. self.assertEqual("failed", terminal.operations[-1].status)
  1541. self.assertEqual(0, len(terminal.candidates))
  1542. async def test_pending_recovery_survives_transient_repository_error(self):
  1543. await self._create_child("child-a")
  1544. command_id = "transient-recovery-candidate"
  1545. request = {
  1546. "operation": "create",
  1547. "content": {"text": "eventually consistent candidate"},
  1548. "parent_refs": [],
  1549. "effective_at_sequence": 5,
  1550. "command_id": command_id,
  1551. }
  1552. original_replace = self.store.replace_candidate_ledger
  1553. writes = 0
  1554. async def fail_first_terminal_publish(root_trace_id, raw_ledger):
  1555. nonlocal writes
  1556. writes += 1
  1557. if writes == 2:
  1558. raise OSError("candidate terminal publish interrupted")
  1559. await original_replace(root_trace_id, raw_ledger)
  1560. with patch.object(
  1561. self.store,
  1562. "replace_candidate_ledger",
  1563. side_effect=fail_first_terminal_publish,
  1564. ):
  1565. with self.assertRaises(RecoverableToolExecutionError):
  1566. await self.service.manage("child-a", **request)
  1567. with patch.object(
  1568. self.repository,
  1569. "put_version",
  1570. side_effect=ValueError("repository temporarily unavailable"),
  1571. ):
  1572. with self.assertRaises(RecoverableToolExecutionError):
  1573. await self.service.manage("child-a", **request)
  1574. still_pending = CandidateLedger.model_validate(
  1575. await self.store.get_candidate_ledger("root-a")
  1576. )
  1577. self.assertEqual("pending", still_pending.operations[-1].status)
  1578. with patch.object(
  1579. self.repository,
  1580. "resolve",
  1581. side_effect=RuntimeError("artifact resolver temporarily unavailable"),
  1582. ):
  1583. with self.assertRaises(RecoverableToolExecutionError):
  1584. await self.service.manage("child-a", **request)
  1585. still_pending = CandidateLedger.model_validate(
  1586. await self.store.get_candidate_ledger("root-a")
  1587. )
  1588. self.assertEqual("pending", still_pending.operations[-1].status)
  1589. recovered = await self.service.manage("child-a", **request)
  1590. completed = CandidateLedger.model_validate(
  1591. await self.store.get_candidate_ledger("root-a")
  1592. )
  1593. self.assertEqual(recovered, completed.candidates[-1])
  1594. self.assertEqual("completed", completed.operations[-1].status)
  1595. self.assertEqual(1, len(self.repository.contents))
  1596. async def test_first_repository_timeout_after_commit_remains_replayable(self):
  1597. await self._create_child("child-a")
  1598. request = {
  1599. "operation": "create",
  1600. "content": {"text": "committed before response timeout"},
  1601. "parent_refs": [],
  1602. "effective_at_sequence": 5,
  1603. "command_id": "first-call-timeout-candidate",
  1604. }
  1605. original_put = self.repository.put_version
  1606. async def commit_then_timeout(version_request):
  1607. await original_put(version_request)
  1608. raise TimeoutError("response was lost after commit")
  1609. with patch.object(
  1610. self.repository,
  1611. "put_version",
  1612. side_effect=commit_then_timeout,
  1613. ):
  1614. with self.assertRaises(RecoverableToolExecutionError):
  1615. await self.service.manage("child-a", **request)
  1616. pending = CandidateLedger.model_validate(
  1617. await self.store.get_candidate_ledger("root-a")
  1618. )
  1619. self.assertEqual("pending", pending.operations[-1].status)
  1620. self.assertEqual(1, len(self.repository.contents))
  1621. recovered = await self.service.manage("child-a", **request)
  1622. completed = CandidateLedger.model_validate(
  1623. await self.store.get_candidate_ledger("root-a")
  1624. )
  1625. self.assertEqual(recovered, completed.candidates[-1])
  1626. self.assertEqual("completed", completed.operations[-1].status)
  1627. self.assertEqual(1, len(self.repository.contents))
  1628. async def test_typed_repository_rejection_is_terminal(self):
  1629. await self._create_child("child-a")
  1630. with patch.object(
  1631. self.repository,
  1632. "put_version",
  1633. side_effect=CandidateRepositoryRejected("content policy rejected"),
  1634. ):
  1635. with self.assertRaisesRegex(
  1636. CandidateStateError,
  1637. "content policy rejected",
  1638. ):
  1639. await self.service.manage(
  1640. "child-a",
  1641. operation="create",
  1642. content={"text": "rejected candidate"},
  1643. parent_refs=[],
  1644. effective_at_sequence=5,
  1645. command_id="deterministic-rejection-candidate",
  1646. )
  1647. failed = CandidateLedger.model_validate(
  1648. await self.store.get_candidate_ledger("root-a")
  1649. )
  1650. self.assertEqual("failed", failed.operations[-1].status)
  1651. self.assertEqual(0, len(failed.candidates))
  1652. self.assertEqual(0, len(self.repository.contents))
  1653. async def test_descendant_adoption_blocks_ancestor_rewind_without_mapping(self):
  1654. await self._create_child("child-a")
  1655. await self.store.create_trace(Trace(
  1656. trace_id="grandchild-a",
  1657. mode="agent",
  1658. agent_type="writer",
  1659. uid="user-1",
  1660. parent_trace_id="child-a",
  1661. context=self._context(
  1662. "root-a",
  1663. task_brief=TaskBrief(
  1664. objective="write descendant candidate",
  1665. reason="the child needs an option",
  1666. completion_criteria=["candidate is complete"],
  1667. expected_outputs=["one candidate"],
  1668. ),
  1669. ),
  1670. ))
  1671. candidate = await self.service.manage(
  1672. "grandchild-a",
  1673. operation="create",
  1674. content={"text": "nested candidate"},
  1675. parent_refs=[],
  1676. effective_at_sequence=4,
  1677. )
  1678. await self._record_validation("grandchild-a", candidate)
  1679. await self.service.apply_review_actions(
  1680. "child-a",
  1681. "grandchild-a",
  1682. report_refs=[candidate],
  1683. actions=[CandidateReviewAction(
  1684. action="adopt",
  1685. candidate_ref=candidate,
  1686. reason="commit descendant output",
  1687. )],
  1688. effective_at_sequence=9,
  1689. )
  1690. with self.assertRaisesRegex(CandidateStateError, "committed"):
  1691. await self.service.assert_rewind_allowed("root-a", 100)
  1692. async def test_failed_candidate_can_only_be_revised_or_discarded(self):
  1693. await self._create_child("child-a")
  1694. candidate = await self.service.manage(
  1695. "child-a",
  1696. operation="create",
  1697. content={"text": "placeholder"},
  1698. parent_refs=[],
  1699. effective_at_sequence=4,
  1700. )
  1701. await self._record_validation("child-a", candidate, outcome="failed")
  1702. with self.assertRaisesRegex(CandidateStateError, "passed"):
  1703. await self.service.apply_review_actions(
  1704. "root-a",
  1705. "child-a",
  1706. report_refs=[candidate],
  1707. actions=[CandidateReviewAction(
  1708. action="adopt",
  1709. candidate_ref=candidate,
  1710. reason="invalid",
  1711. )],
  1712. effective_at_sequence=9,
  1713. )
  1714. records = await self.service.apply_review_actions(
  1715. "root-a",
  1716. "child-a",
  1717. report_refs=[candidate],
  1718. actions=[CandidateReviewAction(
  1719. action="revise",
  1720. candidate_ref=candidate,
  1721. reason="remove placeholder",
  1722. )],
  1723. effective_at_sequence=10,
  1724. )
  1725. self.assertEqual("discarded", records[0].state)
  1726. self.assertIn("retry_from=output", records[0].reason)
  1727. async def test_adoption_replays_same_operation_after_finalize_crash(self):
  1728. await self._create_child("child-a")
  1729. candidate = await self.service.manage(
  1730. "child-a",
  1731. operation="create",
  1732. content={"text": "A"},
  1733. parent_refs=[],
  1734. effective_at_sequence=4,
  1735. )
  1736. await self._record_validation("child-a", candidate)
  1737. action = CandidateReviewAction(
  1738. action="adopt",
  1739. candidate_ref=candidate,
  1740. reason="publish once",
  1741. )
  1742. original_replace = self.store.replace_candidate_ledger
  1743. calls = 0
  1744. async def fail_finalize(root_trace_id, ledger):
  1745. nonlocal calls
  1746. calls += 1
  1747. if calls == 3:
  1748. raise OSError("crash before framework finalize")
  1749. await original_replace(root_trace_id, ledger)
  1750. with patch.object(
  1751. self.store,
  1752. "replace_candidate_ledger",
  1753. side_effect=fail_finalize,
  1754. ):
  1755. with self.assertRaisesRegex(OSError, "finalize"):
  1756. await self.service.apply_review_actions(
  1757. "root-a",
  1758. "child-a",
  1759. report_refs=[candidate],
  1760. actions=[action],
  1761. effective_at_sequence=9,
  1762. )
  1763. pending = CandidateLedger.model_validate(
  1764. await self.store.get_candidate_ledger("root-a")
  1765. )
  1766. self.assertEqual("adoption_pending", pending.current_state(candidate))
  1767. await self.service.apply_review_actions(
  1768. "root-a",
  1769. "child-a",
  1770. report_refs=[candidate],
  1771. actions=[action],
  1772. effective_at_sequence=9,
  1773. )
  1774. self.assertEqual(2, self.repository.adoption_calls)
  1775. self.assertEqual(1, len(self.repository.adoptions))
  1776. completed = CandidateLedger.model_validate(
  1777. await self.store.get_candidate_ledger("root-a")
  1778. )
  1779. self.assertEqual("adopted", completed.current_state(candidate))
  1780. if __name__ == "__main__":
  1781. unittest.main()