File size: 3,351 Bytes
8628c98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Authoritative workflow run cancellation handler."""

from datetime import datetime, timezone
from typing import Any, Dict, List, Optional

from language_core.execution_session import GLOBAL_SESSION_REGISTRY
from language_core.executor.state_and_errors import make_error_semantics, validate_state_transition
from language_core.runtime_events import EVENT_NODE_CANCELLED, EVENT_RUN_CANCELLED, GLOBAL_EVENT_STORE
from runtime_environment.active_runs import GLOBAL_ACTIVE_RUNS


def cancel_workflow_run(
    run_id: Optional[str] = None,
    node_results: Optional[Dict[str, Dict[str, Any]]] = None,
) -> Dict[str, Any]:
    """Authoritative idempotent workflow cancellation across active runs and step sessions."""
    clean_run_id = str(run_id).strip() if run_id else None
    updated_results = dict(node_results or {})

    if clean_run_id:
        GLOBAL_ACTIVE_RUNS.cancel(clean_run_id)
        session = GLOBAL_SESSION_REGISTRY.cancel(clean_run_id)
        if session:
            for nid, r in session.node_results.items():
                if nid not in updated_results or (r.get("exec_state") or r.get("status")) == "cancelled":
                    updated_results[nid] = r

    cancelled_nodes: List[str] = []
    for nid, r in updated_results.items():
        curr_state = r.get("exec_state") or r.get("status") or "idle"
        if curr_state in ("running", "queued") and validate_state_transition(curr_state, "cancelled"):
            lbl = r.get("label") or nid
            updated_results[nid] = {
                **r,
                "status": "cancelled",
                "exec_state": "cancelled",
                "freshness": "invalidated",
                "error": "[CANCELLED] Node execution was cancelled by user request.",
                "error_semantics": make_error_semantics(
                    code="ERR-CANCELLED",
                    what=f"Execution cancelled: {lbl}",
                    node_id=nid,
                    node_label=lbl,
                    why="Execution was cancelled by authoritative cancellation request.",
                    how_to_fix="Rerun the workflow when ready.",
                    severity="info",
                ),
            }
            cancelled_nodes.append(nid)

    ts = datetime.now(timezone.utc).isoformat()
    logs = [
        f"[CANCELLED] Run '{run_id or 'unknown'}' cancelled at {ts}.",
        f"[CANCELLED] Cancelled {len(cancelled_nodes)} node(s): {', '.join(cancelled_nodes) if cancelled_nodes else 'none in flight'}.",
    ]
    if clean_run_id:
        g_rev = (GLOBAL_EVENT_STORE.get_run_metadata(clean_run_id) or {}).get("graph_revision", "")
        for c_nid in cancelled_nodes:
            GLOBAL_EVENT_STORE.record_event(
                run_id=clean_run_id, graph_revision=g_rev, event_type=EVENT_NODE_CANCELLED,
                node_id=c_nid, status="cancelled", message=f"Node '{c_nid}' cancelled.",
            )
        GLOBAL_EVENT_STORE.record_event(
            run_id=clean_run_id, graph_revision=g_rev, event_type=EVENT_RUN_CANCELLED,
            status="cancelled", message=f"Run '{clean_run_id}' cancelled.",
        )

    return {
        "run_id": run_id or "run_cancelled",
        "status": "cancelled",
        "success": False,
        "cancelled_nodes": cancelled_nodes,
        "node_results": updated_results,
        "logs": logs,
    }