File size: 3,859 Bytes
ea3ef49
91a883e
 
 
 
ea3ef49
 
 
91a883e
ea3ef49
 
 
 
91a883e
 
 
 
 
 
 
 
 
 
 
 
 
ea3ef49
91a883e
 
 
ea3ef49
91a883e
 
 
 
 
 
 
ea3ef49
91a883e
 
 
ea3ef49
91a883e
 
 
 
 
 
 
 
 
 
 
ea3ef49
 
 
91a883e
ea3ef49
91a883e
 
ea3ef49
91a883e
 
 
 
 
 
 
 
 
 
 
ea3ef49
 
 
91a883e
 
 
 
 
 
 
ea3ef49
 
 
 
 
 
 
91a883e
ea3ef49
 
 
 
91a883e
ea3ef49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
ALLI Lambda Function 3: DAG Topology Compiler (alli-compile)
Pure mathematical DAG compiler: constructs topological adjacency graphs,
calculates in-degrees, checks for circular deadlocks (DAG-001) using Kahn's algorithm,
and computes strict execution order.
"""

import json
from collections import defaultdict, deque
from typing import Dict, Any, List, Optional
from language_core.topology import TopologyGraph, Node, Port, Connection


def compile_dag_logic(nodes: List[Dict[str, Any]], edges: List[Dict[str, Any]]) -> Dict[str, Any]:
    """Pure mathematical DAG analysis and execution sequencing."""
    if not nodes:
        return {
            "success": True,
            "has_cycle": False,
            "node_count": 0,
            "edge_count": 0,
            "execution_order": [],
            "in_degrees": {},
            "diagnostics": [],
        }

    diagnostics = []
    node_map = {n["id"]: n for n in nodes}
    in_degrees = {n["id"]: 0 for n in nodes}
    adj_list = defaultdict(list)

    # Build dependency graph
    for edge in edges:
        src = edge.get("source")
        tgt = edge.get("target")
        if src in node_map and tgt in node_map:
            adj_list[src].append(tgt)
            in_degrees[tgt] += 1

    # Kahn's Algorithm for topological sorting & cycle detection
    queue = deque([n_id for n_id, deg in in_degrees.items() if deg == 0])
    ordered_ids = []

    while queue:
        curr = queue.popleft()
        ordered_ids.append(curr)
        for neighbor in adj_list[curr]:
            in_degrees[neighbor] -= 1
            if in_degrees[neighbor] == 0:
                queue.append(neighbor)

    has_cycle = len(ordered_ids) < len(nodes)

    if has_cycle:
        diagnostics.append({
            "code": "DAG-001",
            "severity": "error",
            "message": "Circular dependency detected! The workflow graph contains a loop that will deadlock.",
        })
        # Return original IDs as fallback
        ordered_ids = [n["id"] for n in nodes]

    # Compute execution steps with node details
    ordered_steps = []
    for step_num, n_id in enumerate(ordered_ids, 1):
        node = node_map.get(n_id, {})
        ordered_steps.append({
            "step": step_num,
            "node_id": n_id,
            "node_type": node.get("node_type") or node.get("type", "custom"),
            "label": node.get("data", {}).get("label") or node.get("node_type", "node"),
            "incoming_dependencies": [e.get("source") for e in edges if e.get("target") == n_id],
        })

    return {
        "success": not has_cycle,
        "has_cycle": has_cycle,
        "node_count": len(nodes),
        "edge_count": len(edges),
        "execution_order": ordered_ids,
        "ordered_steps": ordered_steps,
        "in_degrees": in_degrees,
        "diagnostics": diagnostics,
    }


def handler(event: Dict[str, Any], context: Any = None) -> Dict[str, Any]:
    """Standalone AWS Lambda handler entrypoint for alli-compile function."""
    try:
        body_raw = event.get("body", "{}")
        body = json.loads(body_raw) if isinstance(body_raw, str) else body_raw

        nodes = body.get("nodes", [])
        edges = body.get("edges", [])

        result = compile_dag_logic(nodes, edges)

        return {
            "statusCode": 200,
            "headers": {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "POST, OPTIONS",
            },
            "body": json.dumps(result),
        }
    except Exception as err:
        return {
            "statusCode": 500,
            "headers": {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "*",
            },
            "body": json.dumps({"error": str(err)}),
        }