EnergyVenom's picture
Patchwise Agent Studio: Oracle AI Agent Studio cycles
af1bee9 verified
Raw History Blame Contribute Delete
9.97 kB
"""Temporal workflows (deterministic code only; activities are referenced by name, no heavy imports here).
PatchCycleWorkflow (workflow id = run_id) is the durable outer loop around the LangGraph agent nodes:
scout_and_research -> design_tests -> [HUMAN approve_cases] -> plan_and_seed_data -> build_scripts
-> execute_attempt(0) --pass--> report
--fail--> self_heal -> execute_attempt(1) -> triage (exactly one retry, owned here)
triage --review needed--> [HUMAN submit_review] --confirmed real defect--> ticket -> report -> learn
The routing decisions come from the SAME routing functions as the LangGraph graph (computed inside the activities and
returned as the next step), so both orchestrators route identically. Human gates are signals; durable timers send a
reminder and an escalation (they never auto-approve)."""
from __future__ import annotations
import asyncio
from datetime import timedelta
from typing import Any
from temporalio import workflow
from temporalio.common import RetryPolicy
from temporalio.exceptions import ActivityError, ApplicationError, CancelledError
NON_RETRYABLE = ["KillSwitchEngaged", "FatalNodeError", "ValidationError", "PolicyViolation", "NotAvailable", "EgressDenied"]
RETRY = RetryPolicy(initial_interval=timedelta(seconds=2), backoff_coefficient=2.0, maximum_interval=timedelta(seconds=60),
maximum_attempts=3, non_retryable_error_types=NON_RETRYABLE)
# activity -> (start_to_close, heartbeat_timeout or None)
TIMEOUTS: dict[str, tuple[timedelta, timedelta | None]] = {
"scout_and_research": (timedelta(minutes=30), timedelta(minutes=2)),
"design_tests": (timedelta(minutes=15), None),
"prepare_approval": (timedelta(minutes=5), None),
"apply_approval": (timedelta(minutes=10), None),
"plan_and_seed_data": (timedelta(minutes=15), None),
"build_scripts": (timedelta(minutes=30), None),
"execute_attempt": (timedelta(hours=3), timedelta(minutes=2)),
"self_heal": (timedelta(minutes=15), None),
"triage": (timedelta(minutes=15), None),
"prepare_review": (timedelta(minutes=5), None),
"apply_review": (timedelta(minutes=5), None),
"ticket": (timedelta(minutes=10), None),
"report": (timedelta(minutes=20), None),
"learn": (timedelta(minutes=10), None),
"notify": (timedelta(minutes=2), None),
"finalize_run": (timedelta(minutes=2), None),
"check_patch": (timedelta(minutes=2), None),
"create_scheduled_run": (timedelta(minutes=2), None),
"purge": (timedelta(minutes=30), None),
}
async def _act(name: str, *args: Any, task_queue: str | None = None) -> Any:
stc, hb = TIMEOUTS[name]
return await workflow.execute_activity(name, args=list(args), start_to_close_timeout=stc, heartbeat_timeout=hb,
retry_policy=RETRY, task_queue=task_queue)
@workflow.defn(name="PatchCycleWorkflow")
class PatchCycleWorkflow:
def __init__(self) -> None:
self._answers: dict[str, dict] = {}
self._cancel_reason: str | None = None
self._status = "queued"
self._gate: str | None = None
self._step: str | None = None
self._notices: list[str] = []
# ---------------------------------------------------------------- signals / queries
@workflow.signal
def approve_cases(self, answer: dict) -> None:
self._answers["approve_cases"] = answer
@workflow.signal
def submit_review(self, answer: dict) -> None:
self._answers["human_review"] = answer
@workflow.signal
def cancel(self, reason: str) -> None:
self._cancel_reason = reason or "cancelled"
@workflow.query
def status(self) -> dict:
return {"status": self._status, "step": self._step, "pending_gate": self._gate, "notices": self._notices}
@workflow.query
def pending_gate(self) -> str | None:
return self._gate
# ---------------------------------------------------------------- helpers
async def _step_do(self, name: str, *args: Any, task_queue: str | None = None) -> Any:
if self._cancel_reason:
raise _Cancelled(self._cancel_reason)
self._step, self._status = name, "running"
return await _act(name, *args, task_queue=task_queue)
async def _wait_gate(self, run_id: str, gate: str, remind_s: int, escalate_s: int) -> dict:
self._gate, self._status = gate, "waiting_approval" if gate == "approve_cases" else "waiting_review"
done = lambda: gate in self._answers or self._cancel_reason is not None # noqa: E731
try:
await workflow.wait_condition(done, timeout=timedelta(seconds=remind_s))
except asyncio.TimeoutError:
self._notices.append(f"reminder:{gate}")
await _act("notify", run_id, "reminder", gate)
try:
await workflow.wait_condition(done, timeout=timedelta(seconds=max(1, escalate_s - remind_s)))
except asyncio.TimeoutError:
self._notices.append(f"escalation:{gate}")
await _act("notify", run_id, "escalation", gate)
await workflow.wait_condition(done) # waits for a human indefinitely: no auto-approval, ever
self._gate = None
if self._cancel_reason:
raise _Cancelled(self._cancel_reason)
return self._answers.pop(gate)
# ---------------------------------------------------------------- the patch cycle
@workflow.run
async def run(self, inp: dict) -> dict:
rid = inp["run_id"]
browser_q = inp.get("browser_queue")
remind, escalate = int(inp.get("remind_after_s", 86400)), int(inp.get("escalate_after_s", 259200))
try:
await self._step_do("scout_and_research", rid)
await self._step_do("design_tests", rid)
gate = await self._step_do("prepare_approval", rid)
if gate and not gate.get("answered"):
answer = await self._wait_gate(rid, "approve_cases", remind, escalate)
await self._step_do("apply_approval", rid, answer)
await self._step_do("plan_and_seed_data", rid)
await self._step_do("build_scripts", rid)
route = await self._step_do("execute_attempt", rid, 0, task_queue=browser_q)
if route == "self_heal":
await self._step_do("self_heal", rid)
route = await self._step_do("execute_attempt", rid, 1, task_queue=browser_q)
if route == "triage":
route = await self._step_do("triage", rid)
if route == "human_review":
rv = await self._step_do("prepare_review", rid)
if not rv.get("answered"):
answer = await self._wait_gate(rid, "human_review", remind, escalate)
route = await self._step_do("apply_review", rid, answer)
else:
route = rv.get("route", "reporter")
if route == "ticket":
await self._step_do("ticket", rid)
await self._step_do("report", rid)
result = await self._step_do("learn", rid)
self._status = "completed"
await _act("finalize_run", rid, "completed", "")
return {"status": "completed", **(result or {})}
except _Cancelled as c:
self._status = "cancelled"
await _act("finalize_run", rid, "cancelled", c.reason)
return {"status": "cancelled", "reason": c.reason}
except (asyncio.CancelledError, CancelledError):
self._status = "cancelled"
# still allowed to run a cleanup activity after a cancellation request
await _act("finalize_run", rid, "cancelled", "workflow cancelled")
raise
except ActivityError as e:
cause = e.cause
kind = getattr(cause, "type", None) or type(cause).__name__
status = "killed" if kind == "KillSwitchEngaged" else "failed"
self._status = status
await _act("finalize_run", rid, status, f"{kind}: {getattr(cause, 'message', str(cause))}")
raise ApplicationError(f"run {status}: {kind}", type=kind, non_retryable=True) from e
class _Cancelled(Exception):
def __init__(self, reason: str):
super().__init__(reason)
self.reason = reason
@workflow.defn(name="PatchWatchWorkflow")
class PatchWatchWorkflow:
"""Started by the Temporal Schedule 'fpt-patch-watch': checks the pod release; with autostart, starts a cycle."""
@workflow.run
async def run(self, inp: dict) -> dict:
res = await _act("check_patch")
if res.get("run_id"):
await workflow.start_child_workflow("PatchCycleWorkflow", {**inp, "run_id": res["run_id"]}, id=res["run_id"],
parent_close_policy=workflow.ParentClosePolicy.ABANDON)
return res
@workflow.defn(name="ScheduledRunWorkflow")
class ScheduledRunWorkflow:
"""Started by a Temporal Schedule 'fpt-sched-<id>' (interval or daily cron)."""
@workflow.run
async def run(self, inp: dict) -> dict:
rid = await _act("create_scheduled_run", int(inp["schedule_id"]))
if rid:
await workflow.start_child_workflow("PatchCycleWorkflow", {**inp, "run_id": rid}, id=rid,
parent_close_policy=workflow.ParentClosePolicy.ABANDON)
return {"run_id": rid}
@workflow.defn(name="PurgeWorkflow")
class PurgeWorkflow:
@workflow.run
async def run(self, inp: dict) -> dict:
return await _act("purge")
WORKFLOWS = [PatchCycleWorkflow, PatchWatchWorkflow, ScheduledRunWorkflow, PurgeWorkflow]