""" ALLI Workflow Executor: Inline Core Primitive, Loop, Math, Compare & Print Node Handlers. """ import math import time from typing import Any, Dict, List from language_core.executor.state_and_errors import WorkflowExecutionError def _execute_loop_node( ntype: str, inputs: Dict[str, Any], params: Dict[str, Any], settings: Dict[str, Any], timeout_seconds: float = 5.0, ) -> Dict[str, Any]: """Enforces bounded iteration limits and timeout safety contracts for loop constructs.""" max_iterations = min(max(1, int(settings.get("max_iterations") or params.get("max_iterations") or 1000)), 10000) timeout = float(settings.get("timeout_seconds") or timeout_seconds or 5.0) start_time = time.perf_counter() if "for" in ntype: raw_iter = inputs.get("iterable") if raw_iter is None: raw_iter = params.get("iterable") if raw_iter is None: raw_iter = list(range(int(params.get("range_count") or params.get("count") or 5))) elif isinstance(raw_iter, (list, tuple, set)): raw_iter = list(raw_iter) elif isinstance(raw_iter, dict): raw_iter = list(raw_iter.items()) elif isinstance(raw_iter, str): raw_iter = list(raw_iter) elif isinstance(raw_iter, int): raw_iter = list(range(raw_iter)) else: try: raw_iter = list(raw_iter) except Exception: raw_iter = [raw_iter] if len(raw_iter) > max_iterations: raise WorkflowExecutionError( node_id="", node_type=ntype, message=f"[ERR-LOOP-OVERFLOW] Loop iteration count {len(raw_iter)} exceeded bounded safety limit of {max_iterations} iterations.", ) if (time.perf_counter() - start_time) > timeout: raise WorkflowExecutionError(node_id="", node_type=ntype, message=f"[ERR-LOOP-TIMEOUT] Loop execution exceeded timeout of {timeout}s.") return { "items": raw_iter, "item": raw_iter[0] if raw_iter else None, "iteration_count": len(raw_iter), "completed": True, "out": raw_iter, "result": raw_iter, "body": raw_iter[0] if raw_iter else None, "done": raw_iter, } if "while" in ntype: initial_val = float(inputs.get("initial_value") or params.get("initial_value", 0)) step_val = float(inputs.get("step") or params.get("step") or params.get("step_value", 1)) threshold = float(params.get("target_threshold") or params.get("threshold", 5)) max_loop_steps = min(int(settings.get("max_iterations") or params.get("max_iterations", 100)), 10000) curr, step_count = initial_val, 0 while step_count < max_loop_steps: if (time.perf_counter() - start_time) > timeout: raise WorkflowExecutionError(node_id="", node_type=ntype, message=f"[ERR-LOOP-TIMEOUT] While loop exceeded timeout of {timeout}s.") should_continue = (curr < threshold) if step_val > 0 else ((curr > threshold) if step_val < 0 else False) if not should_continue: break curr += step_val step_count += 1 if step_count >= max_loop_steps and (curr < threshold if step_val > 0 else curr > threshold): raise WorkflowExecutionError( node_id="", node_type=ntype, message=f"[ERR-LOOP-OVERFLOW] While loop exceeded maximum bounded iterations limit of {max_loop_steps}.", ) final_val = int(curr) if curr.is_integer() else curr return {"completed": True, "step_count": step_count, "iteration_count": step_count, "result": final_val, "out": final_val, "final_value": final_val, "val": final_val} return {"completed": True, "items": []} def _execute_constant_node(node_type: str, inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: """Handler for literal constant nodes (int, float, str, bool, list, dict).""" raw_val = params.get("literal_value") if params.get("literal_value") is not None else params.get("default_value", 0) t = f"{node_type.lower()} {str(params.get('const_type') or '').lower()}" if "int" in t or "integer" in t: try: val: Any = int(raw_val) except (ValueError, TypeError): val = int(float(raw_val)) elif "float" in t or "number" in t: val = float(raw_val) elif "str" in t or "string" in t or "text" in t: val = str(raw_val) elif "bool" in t or "boolean" in t: val = raw_val.lower() in ("true", "1", "yes") if isinstance(raw_val, str) else bool(raw_val) elif "list" in t: val = raw_val if isinstance(raw_val, list) else [raw_val] elif "dict" in t: val = raw_val if isinstance(raw_val, dict) else {} elif isinstance(raw_val, str): if raw_val.lstrip("-").isdigit(): val = int(raw_val) elif "." in raw_val and raw_val.replace(".", "", 1).replace("-", "", 1).isdigit(): val = float(raw_val) else: val = raw_val else: val = raw_val return {"val": val, "result": val, "out": val, "value": val} def _execute_variable_node(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: """Handler for variable assignment and pass-through.""" val = inputs.get("in_val") for k in ("in", "val", "value"): if val is None: val = inputs.get(k) if val is None: val = params.get("literal_value", 0) var_name = params.get("var_name", "variable") var_type = str(params.get("var_type") or params.get("cast_type") or "any").strip().lower() if var_type and var_type != "any": from language_core.executor.wave1_handlers import strict_cast_value val = strict_cast_value(val, var_type, allow_any=True) return {"out_val": val, "val": val, "result": val, "out": val, "value": val, "name": var_name} def _execute_math_sqrt_node(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: """Handler for math.sqrt with domain error safety.""" raw_x = inputs.get("x") if raw_x is None: raw_x = params.get("x") if raw_x is None: raw_x = inputs.get("val") if raw_x is None: raise ValueError("Missing required input 'x' for square root.") x = float(raw_x) if x < 0: raise ValueError(f"math domain error: Cannot compute square root of negative number ({x})") res = math.sqrt(x) if params.get("rounding", "none") == "round": res = round(res, int(params.get("precision", 2))) return {"result": res, "val": res, "out": res} def _execute_binary_op_node(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: """Handler for binary arithmetic operations.""" a = inputs["a"] if inputs.get("a") is not None else params.get("a", 0) b = inputs["b"] if inputs.get("b") is not None else params.get("b", 0) op = params.get("operator", "+") if op == "+": res = a + b elif op == "-": res = a - b elif op == "*": res = a * b elif op == "/": if b == 0: raise ZeroDivisionError("division by zero in binary operation ('/')") res = a / b elif op == "//": if b == 0: raise ZeroDivisionError("integer division by zero in binary operation ('//')") res = a // b elif op == "%": if b == 0: raise ZeroDivisionError("modulo by zero in binary operation ('%')") res = a % b elif op == "**": res = a ** b else: raise ValueError(f"Unsupported binary operator '{op}'") return {"result": res, "val": res, "out": res} def _execute_print_node(inputs: Dict[str, Any], params: Dict[str, Any], stdout_collector: List[str]) -> Dict[str, Any]: """Handler for terminal output / print node.""" val = inputs.get("value") for k in ("val", "in", "x"): if val is None: val = inputs.get(k) if val is None: val = params.get("value", "") prefix = params.get("prefix", "") line_out = f"{prefix} {val}" if prefix and not prefix.endswith(" ") else f"{prefix}{val}" stdout_collector.append(line_out) return {"out": val, "val": val, "result": val, "value": val, "printed_string": line_out} def _execute_compare_node(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: """Handler for comparison operators.""" a = inputs["a"] if inputs.get("a") is not None else params.get("a", 0) b = inputs["b"] if inputs.get("b") is not None else params.get("b", 0) try: a, b = float(a), float(b) except (ValueError, TypeError): pass op = params.get("operator", "==") ops = {"==": a == b, "!=": a != b, "<": a < b, "<=": a <= b, ">": a > b, ">=": a >= b} if op not in ops: raise ValueError(f"Unsupported comparison operator '{op}'") return {"result": ops[op], "val": ops[op], "out": ops[op]} def _execute_if_else_node(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: """Handler for conditional branching.""" cond_val = inputs.get("condition") if inputs.get("condition") is not None else params.get("condition", True) is_true = bool(cond_val) true_val = inputs.get("then_val") if inputs.get("then_val") is not None else params.get("then_val", params.get("default_then", True)) false_val = inputs.get("else_val") if inputs.get("else_val") is not None else params.get("else_val", params.get("default_else", False)) selected = true_val if is_true else false_val return { "result": selected, "val": selected, "out": selected, "branch_taken": "then" if is_true else "else", "then_val": true_val, "else_val": false_val, "then": true_val, "else": false_val, }