Spaces:
Running

File size: 14,641 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
"""Workflow lifecycle: draft -> dry-run -> approve (owner) -> activate (version N) -> rollback.



Versions are immutable (a database trigger rejects changes to ``definition``); only their

status moves. Approval binds to the exact definition hash that passed a dry run. Activation

makes version N the only active one and syncs its trigger into the engine:



* schedule trigger -> one ``schedules`` row (Phase 5) named ``workflow:<id>`` that emits

  ``workflow.run`` events with ``{"workflow_id", "version", "trigger": "schedule"}``;

* event trigger    -> one ``workflow_triggers`` row (fan-out in ``core.workflows.triggers``);

* manual trigger   -> nothing (``POST /workflows/{id}/run``).



Rollback marks N ``rolled_back`` and re-activates the latest earlier version that was active

(N-1 normally); with none, the workflow is paused and its triggers removed.

"""

from __future__ import annotations

import uuid
from datetime import UTC, datetime
from typing import Any

from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession

from core.db.session import Database
from core.events import store as event_store
from core.events.models import Schedule
from core.tools.registry import ToolRegistry
from core.workflows.compiler import CheckReport, check
from core.workflows.dsl import EventTrigger, ScheduleTrigger, WorkflowDefinition
from core.workflows.executor import WORKFLOW_INTENT
from core.workflows.models import Workflow, WorkflowTrigger, WorkflowVersion

ACTIVATABLE = ("approved", "superseded", "rolled_back")


class LifecycleError(Exception):
    def __init__(self, message: str, *, status: int = 409, report: CheckReport | None = None):
        super().__init__(message)
        self.status = status
        self.report = report


def schedule_name(workflow_id: uuid.UUID) -> str:
    return f"workflow:{workflow_id}"


def _validated(

    data: dict[str, Any] | WorkflowDefinition, registry: ToolRegistry

) -> tuple[WorkflowDefinition, CheckReport]:
    defn, report = check(data, registry)
    if defn is None or not report.ok:
        raise LifecycleError("definition has errors", status=422, report=report)
    return defn, report


async def _workflow(s: AsyncSession, workflow_id: uuid.UUID) -> Workflow:
    wf = await s.get(Workflow, workflow_id, with_for_update=True)
    if wf is None:
        raise LifecycleError("workflow not found", status=404)
    return wf


async def _version(s: AsyncSession, workflow_id: uuid.UUID, version: int) -> WorkflowVersion:
    v = (
        await s.execute(
            select(WorkflowVersion)
            .where(WorkflowVersion.workflow_id == workflow_id, WorkflowVersion.version == version)
            .with_for_update()
        )
    ).scalar_one_or_none()
    if v is None:
        raise LifecycleError(f"version {version} not found", status=404)
    return v


def _new_version(

    tenant_id: uuid.UUID,

    wf: Workflow,

    number: int,

    defn: WorkflowDefinition,

    report: CheckReport,

    *,

    actor: str,

    nl_source: str | None,

    parent: int | None = None,

    note: str | None = None,

) -> WorkflowVersion:
    pinned = defn.model_copy(update={"id": wf.key, "version": number})
    return WorkflowVersion(
        tenant_id=tenant_id,
        workflow_id=wf.id,
        version=number,
        definition=pinned.model_dump(mode="json"),
        definition_hash=pinned.content_hash(),
        nl_source=nl_source,
        status="draft",
        checks=report.as_dict(),
        created_by=actor,
        parent_version=parent,
        note=note,
    )


async def create_workflow(

    db: Database,

    tenant_id: uuid.UUID,

    data: dict[str, Any] | WorkflowDefinition,

    registry: ToolRegistry,

    *,

    actor: str,

    user_id: uuid.UUID | None = None,

    nl_source: str | None = None,

    source: str = "json",

    template: str | None = None,

) -> tuple[Workflow, WorkflowVersion]:
    defn, report = _validated(data, registry)
    async with db.session(tenant_id=tenant_id) as s, s.begin():
        key = defn.id
        taken = set(
            (await s.execute(select(Workflow.key).where(Workflow.key.like(f"{key[:55]}%"))))
            .scalars()
            .all()
        )
        n = 2
        while key in taken:  # a second copy of a template gets a suffix
            key = f"{defn.id[:55]}_{n}"
            n += 1
        wf = Workflow(
            id=uuid.uuid4(),
            tenant_id=tenant_id,
            key=key,
            name=defn.name,
            description=defn.description,
            status="draft",
            source=source,
            template=template,
            created_by=user_id,
        )
        s.add(wf)
        await s.flush()
        v = _new_version(tenant_id, wf, 1, defn, report, actor=actor, nl_source=nl_source)
        s.add(v)
    return wf, v


