File size: 9,970 Bytes
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
"""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]