File size: 15,764 Bytes
52cd762
4992fbd
 
 
52cd762
 
 
 
4992fbd
52cd762
 
 
 
 
 
 
 
 
4992fbd
 
 
 
 
52cd762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4992fbd
52cd762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4992fbd
 
 
 
 
 
52cd762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4992fbd
 
 
 
 
 
52cd762
 
 
 
 
 
 
 
4992fbd
 
 
 
 
 
52cd762
 
 
 
 
 
 
 
 
 
4992fbd
52cd762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ab51f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4992fbd
 
 
 
 
 
52cd762
 
 
 
 
 
4992fbd
52cd762
 
 
 
 
 
 
 
 
 
4992fbd
52cd762
 
 
 
 
4992fbd
 
 
 
 
 
 
 
 
 
52cd762
 
 
 
 
 
 
4992fbd
 
 
 
 
 
 
52cd762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4992fbd
 
 
 
 
 
 
52cd762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4992fbd
 
 
 
 
52cd762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4992fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52cd762
4992fbd
52cd762
 
 
 
 
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
"""
Regression and Acceptance Test Suite for Phase 3.6 & Phase 5 Step 5.2: Connection Validation.
Verifies all 11 criteria of connection validation across Language Core, Topology Graph, and Validate Lambda.
Supports both pytest discovery and standalone script execution.
"""

import sys
from pathlib import Path
import pytest

# Add backend root directory to sys.path
sys.path.insert(0, str(Path(__file__).parent.parent))

from language_core.types import parse_type_string, DataType
from language_core.topology import TopologyGraph, Node, Port, InvalidConnectionError, CycleDetectedError
from lambdas.validate_handler import validate_connection_logic, validate_types_logic


# ---------------------------------------------------------------------------
# Test Fixture Nodes Map
# ---------------------------------------------------------------------------
def get_fixture_nodes_map():
    return {
        "math_node": {
            "id": "math_node",
            "type": "math.sqrt",
            "inputs": [
                {"id": "x", "name": "x", "type_hint": "float", "kind": "data", "multiple": False}
            ],
            "outputs": [
                {"id": "result", "name": "result", "type_hint": "float", "kind": "data"}
            ]
        },
        "int_provider": {
            "id": "int_provider",
            "type": "constant.int",
            "inputs": [],
            "outputs": [
                {"id": "val", "name": "value", "type_hint": "int", "kind": "data"}
            ]
        },
        "str_provider": {
            "id": "str_provider",
            "type": "constant.str",
            "inputs": [],
            "outputs": [
                {"id": "out", "name": "text", "type_hint": "str", "kind": "data"}
            ]
        },
        "printer": {
            "id": "printer",
            "type": "display.output",
            "inputs": [
                {"id": "in", "name": "input", "type_hint": "Any", "kind": "data", "multiple": True}
            ],
            "outputs": []
        },
        "branch_node": {
            "id": "branch_node",
            "type": "control.branch",
            "inputs": [
                {"id": "condition", "name": "condition", "type_hint": "bool", "kind": "data"},
                {"id": "flow_in", "name": "flow_in", "type_hint": "control", "kind": "control"}
            ],
            "outputs": [
                {"id": "true_flow", "name": "then", "type_hint": "control", "kind": "control"},
                {"id": "false_flow", "name": "else", "type_hint": "control", "kind": "control"}
            ]
        },
        "action_node": {
            "id": "action_node",
            "type": "control.action",
            "inputs": [
                {"id": "exec", "name": "exec", "type_hint": "control", "kind": "control"}
            ],
            "outputs": [
                {"id": "done", "name": "done", "type_hint": "control", "kind": "control"}
            ]
        }
    }