async def add_version(

    db: Database,

    tenant_id: uuid.UUID,

    workflow_id: uuid.UUID,

    data: dict[str, Any] | WorkflowDefinition,

    registry: ToolRegistry,

    *,

    actor: str,

    nl_source: str | None = None,

    note: str | None = None,

) -> WorkflowVersion:
    defn, report = _validated(data, registry)
    async with db.session(tenant_id=tenant_id) as s, s.begin():
        wf = await _workflow(s, workflow_id)
        last = (
            await s.execute(
                select(func.max(WorkflowVersion.version)).where(
                    WorkflowVersion.workflow_id == workflow_id
                )
            )
        ).scalar_one()
        number = int(last or 0) + 1
        v = _new_version(
            tenant_id,
            wf,
            number,
            defn,
            report,
            actor=actor,
            nl_source=nl_source,
            parent=wf.active_version or (number - 1 or None),
            note=note,
        )
        s.add(v)
        wf.name, wf.description, wf.updated_at = defn.name, defn.description, datetime.now(UTC)
    return v


async def record_dry_run(

    db: Database, tenant_id: uuid.UUID, workflow_id: uuid.UUID, version: int, report: dict

) -> WorkflowVersion:
    async with db.session(tenant_id=tenant_id) as s, s.begin():
        v = await _version(s, workflow_id, version)
        v.dry_run = report
        v.dry_run_at = datetime.now(UTC)
        v.dry_run_hash = report.get("definition_hash")
        if v.status in ("draft", "dry_run_ok", "dry_run_failed"):
            v.status = "dry_run_ok" if report.get("ok") else "dry_run_failed"
    return v


async def approve(

    db: Database, tenant_id: uuid.UUID, workflow_id: uuid.UUID, version: int, user_id: uuid.UUID

) -> WorkflowVersion:
    async with db.session(tenant_id=tenant_id) as s, s.begin():
        v = await _version(s, workflow_id, version)
        if v.status != "dry_run_ok":
            raise LifecycleError(f"version {version} is {v.status}: it needs a passing dry run")
        if v.dry_run_hash != v.definition_hash:
            raise LifecycleError("the dry run does not match this definition; dry-run again")
        v.status = "approved"
        v.approved_by = user_id
        v.approved_at = datetime.now(UTC)
    return v


async def sync_triggers(

    s: AsyncSession, wf: Workflow, defn: WorkflowDefinition | None, version: int | None

) -> None:
    """Make the engine's schedule / subscription rows match the active version (or none)."""
    name = schedule_name(wf.id)
    sched = (await s.execute(select(Schedule).where(Schedule.name == name))).scalar_one_or_none()
    trig = (
        await s.execute(select(WorkflowTrigger).where(WorkflowTrigger.workflow_id == wf.id))
    ).scalar_one_or_none()
    t = defn.trigger if defn is not None else None
    if isinstance(t, ScheduleTrigger) and version is not None:
        payload = {"workflow_id": str(wf.id), "version": version, "trigger": "schedule"}
        nxt = event_store.next_fire(t.cron, t.tz, datetime.now(UTC))
        if sched is None:
            s.add(
                Schedule(
                    tenant_id=wf.tenant_id,
                    name=name,
                    cron=t.cron,
                    timezone=t.tz,
                    event_type=WORKFLOW_INTENT,
                    payload=payload,
                    enabled=True,
                    next_run_at=nxt,
                )
            )
        else:
            sched.cron, sched.timezone, sched.payload = t.cron, t.tz, payload
            sched.event_type, sched.enabled, sched.next_run_at = WORKFLOW_INTENT, True, nxt
    elif sched is not None:
        await s.delete(sched)
    if isinstance(t, EventTrigger) and version is not None:
        conds = [c.model_dump(mode="json") for c in t.when]
        if trig is None:
            s.add(
                WorkflowTrigger(
                    tenant_id=wf.tenant_id,
                    workflow_id=wf.id,
                    version=version,
                    event_type=t.event_type,
                    conditions=conds,
                    enabled=True,
                )
            )
        else:
            trig.version, trig.event_type, trig.conditions, trig.enabled = (
                version,
                t.event_type,
                conds,
                True,
            )
    elif trig is not None:
        await s.delete(trig)
    await s.flush()


