Spaces:
Running

File size: 8,942 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"""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}."