# ---------------------------------------------------------------------------
# 1. Node & Port Schema Resolution
# ---------------------------------------------------------------------------
def test_node_and_port_resolution():
    nodes_map = get_fixture_nodes_map()
    
    # Missing node
    res = validate_connection_logic(
        {"source": "non_existent", "target": "math_node", "sourceHandle": "out", "targetHandle": "x"},
        nodes_map=nodes_map
    )
    assert not res["valid"] and res["code"] == "VAL-NODE-NOT-FOUND", f"Failed: {res}"

    # Missing source port
    res = validate_connection_logic(
        {"source": "int_provider", "target": "math_node", "sourceHandle": "unknown_port", "targetHandle": "x"},
        nodes_map=nodes_map
    )
    assert not res["valid"] and res["code"] == "VAL-PORT-NOT-FOUND", f"Failed: {res}"

    # Missing target port
    res = validate_connection_logic(
        {"source": "int_provider", "target": "math_node", "sourceHandle": "val", "targetHandle": "unknown_port"},
        nodes_map=nodes_map
    )
    assert not res["valid"] and res["code"] == "VAL-PORT-NOT-FOUND", f"Failed: {res}"


# ---------------------------------------------------------------------------
# 2. Port Direction Validation
# ---------------------------------------------------------------------------
def test_port_direction_validation():
    nodes_map = get_fixture_nodes_map()
    
    # Reversing direction: Input handle -> Output handle
    res = validate_connection_logic(
        {"source": "math_node", "target": "int_provider", "sourceHandle": "x", "targetHandle": "val"},
        nodes_map=nodes_map
    )
    assert not res["valid"] and res["code"] == "VAL-PORT-DIRECTION", f"Failed: {res}"


# ---------------------------------------------------------------------------
# 3. Type Compatibility, Widening, and Any
# ---------------------------------------------------------------------------
def test_type_compatibility_widening_and_any():
    nodes_map = get_fixture_nodes_map()
    
    # Numeric widening: int -> float (Allowed)
    res = validate_connection_logic(
        {"source": "int_provider", "target": "math_node", "sourceHandle": "val", "targetHandle": "x"},
        nodes_map=nodes_map
    )
    assert res["valid"], f"Expected valid int -> float widening, got {res}"

    # Type mismatch: str -> float (Rejected)
    res = validate_connection_logic(
        {"source": "str_provider", "target": "math_node", "sourceHandle": "out", "targetHandle": "x"},
        nodes_map=nodes_map
    )
    assert not res["valid"] and res["code"] == "VAL-TYPE-MISMATCH", f"Failed: {res}"

    # Precision loss: float -> int (Rejected)
    res_float_to_int = validate_types_logic("float", "int")
    assert not res_float_to_int["valid"], f"Expected float -> int rejection, got {res_float_to_int}"

    # Any handling: float -> Any (Allowed)
    res_any = validate_connection_logic(
        {"source": "math_node", "target": "printer", "sourceHandle": "result", "targetHandle": "in"},
        nodes_map=nodes_map
    )
    assert res_any["valid"], f"Expected valid float -> Any, got {res_any}"

    # Step 5.3: GAP-04 Source Union Strict Assignability
    res_union_mismatch = validate_types_logic("int | str", "int")
    assert not res_union_mismatch["valid"], f"Expected int | str -> int rejection: {res_union_mismatch}"
    assert "Union Type Mismatch" in res_union_mismatch["reason"]

    res_union_valid = validate_types_logic("int | float", "number")
    assert res_union_valid["valid"], f"Expected int | float -> number valid: {res_union_valid}"

    # Step 5.3: GAP-09 Abstract Collections Compatibility
    res_iter = validate_types_logic("list[int]", "iterable[int]")
    assert res_iter["valid"], f"Expected list[int] -> iterable[int] valid: {res_iter}"

    res_seq_reject = validate_types_logic("set[int]", "sequence[int]")
    assert not res_seq_reject["valid"], f"Expected set[int] -> sequence[int] rejection: {res_seq_reject}"

    # Step 5.3: GAP-10 Untyped container dynamic warning
    res_untyped = validate_types_logic("list", "iterable[int]")
    assert res_untyped["valid"], f"Expected list -> iterable[int] valid: {res_untyped}"
    assert res_untyped.get("warning") and "Dynamic Source" in res_untyped["warning"]


