"""Conservative self-healing for failed workflow steps. A failed step is classified from the gateway outcome: * ``rate_limit``: quota / circuit breaker / HTTP 429 -> propose more retries with backoff; * ``transient``: timeout, 5xx, dropped database connection -> propose more retries with backoff (never applied automatically: a retried call may repeat an upstream effect whose outcome was unknown, so the owner decides); * ``auth``: missing or rejected credentials, channel not connected -> reconnect (no DSL fix); * ``schema``: invalid arguments, unknown tool, a reference that no longer resolves -> propose dropping arguments the tool no longer accepts, otherwise ask the owner; * ``data``: anything else (not found, business rule) -> ask the owner. Every proposal is a JSON Patch against the failed version's definition and lands in the workflow inbox (``workflow_proposals``). Only rate-limit fixes are applied automatically, and only when the tenant opted in (``settings.workflows.auto_heal_rate_limits = true``); the result is a new version that differs from the old one only in ``retry``. """ from __future__ import annotations import copy import logging import re import uuid from typing import Any from sqlalchemy import select from sqlalchemy.dialects.postgresql import insert from core.db.session import Database from core.tenancy.models import Tenant from core.workflows.dsl import WorkflowDefinition from core.workflows.executor import is_rate_limited, is_transient from core.workflows.models import WorkflowProposal log = logging.getLogger(__name__) AUTH_MARKERS = ( "401", "403", "unauthorized", "forbidden by provider", "credential", "token", "not connected", "oauth", "api key", ) SCHEMA_MARKERS = ( "invalid arguments", "unknown tool", "reference error", "extra_forbidden", "not a list", "missing", "schema", ) def classify(failure: dict[str, Any]) -> str: reason = str(failure.get("reason") or "").lower() status = str(failure.get("status") or "") if is_rate_limited(reason) or "circuit breaker" in reason: return "rate_limit" if is_transient(reason): return "transient" if any(m in reason for m in AUTH_MARKERS): return "auth" if status == "schema" or any(m in reason for m in SCHEMA_MARKERS): return "schema" return "data" def apply_patch(doc: dict[str, Any], patch: list[dict[str, Any]]) -> dict[str, Any]: """Minimal RFC 6902 (add / replace / remove) for the proposals we generate.""" out = copy.deepcopy(doc) for op in patch: parts = [p.replace("~1", "/").replace("~0", "~") for p in op["path"].split("/")[1:]] parent: Any = out for p in parts[:-1]: parent = parent[int(p)] if isinstance(parent, list) else parent[p] last = parts[-1] key: Any = int(last) if isinstance(parent, list) else last if op["op"] in ("add", "replace"): parent[key] = op["value"] elif op["op"] == "remove": del parent[key] else: raise ValueError(f"unsupported patch op {op['op']}") return out def propose(defn: WorkflowDefinition, failure: dict[str, Any]) -> tuple[str, str, list[dict]]: """(class, summary, patch) for a failed step.""" kind = classify(failure) step_id = str(failure.get("step")) idx = next((i for i, s in enumerate(defn.steps) if s.id == step_id), None) reason = str(failure.get("reason") or "") if idx is None: return kind, f"Step {step_id} failed: {reason}", [] step = defn.steps[idx] if kind in ("rate_limit", "transient"): attempts = min(5, max(3, step.retry.max_attempts + 2)) backoff = min(60.0, max(5.0, step.retry.backoff_s * 2 or 5.0)) patch = [ { "op": "replace", "path": f"/steps/{idx}/retry", "value": {"max_attempts": attempts, "backoff_s": backoff}, } ] return ( kind, ( f"Step {step_id} " + ("hit a rate limit" if kind == "rate_limit" else f"failed transiently ({reason})") + f". Retry up to {attempts} times with " f"{backoff:g}s exponential backoff." ), patch, ) if kind == "auth": return ( kind, ( f"Step {step_id} ({step.tool}) could not authenticate: {reason}. Reconnect the " "integration in Settings; the workflow itself does not change." ), [], ) if kind == "schema": bad = sorted(set(re.findall(r"'(\w+)'", reason)) & set(step.args)) if "extra_forbidden" in reason and bad: patch = [{"op": "remove", "path": f"/steps/{idx}/args/{a}"} for a in bad] return ( kind, (f"{step.tool} no longer accepts {bad}. Remove them from step {step_id}."), patch, ) return ( kind, ( f"Step {step_id} no longer matches {step.tool}'s inputs or an earlier step's " f"output: {reason}. Edit the step." ), [], ) return ( kind, ( f"Step {step_id} failed on the data it saw: {reason}. Check the records involved, " "or add a condition to skip them." ), [], ) async def _auto_heal_allowed(db: Database, tenant_id: uuid.UUID) -> bool: async with db.session(tenant_id=tenant_id) as s: settings = ( await s.execute(select(Tenant.settings).where(Tenant.id == tenant_id)) ).scalar_one_or_none() or {} return bool((settings.get("workflows") or {}).get("auto_heal_rate_limits")) async def handle_failure( db: Database, tenant_id: uuid.UUID, run_id: uuid.UUID, ctx: dict[str, Any], failure: dict[str, Any], registry: Any = None, ) -> str: """Record a proposal for a failed run (idempotent per run + step); maybe auto-apply it.""" defn = WorkflowDefinition.model_validate(ctx["definition"]) wf = ctx["workflow"] kind, summary, patch = propose(defn, failure) pid = uuid.uuid4() async with db.session(tenant_id=tenant_id) as s, s.begin(): inserted = ( await s.execute( insert(WorkflowProposal) .values( id=pid, tenant_id=tenant_id, workflow_id=uuid.UUID(str(wf["id"])), version=int(wf["version"]), run_id=run_id, step_id=str(failure.get("step"))[:40], failure_class=kind, error=str(failure.get("reason") or "")[:4000], summary=summary, patch=patch, status="pending", ) .on_conflict_do_nothing(constraint="uq_workflow_proposals_run_step") .returning(WorkflowProposal.id) ) ).scalar_one_or_none() if inserted is None: return "A fix was already proposed." if kind == "rate_limit" and patch and registry is not None: if await _auto_heal_allowed(db, tenant_id): return await _auto_apply(db, tenant_id, pid, defn, wf, patch, summary, registry) return f"Proposed fix ({kind}) sent to the workflow inbox." async def _auto_apply( db: Database, tenant_id: uuid.UUID, proposal_id: uuid.UUID, defn: WorkflowDefinition, wf: dict[str, Any], patch: list[dict[str, Any]], summary: str, registry: Any, ) -> str: from datetime import UTC, datetime from core.workflows import versions fixed = WorkflowDefinition.model_validate(apply_patch(defn.model_dump(mode="json"), patch)) try: v = await versions.auto_apply( db, tenant_id, uuid.UUID(str(wf["id"])), int(wf["version"]), fixed, registry, note=f"self-heal: {summary}", ) except versions.LifecycleError as exc: log.warning("auto-heal refused: %s", exc) return "Proposed fix (rate_limit) sent to the workflow inbox." if v is None: return "Proposed fix (rate_limit) sent to the workflow inbox." async with db.session(tenant_id=tenant_id) as s, s.begin(): p = await s.get(WorkflowProposal, proposal_id) if p is not None: p.status, p.applied_version, p.decided_at = "auto_applied", v.version, datetime.now(UTC) return f"Backoff fix auto-applied as version {v.version}."