Spaces:
Running
Running
Download core/workflows/versions.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/workflows/versions.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/workflows/versions.py
-
curl -L -o versions.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/workflows/versions.py
14.6 kB
| """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) | |