# ---------------------------------------------------------------------------
# 4. Port Multiplicity Constraints
# ---------------------------------------------------------------------------
def test_port_multiplicity_constraints():
    nodes_map = get_fixture_nodes_map()
    existing_edges = [
        {"id": "e1", "source": "int_provider", "target": "math_node", "sourceHandle": "val", "targetHandle": "x"}
    ]

    # Trying to connect a second source to math_node's 'x' (multiple: False)
    res = validate_connection_logic(
        {"source": "str_provider", "target": "math_node", "sourceHandle": "out", "targetHandle": "x"},
        nodes_map=nodes_map,
        edges=existing_edges
    )
    assert not res["valid"] and res["code"] == "VAL-PORT-MULTIPLICITY", f"Failed: {res}"

    # Printer's 'in' allows multiple: True
    printer_edges = [
        {"id": "e_print1", "source": "int_provider", "target": "printer", "sourceHandle": "val", "targetHandle": "in"}
    ]
    res_multi = validate_connection_logic(
        {"source": "str_provider", "target": "printer", "sourceHandle": "out", "targetHandle": "in"},
        nodes_map=nodes_map,
        edges=printer_edges
    )
    assert res_multi["valid"], f"Expected multiple inputs allowed on printer.in, got: {res_multi}"


# ---------------------------------------------------------------------------
# 5. Duplicate Connection Rejection
# ---------------------------------------------------------------------------
def test_duplicate_connection_rejection():
    nodes_map = get_fixture_nodes_map()
    existing_edges = [
        {"id": "e1", "source": "int_provider", "target": "math_node", "sourceHandle": "val", "targetHandle": "x"}
    ]

    dup_res = validate_connection_logic(
        {"source": "int_provider", "target": "math_node", "sourceHandle": "val", "targetHandle": "x"},
        nodes_map=nodes_map,
        edges=existing_edges
    )
    assert not dup_res["valid"] and dup_res["code"] == "VAL-DUPLICATE-CONNECTION", f"Failed: {dup_res}"


# ---------------------------------------------------------------------------
# 6. Cycle Detection (DAG-001)
# ---------------------------------------------------------------------------
def test_cycle_detection_dag001():
    nodes_map = get_fixture_nodes_map()

    # Self-loop
    self_loop_res = validate_connection_logic(
        {"source": "math_node", "target": "math_node", "sourceHandle": "result", "targetHandle": "x"},
        nodes_map=nodes_map
    )
    assert not self_loop_res["valid"] and self_loop_res["code"] == "DAG-001", f"Failed: {self_loop_res}"

    # Multi-node cycle: A -> B -> C -> A
    cycle_nodes_map = {
        "A": {"id": "A", "outputs": [{"id": "out", "type_hint": "Any", "kind": "data"}], "inputs": [{"id": "in", "type_hint": "Any", "kind": "data", "multiple": True}]},
        "B": {"id": "B", "outputs": [{"id": "out", "type_hint": "Any", "kind": "data"}], "inputs": [{"id": "in", "type_hint": "Any", "kind": "data", "multiple": True}]},
        "C": {"id": "C", "outputs": [{"id": "out", "type_hint": "Any", "kind": "data"}], "inputs": [{"id": "in", "type_hint": "Any", "kind": "data", "multiple": True}]},
    }
    chain_edges = [
        {"source": "A", "target": "B", "sourceHandle": "out", "targetHandle": "in"},
        {"source": "B", "target": "C", "sourceHandle": "out", "targetHandle": "in"},
    ]
    # Connecting C -> A creates cycle A -> B -> C -> A
    cycle_res = validate_connection_logic(
        {"source": "C", "target": "A", "sourceHandle": "out", "targetHandle": "in"},
        nodes_map=cycle_nodes_map,
        edges=chain_edges
    )
    assert not cycle_res["valid"] and cycle_res["code"] == "DAG-001", f"Failed: {cycle_res}"


# ---------------------------------------------------------------------------
# 7. Control-Flow Isolation
# ---------------------------------------------------------------------------
def test_control_flow_isolation():
    nodes_map = get_fixture_nodes_map()

    # Valid: Control -> Control
    res_ctrl = validate_connection_logic(
        {"source": "branch_node", "target": "action_node", "sourceHandle": "true_flow", "targetHandle": "exec"},
        nodes_map=nodes_map
    )
    assert res_ctrl["valid"], f"Expected valid control connection, got {res_ctrl}"

    # Invalid: Data output -> Control input
    res_data_to_ctrl = validate_connection_logic(
        {"source": "int_provider", "target": "action_node", "sourceHandle": "val", "targetHandle": "exec"},
        nodes_map=nodes_map
    )
    assert not res_data_to_ctrl["valid"] and res_data_to_ctrl["code"] == "VAL-CONTROL-ISOLATION", f"Failed: {res_data_to_ctrl}"

    # Invalid: Control output -> Data input
    res_ctrl_to_data = validate_connection_logic(
        {"source": "branch_node", "target": "printer", "sourceHandle": "true_flow", "targetHandle": "in"},
        nodes_map=nodes_map
    )
    assert not res_ctrl_to_data["valid"] and res_ctrl_to_data["code"] == "VAL-CONTROL-ISOLATION", f"Failed: {res_ctrl_to_data}"