async def _activate(s: AsyncSession, wf: Workflow, v: WorkflowVersion) -> None:
    now = datetime.now(UTC)
    if wf.active_version is not None and wf.active_version != v.version:
        cur = await _version(s, wf.id, wf.active_version)
        cur.status, cur.deactivated_at = "superseded", now
    v.status, v.activated_at, v.deactivated_at = "active", now, None
    wf.status, wf.active_version, wf.updated_at = "active", v.version, now
    await sync_triggers(s, wf, WorkflowDefinition.model_validate(v.definition), v.version)


async def activate(

    db: Database, tenant_id: uuid.UUID, workflow_id: uuid.UUID, version: int

) -> WorkflowVersion:
    async with db.session(tenant_id=tenant_id) as s, s.begin():
        wf = await _workflow(s, workflow_id)
        v = await _version(s, workflow_id, version)
        if v.status == "active":
            return v
        if v.status not in ACTIVATABLE or v.approved_at is None:
            raise LifecycleError(f"version {version} is {v.status}: an owner must approve it")
        await _activate(s, wf, v)
    return v


async def rollback(

    db: Database, tenant_id: uuid.UUID, workflow_id: uuid.UUID

) -> WorkflowVersion | None:
    """Active N -> rolled_back; the latest earlier version that was active becomes active."""
    async with db.session(tenant_id=tenant_id) as s, s.begin():
        wf = await _workflow(s, workflow_id)
        if wf.active_version is None:
            raise LifecycleError("workflow has no active version to roll back")
        cur = await _version(s, workflow_id, wf.active_version)
        now = datetime.now(UTC)
        cur.status, cur.deactivated_at = "rolled_back", now
        prev = (
            await s.execute(
                select(WorkflowVersion)
                .where(
                    WorkflowVersion.workflow_id == workflow_id,
                    WorkflowVersion.version < cur.version,
                    WorkflowVersion.activated_at.is_not(None),
                    WorkflowVersion.status == "superseded",
                )
                .order_by(WorkflowVersion.version.desc())
                .limit(1)
                .with_for_update()
            )
        ).scalar_one_or_none()
        if prev is None:
            wf.status, wf.active_version, wf.updated_at = "paused", None, now
            await sync_triggers(s, wf, None, None)
            return None
        wf.active_version = None  # cur is no longer active; _activate must not supersede it
        await _activate(s, wf, prev)
        return prev


async def deactivate(db: Database, tenant_id: uuid.UUID, workflow_id: uuid.UUID) -> None:
    async with db.session(tenant_id=tenant_id) as s, s.begin():
        wf = await _workflow(s, workflow_id)
        if wf.active_version is not None:
            cur = await _version(s, workflow_id, wf.active_version)
            cur.status, cur.deactivated_at = "superseded", datetime.now(UTC)
        wf.status, wf.active_version, wf.updated_at = "paused", None, datetime.now(UTC)
        await sync_triggers(s, wf, None, None)


async def auto_apply(

    db: Database,

    tenant_id: uuid.UUID,

    workflow_id: uuid.UUID,

    base_version: int,

    defn: WorkflowDefinition,

    registry: ToolRegistry,

    *,

    note: str,

) -> WorkflowVersion | None:
    """Self-healing for retry/backoff-only fixes the tenant opted into: a new version that

    differs from the active one only in ``retry`` settings, activated without a new owner

    approval. Returns None if the base is no longer the active version."""
    defn, report = _validated(defn, registry)
    async with db.session(tenant_id=tenant_id) as s, s.begin():
        wf = await _workflow(s, workflow_id)
        if wf.active_version != base_version:
            return None
        base = await _version(s, workflow_id, base_version)
        if not only_retry_changed(WorkflowDefinition.model_validate(base.definition), defn):
            raise LifecycleError("auto-apply is limited to retry/backoff changes")
        last = (
            await s.execute(
                select(func.max(WorkflowVersion.version)).where(
                    WorkflowVersion.workflow_id == workflow_id
                )
            )
        ).scalar_one()
        v = _new_version(
            tenant_id,
            wf,
            int(last) + 1,
            defn,
            report,
            actor="system:self-heal",
            nl_source=base.nl_source,
            parent=base_version,
            note=note,
        )
        v.approved_at = datetime.now(UTC)  # inherits the owner's approval of the base version
        v.approved_by = base.approved_by
        s.add(v)
        await s.flush()
        await _activate(s, wf, v)
    return v


def only_retry_changed(a: WorkflowDefinition, b: WorkflowDefinition) -> bool:
    def strip(d: WorkflowDefinition) -> dict[str, Any]:
        c = d.content()
        for st in c["steps"]:
            st.pop("retry", None)
        return c

    return strip(a) == strip(b)