"""RunManager: ONE worker thread runs one graph run at a time (mock + Playwright are stateful, workers: 1). Jobs: start / resume (gate answer) / continue (crash recovery). Status: queued -> running -> waiting_approval | waiting_sign_in | waiting_review -> running -> completed | failed | killed | cancelled | interrupted (backend restarted mid-run). waiting_sign_in: a pod with assisted sign-in waits for a person to sign in (platform/assisted_signin.py).""" from __future__ import annotations import json import logging import queue import secrets import threading from datetime import datetime, timezone from langgraph.errors import GraphRecursionError from langgraph.types import Command from ..graph.build import build_graph, run_config, sqlite_checkpointer from ..graph.runtime import FatalNodeError from ..platform import procs from ..platform.failures import plain as plain_failure from ..platform.killswitch import KillSwitchEngaged from ..platform.rundb import now_iso log = logging.getLogger("fpt.runner") GATE_STATUS = {"approve_cases": "waiting_approval", "sign_in": "waiting_sign_in", "human_review": "waiting_review"} TERMINAL = ("completed", "failed", "killed", "cancelled") def end_sign_in(svc, run_id: str, sessions=None) -> None: """A run that ended keeps no captured session (assisted sign-in) and no sign-in browser open; never raises.""" from ..platform import assisted_signin assisted_signin.at_end(svc, run_id, sessions) def sweep_test_data(svc, run_id: str, reason: str) -> dict | None: """Cancel Fusion test invoices a run left behind (platform/cleanup.py), then record what stays on the pod; never raises.""" from ..platform import cleanup try: out = cleanup.sweep(svc, run_id, reason) except Exception: # noqa: BLE001 log.exception("test data clean-up of run %s failed", run_id) out = None try: # what stays on the pod for a person goes to the ledger (platform/left_on_pod.py), also when the sweep had nothing to do from ..platform import left_on_pod left_on_pod.record(svc, run_id) except Exception: # noqa: BLE001 log.exception("recording the test documents run %s left on its pod failed", run_id) return out class RunError(RuntimeError): def __init__(self, msg: str, code: str = "CONFLICT", status: int = 409): super().__init__(msg) self.code, self.status = code, status def new_run_id() -> str: return datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S") + "-" + secrets.token_hex(3) def record_anchor(svc, run_id: str, status: str) -> dict: """Write the audit chain head OUTSIDE the DB at run end (anchors file + structured log line) for truncation checks.""" import time as _t head = svc.audit.head() anchor = {"run_id": run_id, "status": status, "audit_seq": head["seq"], "audit_hash": head["hash"], "ts": _t.strftime("%Y-%m-%dT%H:%M:%SZ", _t.gmtime())} f = svc.cfg.path("logs", "audit-anchors.jsonl") f.parent.mkdir(parents=True, exist_ok=True) with f.open("a", encoding="utf-8") as fh: fh.write(json.dumps(anchor) + "\n") logging.getLogger("fpt.audit").info("audit anchor %s", json.dumps(anchor)) return anchor DUPLICATE_WINDOW_S = 600 # a second identical start within 10 minutes of one still going is refused _STATUS_WORDS = {"queued": "queued", "running": "running", "waiting_approval": "waiting for scenario approval", "waiting_sign_in": "waiting for a person to sign in to the pod", "waiting_review": "waiting for QA review"} def _duplicate_run(svc, actor: str, pod_id: int, mods: list[str], patch: str | None) -> dict | None: """A run by the same person on the same pod with the same business areas (and patch) that is still going and started recently: almost always a double click or a second tab.""" from datetime import timedelta since = (datetime.now(timezone.utc) - timedelta(seconds=DUPLICATE_WINDOW_S)).isoformat(timespec="seconds") rows = svc.db.q("SELECT run_id, status, modules, patch_id FROM runs WHERE created_by=? AND pod_id=? AND created_at>=? " "AND status IN ('queued','running','waiting_approval','waiting_sign_in','waiting_review') ORDER BY created_at DESC", (actor, pod_id, since)) return next((r for r in rows if sorted(r["modules"] or []) == sorted(mods) and (r["patch_id"] or None) == (patch or None)), None) def _refuse_duplicate(svc, actor: str, pod: dict, mods: list[str], patch: str | None) -> None: dup = _duplicate_run(svc, actor, pod["id"], mods, patch) if dup: raise RunError(f"Test run {dup['run_id']} with the same business areas on {pod['name']} is already " f"{_STATUS_WORDS.get(dup['status'], dup['status'])}. Open that run instead of starting another.", "DUPLICATE_RUN", 409) def _create_row(svc, rid, actor, trigger, inputs, mods, state, orchestrator, pod) -> None: svc.db.create_run({"run_id": rid, "created_by": actor, "trigger": trigger, "patch_id": inputs.get("patch_id"), "modules": mods, "include_p2": int(state["include_p2"]), "playwright_mode": state["playwright_mode"], "inputs": state, "status": "queued", "orchestrator": orchestrator, "pod_id": pod["id"]}) def create_run_record(svc, inputs: dict, actor: str, trigger: str = "manual", orchestrator: str = "langgraph", run_id: str | None = None) -> tuple[str, dict]: """Validate inputs, create the run row (status queued), the initial shared state, the queued event and the audit entry. Shared by both orchestrators (LangGraph RunManager and the Temporal one). `run_id`: an id the caller reserved beforehand (an Agent Studio cycle records it before the run exists); a new one otherwise.""" svc.kill.check("run.start") from ..platform.pods import PodError, PodRegistry reg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit) try: pod = reg.get(int(inputs["pod_id"])) if inputs.get("pod_id") else reg.default() except PodError as e: raise RunError(str(e), e.code, e.status) from e if not pod["runnable"]: raise RunError(pod["not_runnable_reason"] or "this pod cannot run tests", "POD_NOT_RUNNABLE", 409) if orchestrator == "temporal" and pod.get("sign_in_mode") == "assisted": # its sign_in gate exists in this graph only raise RunError(f"{pod['name']} uses assisted sign-in, which runs on the built-in orchestrator, not Temporal.", "ASSISTED_NEEDS_LANGGRAPH", 409) _refuse_duplicate(svc, actor, pod, [m.upper() for m in inputs.get("modules") or []], inputs.get("patch_id")) # before signing in to Fusion again if pod["kind"] == "fusion": # only business areas this pod has (discovery; the run's scout discovers again) problem = reg.area_problem(pod, [m.upper() for m in inputs.get("modules") or []]) if problem: raise RunError(problem, "AREA_NOT_ON_FUSION", 409) # prove the pod and its test user now, in seconds, instead of failing minutes into the run failed = next((c for c in reg.fusion_checks(pod) if not c["ok"]), None) if failed: svc.db.update("pods", "id", pod["id"], last_check_at=now_iso(), last_check_ok=0, last_check_detail=failed["detail"]) raise RunError(f"{pod['name']}: {failed['detail']}", "POD_CHECK_FAILED", 409) rid = run_id or new_run_id() mods = [m.upper() for m in inputs.get("modules") or []] state = {"run_id": rid, "patch_id": inputs.get("patch_id") or "", "trigger": trigger, "modules_requested": mods, "include_p2": bool(inputs.get("include_p2")), "case_filter": [str(x) for x in inputs.get("case_ids") or []], "depth": inputs.get("depth") if inputs.get("depth") in ("smoke", "standard", "full") else "standard", "playwright_mode": inputs.get("playwright_mode") or svc.cfg.playwright_mode, "stub_knobs": {k: v for k, v in (inputs.get("stub_knobs") or {}).items() if k in ("STUB_FAIL", "STUB_DEFECT", "STUB_UI", "STUB_FLAKY") and v}, "pod_id": pod["id"], "pod_name": pod["name"]} if state["playwright_mode"] == "live" and not svc.cfg.browser_runs_allowed: raise RunError("This server is too small to run a real browser. Start a quick simulation here, or use a server with at least 2 GB of memory.", "BROWSER_RUNS_OFF", 409) state["live_view"] = state["playwright_mode"] == "live" and inputs.get("live_view") is not False if not state["patch_id"]: state.pop("patch_id") if state["playwright_mode"] != "stub": state["stub_knobs"] = {} with svc.db.write_lock: # the duplicate check and the insert are one step: a double click starts one run _refuse_duplicate(svc, actor, pod, mods, inputs.get("patch_id")) _create_row(svc, rid, actor, trigger, inputs, mods, state, orchestrator, pod) if orchestrator == "temporal": from ..graph.statestore import StateStore StateStore(svc.db).save(rid, dict(state)) svc.db.add_event(rid, None, "status", {"status": "queued", "orchestrator": orchestrator}) svc.audit.append("run.started", actor=actor, run_id=rid, summary=f"{trigger} {mods or 'all'} {state['playwright_mode']} via {orchestrator}", payload={**{k: v for k, v in state.items() if k != "run_id"}, **({"via": str(inputs["via"])} if inputs.get("via") else {})}) return rid, state class RunManager: orchestrator = "langgraph" fallback_reason: str | None = None def __init__(self, svc): self.svc = svc self.saver = sqlite_checkpointer(svc.cfg.checkpoint_path) self.graph = build_graph(svc, self.saver) self.q: queue.Queue = queue.Queue() self.current: str | None = None self._cancel: set[str] = set() self._stop = threading.Event() # the app is shutting down: no new run starts, no queued job is taken, a running run stops at its next step self._shutting_down = threading.Event() self._thread: threading.Thread | None = None self.listeners: list = [] # callables(run_id, status) e.g. desktop notifications via SSE self.sign_in = None # the app's SignInSessions (platform/assisted_signin.py), closed with a run that ends # ------------------------------------------------------------ lifecycle def recover(self) -> list[str]: """After a restart: a run that was running is marked interrupted (resume it by hand); a run that was queued with its job saved (a start, a gate answer, a resume) is queued again, so an answered gate is not lost.""" ids = [] for r in self.svc.db.list_runs("running", 1000): self._interrupted(r["run_id"]) ids.append(r["run_id"]) for r in self.svc.db.list_runs("queued", 1000): job = self.svc.db.one("SELECT * FROM run_jobs WHERE run_id=? AND done_at IS NULL ORDER BY id DESC LIMIT 1", (r["run_id"],)) if job and r.get("orchestrator", "langgraph") == "langgraph": self.svc.db.x("UPDATE run_jobs SET done_at=? WHERE run_id=? AND done_at IS NULL AND id None: self.svc.db.update_run(run_id, status="interrupted") self.svc.db.x("UPDATE run_jobs SET done_at=? WHERE run_id=? AND done_at IS NULL", (now_iso(), run_id)) self.svc.db.add_event(run_id, None, "status", {"status": "interrupted", "reason": "backend restarted"}) # the browser died with the old server: cancel the test invoices it had not cleaned up yet (in the background) threading.Thread(target=sweep_test_data, args=(self.svc, run_id, "interrupted by a restart"), daemon=True).start() def _enqueue(self, kind: str, run_id: str, payload, gate: str | None = None) -> None: jid = self.svc.db.insert("run_jobs", {"run_id": run_id, "kind": kind, "gate": gate, "payload": json.dumps(payload, default=str), "created_at": now_iso()}) self.q.put((kind, run_id, payload, gate, jid)) def start_worker(self) -> None: if self._thread and self._thread.is_alive(): return self._stop.clear() self._thread = threading.Thread(target=self._loop, name="fpt-run-worker", daemon=True) self._thread.start() def stop(self) -> None: self._stop.set() self.q.put(None) if self._thread: self._thread.join(timeout=10) def stop_for_shutdown(self, wait_s: float) -> bool: """Shutdown, before the last save: take no new work, and let a running run stop at its next safe point (between two graph steps, where its checkpoint is complete). That run is queued to continue after the restart instead of coming back interrupted. Waits at most wait_s; a step that takes longer (a browser attempt) is left to the old behaviour (interrupted after the restart), so shutdown is never held up. True when the worker stopped in time.""" self._shutting_down.set() self._stop.set() self.q.put(None) t = self._thread if t is None or not t.is_alive(): return True t.join(timeout=max(0.0, float(wait_s))) return not t.is_alive() def drain(self, timeout: float = 600) -> None: """Tests/CLI: process queued jobs synchronously in the calling thread.""" import time end = time.time() + timeout while time.time() < end: try: job = self.q.get_nowait() except queue.Empty: return if job: self._execute(*job) # ------------------------------------------------------------ API def start(self, inputs: dict, actor: str, trigger: str = "manual", run_id: str | None = None) -> str: if self._shutting_down.is_set(): raise RunError("the server is restarting: start the run again in a minute", "SHUTTING_DOWN", 503) rid, state = create_run_record(self.svc, inputs, actor, trigger, orchestrator="langgraph", run_id=run_id) self._enqueue("start", rid, state) return rid def answer_gate(self, run_id: str, gate: str, answer: dict, actor: str) -> None: run = self._get(run_id) if run["pending_gate"] != gate or run["status"] != GATE_STATUS.get(gate): raise RunError(f"run {run_id} is not waiting at gate {gate} (status {run['status']}, gate {run['pending_gate']})", "NOT_AT_GATE") self.svc.kill.check("gate.answer") # check-and-write in one statement: a double click must not let the second answer resume the NEXT gate if not self.svc.db.claim_run(run_id, GATE_STATUS[gate], gate, status="queued", pending_gate=None): raise RunError(f"run {run_id} is no longer waiting at gate {gate}: this answer was already given", "NOT_AT_GATE") self.svc.db.add_event(run_id, gate, "status", {"status": "queued", "answered_by": actor}) self._enqueue("resume", run_id, {**answer, "actor": actor}, gate) def resume(self, run_id: str, actor: str) -> None: run = self._get(run_id) if run["status"] not in ("interrupted", "failed"): raise RunError(f"run {run_id} is {run['status']}; only interrupted/failed runs can be resumed", "NOT_RESUMABLE") self.svc.kill.check("run.resume") self.svc.audit.append("run.resumed", actor=actor, run_id=run_id) snap = self.graph.get_state(run_config(run_id, self.svc.cfg)) intr = self._interrupt(snap) if intr is not None: self._pause(run_id, intr) return self.svc.db.update_run(run_id, status="queued", error=None) self._enqueue("continue", run_id, None) def cancel(self, run_id: str, actor: str, reason: str = "") -> None: run = self._get(run_id) if run["status"] in TERMINAL: raise RunError(f"run {run_id} is already {run['status']}", "ALREADY_FINISHED") self._cancel.add(run_id) if self.current == run_id: procs.kill_all(f"playwright:{run_id}") self.svc.db.update_run(run_id, status="cancelled", pending_gate=None, error=reason or None) self.svc.db.add_event(run_id, None, "status", {"status": "cancelled", "by": actor, "reason": reason}) self.svc.audit.append("run.cancelled", actor=actor, run_id=run_id, summary=reason) end_sign_in(self.svc, run_id, self.sign_in) from ..platform.statesync import save_soon save_soon("run cancelled") if self.current != run_id: # a running one is swept by the worker once Playwright is gone threading.Thread(target=self._release_and_sweep, args=(run_id,), daemon=True).start() def _release_and_sweep(self, run_id: str) -> None: """A cancelled run that is not running here may still own a job on the remote browser runner (a restart left it running): stop it, so the runner is free, and fetch the records it made before the clean-up looks for them.""" from ..adapters.remote_runner import release_job release_job(self.svc, run_id) sweep_test_data(self.svc, run_id, "cancelled") def gate_payload(self, run_id: str) -> dict | None: snap = self.graph.get_state(run_config(run_id, self.svc.cfg)) return self._interrupt(snap) def state(self, run_id: str) -> dict: vals = dict(self.graph.get_state(run_config(run_id, self.svc.cfg)).values or {}) if not vals: # an old finished run whose step checkpoints were pruned: its final state was kept in the run folder from ..platform.retention import final_state vals = final_state(self.svc.cfg.runs_dir / run_id) or {} return vals def kill_active(self) -> None: if self.current: procs.kill_all(f"playwright:{self.current}") # ------------------------------------------------------------ worker def _get(self, run_id: str) -> dict: r = self.svc.db.get_run(run_id) if not r: raise RunError(f"run {run_id} not found", "NOT_FOUND", 404) return r @staticmethod def _interrupt(snap) -> dict | None: for t in snap.tasks or (): for i in t.interrupts or (): return i.value return None def _pause(self, run_id: str, payload: dict) -> None: gate = payload.get("gate") st = GATE_STATUS.get(gate, "waiting_approval") self.svc.db.update_run(run_id, status=st, pending_gate=gate) self.svc.db.add_event(run_id, gate, "status", {"status": st, "gate": gate}) self._notify(run_id, st) def _notify(self, run_id: str, status: str) -> None: from ..platform.statesync import save_soon save_soon(f"run {status}") # a run that waits for a person or has ended must survive a restart for fn in list(self.listeners): try: fn(run_id, status) except Exception: # noqa: BLE001 log.exception("listener failed") def _loop(self) -> None: while not self._stop.is_set(): job = self.q.get() if job is None or self._stop.is_set(): # stopping: the job stays in run_jobs and runs after the restart continue try: self._execute(*job) except Exception: # noqa: BLE001 log.exception("run job crashed") def _execute(self, kind: str, run_id: str, payload, gate: str | None = None, job_id: int | None = None) -> None: try: self._work(kind, run_id, payload, gate) finally: r = self.svc.db.get_run(run_id) if r and r["status"] in TERMINAL: end_sign_in(self.svc, run_id, self.sign_in) sweep_test_data(self.svc, run_id, r["status"]) if job_id is not None: self.svc.db.x("UPDATE run_jobs SET done_at=? WHERE id=?", (now_iso(), job_id)) def _continue_after_restart(self, run_id: str) -> None: """The app is shutting down between two steps of this run: queue it with a 'continue' job (kept in run_jobs, so recover() picks it up at the next start) and let the last save hold it that way.""" self.svc.db.update_run(run_id, status="queued") self.svc.db.insert("run_jobs", {"run_id": run_id, "kind": "continue", "gate": None, "payload": "null", "created_at": now_iso()}) self.svc.db.add_event(run_id, None, "status", {"status": "queued", "reason": "the server is restarting; the run continues after the restart"}) self.svc.audit.append("run.paused_for_restart", actor="system", run_id=run_id, summary="stopped between steps for a restart") log.info("run %s stopped between steps for the restart; it continues after it", run_id) def _work(self, kind: str, run_id: str, payload, gate: str | None = None) -> None: run = self.svc.db.get_run(run_id) if not run or run["status"] == "cancelled" or run_id in self._cancel: return cfg = run_config(run_id, self.svc.cfg) if kind == "resume": # a gate answer only resumes the gate it was given for; never a later pause of the same run intr = self._interrupt(self.graph.get_state(cfg)) if intr is None or intr.get("gate") != gate: log.warning("run %s: answer for gate %s dropped, the run is at %s", run_id, gate, intr and intr.get("gate")) self.svc.db.add_event(run_id, gate, "gate_answer_dropped", {"gate": gate, "now_at": intr and intr.get("gate")}) if intr is not None: self._pause(run_id, intr) return payload = Command(resume=payload) self.current = run_id self.svc.db.update_run(run_id, status="running") self.svc.db.add_event(run_id, None, "status", {"status": "running"}) try: if self.svc.kill.engaged(): raise KillSwitchEngaged("kill switch engaged before start") inp = payload if kind in ("start", "resume") else None for _upd in self.graph.stream(inp, cfg, stream_mode="updates"): if run_id in self._cancel: return if self.svc.kill.engaged(): raise KillSwitchEngaged("kill switch engaged between steps") if self._shutting_down.is_set(): self._continue_after_restart(run_id) return snap = self.graph.get_state(cfg) intr = self._interrupt(snap) if intr is not None: self._pause(run_id, intr) return v = snap.values self.svc.db.update_run(run_id, status="completed", current_node=None, pending_gate=None, decisions=v.get("decisions") or {}, decision=v.get("decision"), counts=v.get("counts") or {}, patch_id=v.get("patch_id")) self.svc.db.add_event(run_id, None, "status", {"status": "completed", "decisions": v.get("decisions")}) self.svc.audit.append("run.completed", actor="system", run_id=run_id, summary=json.dumps(v.get("decisions")), payload={"decisions": v.get("decisions"), "counts": v.get("counts")}) record_anchor(self.svc, run_id, "completed") self._notify(run_id, "completed") except KillSwitchEngaged as e: self.svc.db.update_run(run_id, status="killed", error=str(e), pending_gate=None) self.svc.db.add_event(run_id, None, "status", {"status": "killed", "error": str(e)}) self._notify(run_id, "killed") except (FatalNodeError, GraphRecursionError, Exception) as e: # noqa: BLE001 if run_id in self._cancel: return raw = f"{type(e).__name__}: {e}" code, msg = plain_failure(e) # people see a sentence; the raw text stays in the audit log and the server log self.svc.db.update_run(run_id, status="failed", error=msg[:2000], pending_gate=None) self.svc.db.add_event(run_id, None, "status", {"status": "failed", "error": msg[:2000], "code": code, "fatal": isinstance(e, FatalNodeError)}) self.svc.audit.append("run.failed", actor="system", run_id=run_id, summary=msg[:300], payload={"code": code, "raw": raw[:2000]}) self._notify(run_id, "failed") log.warning("run %s failed: %s", run_id, raw) finally: self.current = None self._cancel.discard(run_id)