# ---------------------------------------------------------------------------
# 8. Backend TopologyGraph Engine Integration
# ---------------------------------------------------------------------------
def test_topology_graph_in_memory_engine():
    graph = TopologyGraph()
    n1 = Node(node_id="n1", label="Int Output")
    n1.add_output("out", parse_type_string("int"))

    n2 = Node(node_id="n2", label="Float Input")
    n2.add_input("in", parse_type_string("float"))

    n3 = Node(node_id="n3", label="Str Input")
    n3.add_input("in", parse_type_string("str"))

    graph.add_node(n1)
    graph.add_node(n2)
    graph.add_node(n3)

    # Valid widening connect
    graph.connect("n1", "out", "n2", "in")
    assert len(graph.connections) == 1

    # Duplicate connect rejection
    try:
        graph.connect("n1", "out", "n2", "in")
        assert False, "Should have raised InvalidConnectionError for duplicate"
    except InvalidConnectionError as err:
        assert err.code == "VAL-DUPLICATE-CONNECTION"

    # Type mismatch rejection
    try:
        graph.connect("n1", "out", "n3", "in")
        assert False, "Should have raised InvalidConnectionError for int -> str"
    except InvalidConnectionError as err:
        assert err.code == "VAL-TYPE-MISMATCH"

    # Self-loop rejection
    try:
        graph.connect("n1", "out", "n1", "out")
        assert False, "Should have raised InvalidConnectionError for self-loop"
    except InvalidConnectionError as err:
        assert err.code == "DAG-001"


# ---------------------------------------------------------------------------
# 9. Step 5.2 Edge Cases: Incomplete Connections
# ---------------------------------------------------------------------------
def test_edge_empty_and_malformed_node_ids():
    nodes_map = get_fixture_nodes_map()
    # Missing source endpoint
    res = validate_connection_logic(
        {"source": "", "target": "math_node", "sourceHandle": "out", "targetHandle": "x"},
        nodes_map=nodes_map
    )
    assert not res["valid"] and res["code"] == "VAL-INCOMPLETE-EDGE"

    # Missing target endpoint
    res2 = validate_connection_logic(
        {"source": "int_provider", "target": None, "sourceHandle": "val", "targetHandle": "x"},
        nodes_map=nodes_map
    )
    assert not res2["valid"] and res2["code"] == "VAL-INCOMPLETE-EDGE"


def run_tests():
    print("=" * 70)
    print("ALLI PHASE 3.6 & 5.2: CONNECTION VALIDATION REGRESSION TEST SUITE")
    print("=" * 70)
    test_node_and_port_resolution()
    print("  [PASS] test_node_and_port_resolution")
    test_port_direction_validation()
    print("  [PASS] test_port_direction_validation")
    test_type_compatibility_widening_and_any()
    print("  [PASS] test_type_compatibility_widening_and_any")
    test_port_multiplicity_constraints()
    print("  [PASS] test_port_multiplicity_constraints")
    test_duplicate_connection_rejection()
    print("  [PASS] test_duplicate_connection_rejection")
    test_cycle_detection_dag001()
    print("  [PASS] test_cycle_detection_dag001")
    test_control_flow_isolation()
    print("  [PASS] test_control_flow_isolation")
    test_topology_graph_in_memory_engine()
    print("  [PASS] test_topology_graph_in_memory_engine")
    test_edge_empty_and_malformed_node_ids()
    print("  [PASS] test_edge_empty_and_malformed_node_ids")
    print("\n" + "=" * 70)
    print("ALL CONNECTION VALIDATION TESTS PASSED (100% SUCCESS)")
    print("=" * 70)


if __name__ == "__main__":
    run_tests()