auto / language_core /executor /cancel_runner.py
rsnarsna
feat(alli-backend): Wave-1 standardization, standalone sys.env node & vault crypto, and DEC-014 security hardening
8628c98
Raw History Blame Contribute Delete
3.35 kB
"""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,
}