rsnarsna commited on
Commit ·
355ed30
1
Parent(s): 4df4f1d
feat(phase5): step 5.5 DAG cycle detection, loop feedback CTRL-001 & execution preflight hardening
Browse filesFiles changed (5)
112 unmodified lines11311411511611711819 unmodified lines138139140141142143144145233 unmodified lines379380381382383384328 unmodified lines7137147157167177187197207217227237247257267277287297307317 unmodified lines739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787112 unmodified lines}def validate_connection_logic(connection: Dict[str, Any],nodes_map: Optional[Dict[str, Any]] = None,19 unmodified lines"message": "Incomplete Connection: Both source and target endpoints must be provided.",}# Step 3.6.7: Self-connection prohibitedif from_node_id == to_node_id:return {"valid": False,"code": "DAG-001",233 unmodified lineswhile queue:curr = queue.popleft()if curr == from_node_id:return {"valid": False,"code": "DAG-001",328 unmodified lines)# ─── RULE 3.9.5: WHOLE-GRAPH DAG CYCLE DETECTION (KAHN'S ALGORITHM) ───────# Check if there are cyclical loops across the entire graphis_agent_workflow = any("agent" in str(n.get("node_type") or n.get("type") or n.get("data", {}).get("node_type") or "").lower()for n in nodes)if not is_agent_workflow and len(nodes) > 1:in_degrees = {nid: 0 for nid in node_map}adj_list = defaultdict(list)for e in edges:s = e.get("source") or e.get("from_node")t = e.get("target") or e.get("to_node")if s in in_degrees and t in in_degrees:adj_list[s].append(t)in_degrees[t] += 1queue = deque([nid for nid, deg in in_degrees.items() if deg == 0])7 unmodified linesqueue.append(neighbor)if processed_count < len(node_map) and edges:# Graph contains a cycle! Find cycle path with DFScycle_nodes = [nid for nid, deg in in_degrees.items() if deg > 0]cycle_path: List[str] = []visited_dfs = set()rec_stack: List[str] = []def dfs_find_cycle(node: str) -> bool:visited_dfs.add(node)rec_stack.append(node)for neighbor in adj_list.get(node, []):if neighbor in cycle_nodes:if neighbor in rec_stack:idx = rec_stack.index(neighbor)cycle_path.extend(rec_stack[idx:] + [neighbor])return Trueelif neighbor not in visited_dfs:if dfs_find_cycle(neighbor):return Truerec_stack.pop()return Falsefor cn in cycle_nodes:if cn not in visited_dfs:if dfs_find_cycle(cn):breakif not cycle_path and cycle_nodes:cycle_path = cycle_nodes[:3]cycle_labels = [node_map.get(cid, {}).get("data", {}).get("label") or cidfor cid in cycle_path]cycle_str = " -> ".join(cycle_labels) if cycle_labels else "circular dependency"add_diag("error","Connection Validation","DAG-001",f"[DAG-001] Dependency Cycle Detected: Workflow contains a circular dependency loop: {cycle_str}. Procedural Python workflows require a Directed Acyclic Graph (DAG).",3,node_id=cycle_path[0] if cycle_path else None,fix="Remove circular feedback connections or wrap the iteration inside a For/While Loop node.")# ─── RULE 3.9.5: START VALIDATION / ENTRYPOINT ───────────────────────────root_nodes = [nid for nid, inc in incoming_map.items() if len(inc) == 0]112 unmodified lines11311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116219 unmodified lines182183184185186187188189190191192193194195196197198199200233 unmodified lines434435436437438439440441442443444445446447448449450328 unmodified lines7797807817827837847857867877887897907917927937947957967977 unmodified lines805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903112 unmodified lines}def is_loop_header_node(node_dict: Optional[Dict[str, Any]]) -> bool:if not node_dict:return Falsed = node_dict.get("data") or {}ntype = str(node_dict.get("node_type") or node_dict.get("type") or d.get("node_type") or d.get("type") or "").lower()lbl = str(d.get("label") or node_dict.get("label") or "").lower()return ("for_loop" in ntypeor "while_loop" in ntypeor ntype in ("control.for_loop", "control.while_loop")or (d.get("category") == "Control Flow" and ("for" in lbl or "while" in lbl or "loop" in lbl)))def is_approved_agent_node(node_dict: Optional[Dict[str, Any]]) -> bool:if not node_dict:return Falsed = node_dict.get("data") or {}ntype = str(node_dict.get("node_type") or node_dict.get("type") or d.get("node_type") or d.get("type") or "").lower()cat = str(d.get("category") or "").lower()if cat in ("agent logic", "agent tools", "ai-agents"):return Trueif ntype.startswith("alli.agent.") or ntype.startswith("agent."):return TrueAPPROVED_AGENT_TYPES = {"alli.agent.llm", "agent.llm","alli.agent.tool", "agent.tool","alli.agent.router", "agent.router","alli.agent.memory", "agent.memory","alli.agent.prompt", "agent.prompt","agent.react_agent", "agent.reasoner","agent.checkpointer", "agent.memory_saver",}return ntype in APPROVED_AGENT_TYPESdef is_agent_reasoner_or_memory(node_dict: Optional[Dict[str, Any]]) -> bool:if not node_dict:return Falsed = node_dict.get("data") or {}ntype = str(node_dict.get("node_type") or node_dict.get("type") or d.get("node_type") or d.get("type") or "").lower()return any(k in ntype for k in ["llm", "reasoner", "react", "router", "memory", "checkpointer"])def validate_connection_logic(connection: Dict[str, Any],nodes_map: Optional[Dict[str, Any]] = None,19 unmodified lines"message": "Incomplete Connection: Both source and target endpoints must be provided.",}# Step 3.6.7: Self-connection prohibited (with loop header CTRL-001 distinction)if from_node_id == to_node_id:tgt_is_loop = Falseif nodes_map and to_node_id in nodes_map:tgt_is_loop = is_loop_header_node(nodes_map[to_node_id])if tgt_is_loop:return {"valid": False,"code": "CTRL-001","message": f"[CTRL-001] Invalid Loop Feedback: Node '{from_node_id}' cannot loop back directly to itself. ALLI loop constructs manage iterations internally without backward feedback wires.","source_node": from_node_id,"target_node": to_node_id,}return {"valid": False,"code": "DAG-001",233 unmodified lineswhile queue:curr = queue.popleft()if curr == from_node_id:if is_loop_header_node(tgt_node):return {"valid": False,"code": "CTRL-001","message": f"[CTRL-001] Invalid Loop Feedback: Connecting [{src_label}] -> [{tgt_label}] creates an invalid feedback wire targeting loop header '{tgt_label}'. ALLI loop constructs manage iterations internally without backward feedback wires.","source_node": from_node_id,"target_node": to_node_id,}if is_approved_agent_node(src_node) and is_approved_agent_node(tgt_node):# Approved agent cycle connection allowedbreakreturn {"valid": False,"code": "DAG-001",328 unmodified lines)# ─── RULE 3.9.5: WHOLE-GRAPH DAG CYCLE DETECTION (KAHN'S ALGORITHM) ───────# Detect cyclical loops across the entire graph.# GAP-06: Agent reasoning cycles are permitted ONLY when structurally contained within approved agent constructs.# GAP-12: Loop header feedback wires emit CTRL-001.if len(nodes) > 1:in_degrees = {nid: 0 for nid in node_map}adj_list = defaultdict(list)edge_map_by_pair = defaultdict(list)for e in edges:s = e.get("source") or e.get("from_node")t = e.get("target") or e.get("to_node")if s in in_degrees and t in in_degrees:adj_list[s].append(t)edge_map_by_pair[(s, t)].append(e)in_degrees[t] += 1queue = deque([nid for nid, deg in in_degrees.items() if deg == 0])7 unmodified linesqueue.append(neighbor)if processed_count < len(node_map) and edges:# Graph contains one or more cycles! Find cycle paths with DFScycle_nodes = [nid for nid, deg in in_degrees.items() if deg > 0]visited_dfs = set()found_cycles: List[List[str]] = []for start_cn in cycle_nodes:if start_cn in visited_dfs:continuec_path: List[str] = []rec_stack: List[str] = []def dfs_find_cycle(node: str) -> bool:visited_dfs.add(node)rec_stack.append(node)for neighbor in adj_list.get(node, []):if neighbor in cycle_nodes:if neighbor in rec_stack:idx = rec_stack.index(neighbor)c_path.extend(rec_stack[idx:] + [neighbor])return Trueelif neighbor not in visited_dfs:if dfs_find_cycle(neighbor):return Truerec_stack.pop()return Falseif dfs_find_cycle(start_cn) and c_path:found_cycles.append(c_path)if not found_cycles and cycle_nodes:found_cycles.append(cycle_nodes[:3])for c_path in found_cycles:# 1. Check for Loop Header feedback wires (GAP-12 -> CTRL-001)loop_header_edge = Nonefor i in range(len(c_path) - 1):u_id = c_path[i]v_id = c_path[i + 1]v_node = node_map.get(v_id, {})if is_loop_header_node(v_node):matched_edges = edge_map_by_pair.get((u_id, v_id), [{}])matched_edge = matched_edges[0] if matched_edges else {}loop_header_edge = (u_id,v_id,matched_edge.get("id"),matched_edge.get("target_handle") or matched_edge.get("targetHandle") or matched_edge.get("to_port"),)breakif loop_header_edge:u_id, v_id, eid, tgt_p = loop_header_edgeu_lbl = node_map.get(u_id, {}).get("data", {}).get("label") or u_idv_lbl = node_map.get(v_id, {}).get("data", {}).get("label") or v_idadd_diag("error","Control Flow","CTRL-001",f"[CTRL-001] Invalid Loop Feedback: Feedback wire from '{u_lbl}' ({u_id}) to loop header '{v_lbl}' ({v_id}) violates ALLI loop topology. ALLI loop constructs manage iterations internally without backward feedback wires. Connect downstream body nodes directly from loop outputs without looping back.",4,node_id=v_id,port_id=tgt_p,edge_id=eid,fix="Remove the backward feedback edge to the loop header. Use the loop node's internal iteration controls and downstream body flow.")continue# 2. Check for structurally contained approved agent reasoning loop (GAP-06)is_approved_agent_cycle = (len(c_path) >= 2and all(is_approved_agent_node(node_map.get(nid, {})) for nid in c_path)and any(is_agent_reasoner_or_memory(node_map.get(nid, {})) for nid in c_path))if is_approved_agent_cycle:# Permitted LangGraph ReAct reasoning cyclecontinue# 3. Unintended procedural or malformed cycle (GAP-06 -> DAG-001)cycle_labels = [node_map.get(cid, {}).get("data", {}).get("label") or cidfor cid in c_path]cycle_str = " -> ".join(cycle_labels) if cycle_labels else "circular dependency"add_diag("error","Connection Validation","DAG-001",f"[DAG-001] Dependency Cycle Detected: Workflow contains a circular dependency loop: {cycle_str}. Procedural Python workflows require a Directed Acyclic Graph (DAG).",3,node_id=c_path[0] if c_path else None,fix="Remove circular feedback connections or wrap the iteration inside a For/While Loop node.")# ─── RULE 3.9.5: START VALIDATION / ENTRYPOINT ───────────────────────────root_nodes = [nid for nid, inc in incoming_map.items() if len(inc) == 0]
17 unmodified lines18192021222324174 unmodified lines19920020120220320420520620720820921021121221321421517 unmodified linesfrom language_core.node_schema import default_registry, check_type_compatibilityfrom library_inspector.node_synthesizer import global_staging_registryfrom lambdas.validate_handler import validate_workflow_protocol_logicclass ExecutionPlanStatus(str, Enum):174 unmodified linesdependencies_map: Dict[str, List[str]] = {nid: [] for nid in node_map}reverse_deps_map: Dict[str, List[str]] = {nid: [] for nid in node_map}for e in edges:s = str(e.get("source") or e.get("from_node") or "")t = str(e.get("target") or e.get("to_node") or "")if s in node_map and t in node_map:incoming_edges_map[t].append(e)outgoing_edges_map[s].append(e)in_degrees[t] += 1if s not in dependencies_map[t]:dependencies_map[t].append(s)if t not in reverse_deps_map[s]:reverse_deps_map[s].append(t)# ─── 4. DETERMINISTIC TOPOLOGICAL SORTING & STAGING (KAHN'S ALGORITHM) ───# Compute topological depth rank for strict deterministic tie-breaking17 unmodified lines18192021222324174 unmodified lines19920020120220320420520620720820921021121221321421521621721821922022122222322422517 unmodified linesfrom language_core.node_schema import default_registry, check_type_compatibilityfrom library_inspector.node_synthesizer import global_staging_registryfrom lambdas.validate_handler import validate_workflow_protocol_logic, is_approved_agent_node, is_agent_reasoner_or_memoryclass ExecutionPlanStatus(str, Enum):174 unmodified linesdependencies_map: Dict[str, List[str]] = {nid: [] for nid in node_map}reverse_deps_map: Dict[str, List[str]] = {nid: [] for nid in node_map}agent_feedback_edges = set()for e in edges:s = str(e.get("source") or e.get("from_node") or "")t = str(e.get("target") or e.get("to_node") or "")if s in node_map and t in node_map:s_node = node_map[s]t_node = node_map[t]# Detect approved agent feedback edge in ReAct reasoning loopsif is_approved_agent_node(s_node) and is_approved_agent_node(t_node):if is_agent_reasoner_or_memory(t_node) and not is_agent_reasoner_or_memory(s_node):agent_feedback_edges.add((s, t))e["is_feedback"] = Trueincoming_edges_map[t].append(e)outgoing_edges_map[s].append(e)if (s, t) not in agent_feedback_edges:in_degrees[t] += 1if s not in dependencies_map[t]:dependencies_map[t].append(s)if t not in reverse_deps_map[s]:reverse_deps_map[s].append(t)# ─── 4. DETERMINISTIC TOPOLOGICAL SORTING & STAGING (KAHN'S ALGORITHM) ───# Compute topological depth rank for strict deterministic tie-breaking
104 unmodified lines10510610710810911011111265 unmodified lines17817918018118218332 unmodified lines216217218219220221104 unmodified linesdef connect(self, from_node: str, from_port: str, to_node: str, to_port: str):"""Creates a verified connection between two ports satisfying Phase 3.6 validation rules."""# Step 3.6.7: Self-connection prohibitedif from_node == to_node:raise CycleDetectedError(f"[DAG-001] Self-Loop Prohibited: Node '{from_node}' cannot connect directly to itself.", code="DAG-001")# Step 3.6.1: Node schema existence65 unmodified lineswhile queue:curr = queue.popleft()if curr == from_node:raise CycleDetectedError(f"[DAG-001] Dependency Cycle Detected: Connecting '{from_node}' to '{to_node}' creates a circular deadlock loop in the DAG.",code="DAG-001",32 unmodified linesqueue.append(neighbor)if len(ordered_ids) != len(self.nodes):raise RuntimeError("Topology Error: Circular dependency loop detected in the graph!")return [self.nodes[nid] for nid in ordered_ids]104 unmodified lines10510610710810911011111211311411511611711811965 unmodified lines18518618718818919019119219319419519619732 unmodified lines230231232233234235104 unmodified linesdef connect(self, from_node: str, from_port: str, to_node: str, to_port: str):"""Creates a verified connection between two ports satisfying Phase 3.6 validation rules."""# Step 3.6.7: Self-connection prohibited (with loop header CTRL-001 distinction)if from_node == to_node:tgt_n = self.nodes.get(to_node)tgt_t = getattr(tgt_n, "node_type", "") if tgt_n else ""if "loop" in str(tgt_t).lower():raise InvalidConnectionError(f"[CTRL-001] Invalid Loop Feedback: Node '{from_node}' cannot connect directly to itself as a loop feedback wire.",code="CTRL-001")raise CycleDetectedError(f"[DAG-001] Self-Loop Prohibited: Node '{from_node}' cannot connect directly to itself.", code="DAG-001")# Step 3.6.1: Node schema existence65 unmodified lineswhile queue:curr = queue.popleft()if curr == from_node:tgt_n = self.nodes.get(to_node)tgt_t = getattr(tgt_n, "node_type", "") if tgt_n else ""if "loop" in str(tgt_t).lower():raise InvalidConnectionError(f"[CTRL-001] Invalid Loop Feedback: Connecting '{from_node}' to loop header '{to_node}' violates ALLI loop topology.",code="CTRL-001")raise CycleDetectedError(f"[DAG-001] Dependency Cycle Detected: Connecting '{from_node}' to '{to_node}' creates a circular deadlock loop in the DAG.",code="DAG-001",32 unmodified linesqueue.append(neighbor)if len(ordered_ids) != len(self.nodes):raise CycleDetectedError("Topology Error: Circular dependency loop detected in the graph!", code="DAG-001")return [self.nodes[nid] for nid in ordered_ids]
1125 unmodified lines1126112711281129113011311125 unmodified linesExecutes a single ready node in the workflow graph with value propagation,enforcing state machine transitions, run_id stamping, and next node recommendation."""raw_nodes = graph.get("nodes") or []raw_edges = graph.get("edges") or []node_map: Dict[str, Dict[str, Any]] = {str(n.get("id")): n for n in raw_nodes}1125 unmodified lines112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601125 unmodified linesExecutes a single ready node in the workflow graph with value propagation,enforcing state machine transitions, run_id stamping, and next node recommendation."""start_total_time = time.perf_counter()run_id = str(graph.get("run_id") or (previous_results and next(iter(previous_results.values()), {}).get("run_id")) or f"run_{uuid.uuid4().hex[:12]}")created_ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())# Mandatory Execution Pre-flight Gate (Step 5.5)val_result = validate_workflow_protocol_logic(graph)if not val_result.get("valid") or not val_result.get("can_execute"):duration = round((time.perf_counter() - start_total_time) * 1000, 2)errors = [d.get("message", "Validation error") for d in val_result.get("diagnostics", []) if d.get("severity") == "error"]err_msg = "Workflow step execution blocked by pre-flight validation: " + "; ".join(errors[:3])return {"run_id": run_id,"step_node_id": target_node_id,"status": "failed","exec_state": "failed","node_result": None,"outputs": {},"output_ports": {},"next_node_id": None,"is_workflow_complete": False,"node_results": {},"previous_outputs": dict(previous_outputs or {}),"logs": [f"[ERROR] {err_msg}"],"stdout": "","stderr": err_msg,"exit_code": 1,"success": False,"validation_errors": val_result.get("diagnostics", []),}raw_nodes = graph.get("nodes") or []raw_edges = graph.get("edges") or []node_map: Dict[str, Dict[str, Any]] = {str(n.get("id")): n for n in raw_nodes}
11 unmodified lines121314151617592 unmodified lines61061161261361461561661761861911 unmodified linessys.path.insert(0, str(Path(__file__).parent.parent))from lambdas.validate_handler import validate_workflow_protocol_logic, validate_connection_logic# ---------------------------------------------------------------------------592 unmodified linesprint(" PASS: test_step5_4_python_identifier_validation")test_step5_4_execution_preflight_blocking()print(" PASS: test_step5_4_execution_preflight_blocking")print("\n" + "=" * 75)print("ALL 16 TEST SUITES PASSED WITH ZERO FAILURES!")print("=" * 75)if __name__ == "__main__":run_tests()11 unmodified lines1213141516171819592 unmodified lines61261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786811 unmodified linessys.path.insert(0, str(Path(__file__).parent.parent))from lambdas.validate_handler import validate_workflow_protocol_logic, validate_connection_logicfrom language_core.execution_planner import build_execution_planfrom language_core.workflow_executor import execute_workflow_graph, execute_workflow_step# ---------------------------------------------------------------------------592 unmodified linesprint(" PASS: test_step5_4_python_identifier_validation")test_step5_4_execution_preflight_blocking()print(" PASS: test_step5_4_execution_preflight_blocking")test_step5_5_ordinary_and_disconnected_cycles_dag001()print(" PASS: test_step5_5_ordinary_and_disconnected_cycles_dag001")test_step5_5_approved_agent_cycles_permitted()print(" PASS: test_step5_5_approved_agent_cycles_permitted")test_step5_5_malformed_agent_cycles_rejected()print(" PASS: test_step5_5_malformed_agent_cycles_rejected")test_step5_5_loop_feedback_ctrl001()print(" PASS: test_step5_5_loop_feedback_ctrl001")test_step5_5_execution_preflight_all_entrypoints()print(" PASS: test_step5_5_execution_preflight_all_entrypoints")print("\n" + "=" * 75)print("ALL 21 TEST SUITES PASSED WITH ZERO FAILURES!")print("=" * 75)if __name__ == "__main__":run_tests()# ─── PHASE 5 STEP 5.5: DAG CYCLE DETECTION & EXECUTION PREFLIGHT ─────────────def test_step5_5_ordinary_and_disconnected_cycles_dag001():"""Step 5.5: Tests ordinary procedural cycles and disconnected cycles.Verifies DAG-001 is emitted and can_execute is False."""# 1. Ordinary 3-node procedural cycle: math.add -> math.multiply -> math.sqrt -> math.addcycle_graph = {"name": "Procedural Cycle Graph","nodes": [{"id": "n1", "node_type": "math.add", "data": {"label": "Add"}},{"id": "n2", "node_type": "math.multiply", "data": {"label": "Multiply"}},{"id": "n3", "node_type": "math.sqrt", "data": {"label": "Sqrt"}},],"edges": [{"id": "e1", "source": "n1", "source_handle": "result", "target": "n2", "target_handle": "a"},{"id": "e2", "source": "n2", "source_handle": "result", "target": "n3", "target_handle": "x"},{"id": "e3", "source": "n3", "source_handle": "result", "target": "n1", "target_handle": "a"},],}res = validate_workflow_protocol_logic(cycle_graph)assert not res["valid"], "Procedural cycle must be invalid"assert not res["can_execute"], "Procedural cycle must block execution"dag_diags = [d for d in res["diagnostics"] if d.get("code") == "DAG-001"]assert len(dag_diags) > 0, "Expected DAG-001 diagnostic"assert "Dependency Cycle Detected" in dag_diags[0]["message"]# 2. Disconnected cycle: valid linear nodes plus isolated circular componentdisconnected_graph = {"name": "Disconnected Cycle Graph","nodes": [{"id": "v1", "node_type": "core.variable", "data": {"label": "Var", "customData": {"var_name": "val", "literal_value": "10"}}},{"id": "p1", "node_type": "core.print", "data": {"label": "Print"}},{"id": "c1", "node_type": "math.add", "data": {"label": "CycleA"}},{"id": "c2", "node_type": "math.add", "data": {"label": "CycleB"}},],"edges": [{"id": "e_valid", "source": "v1", "source_handle": "val", "target": "p1", "target_handle": "value"},{"id": "e_c1", "source": "c1", "source_handle": "result", "target": "c2", "target_handle": "a"},{"id": "e_c2", "source": "c2", "source_handle": "result", "target": "c1", "target_handle": "a"},],}res_disc = validate_workflow_protocol_logic(disconnected_graph)assert not res_disc["valid"], "Disconnected cycle must invalidate workflow"assert not res_disc["can_execute"], "Disconnected cycle must block execution"dag_disc_diags = [d for d in res_disc["diagnostics"] if d.get("code") == "DAG-001"]assert len(dag_disc_diags) > 0, "Expected DAG-001 for disconnected cycle"def test_step5_5_approved_agent_cycles_permitted():"""Step 5.5: Tests that approved LangGraph ReAct reasoning cycles are permittedwhen structurally contained within approved agent constructs."""agent_graph = {"name": "Approved ReAct Agent Graph","nodes": [{"id": "prompt_in","node_type": "io.input","data": {"label": "Prompt Input","customData": {"value": "Calculate 2+2"},},},{"id": "agent_llm","node_type": "alli.agent.llm","data": {"label": "LLM Reasoner","category": "Agent Logic","customData": {"model": "gpt-4o"},},},{"id": "tool_calc","node_type": "alli.agent.tool","data": {"label": "Custom Tool","category": "Agent Tools","customData": {"tool_name": "calculator"},"spec": {"inputs": [{"id": "query", "name": "query", "type": "str", "required": False}],"outputs": [{"id": "result", "name": "result", "type": "str"}],},},},],"edges": [{"id": "e_in", "source": "prompt_in", "source_handle": "output", "target": "agent_llm", "target_handle": "prompt"},{"id": "e_fwd", "source": "agent_llm", "source_handle": "response", "target": "tool_calc", "target_handle": "query"},{"id": "e_back", "source": "tool_calc", "source_handle": "result", "target": "agent_llm", "target_handle": "messages"},],}res = validate_workflow_protocol_logic(agent_graph)dag_diags = [d for d in res["diagnostics"] if d.get("code") in ("DAG-001", "CTRL-001")]assert len(dag_diags) == 0, f"Approved agent reasoning cycle must not trigger DAG-001 or CTRL-001: {dag_diags}"# Verify execution planner handles approved agent loop deterministicallyplan = build_execution_plan(agent_graph)assert plan["valid"] is True, f"Execution plan must be valid: {plan.get('validation_errors')}"assert plan["can_execute"] is True, "can_execute must be True for approved agent graph"assert len(plan["execution_order"]) == 3, "Execution planner must order all nodes"assert plan["execution_order"] == ["prompt_in", "agent_llm", "tool_calc"]def test_step5_5_malformed_agent_cycles_rejected():"""Step 5.5: Tests that cycles involving agent nodes and ordinary procedural nodesare NOT permitted and must be rejected with DAG-001."""malformed_agent_graph = {"name": "Malformed Agent Cycle Graph","nodes": [{"id": "agent_llm","node_type": "alli.agent.llm","data": {"label": "LLM Reasoner", "category": "Agent Logic"},},{"id": "math_add","node_type": "math.add","data": {"label": "Add", "category": "Math"},},],"edges": [{"id": "e1", "source": "agent_llm", "source_handle": "response", "target": "math_add", "target_handle": "a"},{"id": "e2", "source": "math_add", "source_handle": "result", "target": "agent_llm", "target_handle": "messages"},],}res = validate_workflow_protocol_logic(malformed_agent_graph)assert not res["valid"], "Malformed agent cycle with procedural node must be invalid"assert not res["can_execute"], "Malformed agent cycle must block execution"dag_diags = [d for d in res["diagnostics"] if d.get("code") == "DAG-001"]assert len(dag_diags) > 0, "Expected DAG-001 for malformed agent cycle with math node"def test_step5_5_loop_feedback_ctrl001():"""Step 5.5: Tests that feedback wires targeting loop headers emit the canonical CTRL-001 diagnostic."""# 1. Wire from downstream node back to for_loop headerloop_feedback_graph = {"name": "Invalid Loop Feedback Graph","nodes": [{"id": "loop_1","node_type": "control.for_loop","data": {"label": "ForLoop","customData": {"range_count": 5, "iterator_var": "item"},},},{"id": "print_1","node_type": "core.print","data": {"label": "Print"},},],"edges": [{"id": "e_fwd", "source": "loop_1", "source_handle": "item", "target": "print_1", "target_handle": "value"},{"id": "e_back", "source": "print_1", "source_handle": "out", "target": "loop_1", "target_handle": "iterable"},],}res = validate_workflow_protocol_logic(loop_feedback_graph)assert not res["valid"], "Loop feedback wire must invalidate graph"assert not res["can_execute"], "Loop feedback wire must block execution"ctrl_diags = [d for d in res["diagnostics"] if d.get("code") == "CTRL-001"]assert len(ctrl_diags) > 0, "Expected CTRL-001 diagnostic for loop header feedback"assert "Invalid Loop Feedback" in ctrl_diags[0]["message"]assert ctrl_diags[0]["node_id"] == "loop_1"# 2. Direct connection check: connecting edge back to loop headeredge_feedback = {"source": "print_1", "target": "loop_1", "from_node": "print_1", "to_node": "loop_1"}nodes_map = {n["id"]: n for n in loop_feedback_graph["nodes"]}conn_res = validate_connection_logic(connection=edge_feedback,nodes_map=nodes_map,edges=[{"source": "loop_1", "target": "print_1", "from_node": "loop_1", "to_node": "print_1"}],)assert not conn_res["valid"], "Connection logic must reject loop feedback"assert conn_res["code"] == "CTRL-001", f"Expected CTRL-001, got {conn_res['code']}"# 3. Direct self-loop on loop headerself_loop = {"source": "loop_1", "target": "loop_1", "from_node": "loop_1", "to_node": "loop_1"}self_res = validate_connection_logic(connection=self_loop, nodes_map=nodes_map)assert not self_res["valid"], "Self-loop on loop header must be rejected"assert self_res["code"] == "CTRL-001", f"Expected CTRL-001 for loop header self-connection, got {self_res['code']}"def test_step5_5_execution_preflight_all_entrypoints():"""Step 5.5: Verifies that pre-flight validation blocks execution across all entrypoints:1. build_execution_plan2. execute_workflow_graph3. execute_workflow_step"""invalid_graph = {"name": "Invalid Cycle Workflow","nodes": [{"id": "a", "node_type": "math.add", "data": {"label": "A"}},{"id": "b", "node_type": "math.add", "data": {"label": "B"}},],"edges": [{"id": "e1", "source": "a", "source_handle": "result", "target": "b", "target_handle": "a"},{"id": "e2", "source": "b", "source_handle": "result", "target": "a", "target_handle": "a"},],}# 1. build_execution_plan pre-flight gateplan = build_execution_plan(invalid_graph)assert plan["valid"] is False, "Execution plan must be invalid"assert plan["can_execute"] is False, "can_execute must be False in execution plan"assert plan["status"] == "invalid"assert len(plan["execution_order"]) == 0, "No nodes may be scheduled on invalid graph"# 2. execute_workflow_graph pre-flight gateexec_res = execute_workflow_graph(invalid_graph)assert exec_res["success"] is False, "Workflow execution must fail immediately"assert exec_res["exit_code"] == 1assert "Workflow validation failed" in exec_res["error"]assert len(exec_res["final_outputs"]) == 0, "No side effects or outputs permitted"# 3. execute_workflow_step pre-flight gatestep_res = execute_workflow_step(invalid_graph, target_node_id="a")assert step_res["success"] is False, "Workflow step must fail immediately"assert step_res["exit_code"] == 1assert "Workflow step execution blocked" in step_res["logs"][0]
lambdas/validate_handler.py+159-43
language_core/execution_planner.py+16-6
language_core/topology.py+16-2
language_core/workflow_executor.py+29
tests/test_workflow_validation.py+250-1