diff --git a/python/packages/declarative/agent_framework_declarative/_workflows/_state.py b/python/packages/declarative/agent_framework_declarative/_workflows/_state.py index c2a18a0c7c4..3829293e1a7 100644 --- a/python/packages/declarative/agent_framework_declarative/_workflows/_state.py +++ b/python/packages/declarative/agent_framework_declarative/_workflows/_state.py @@ -31,6 +31,70 @@ logger = logging.getLogger("agent_framework.declarative") +def _find_top_level_operator(formula: str, operators: tuple[str, ...]) -> tuple[int, str] | None: + """Return the last occurrence of any `operators` outside string literals and brackets. + + Picking the last occurrence makes a chain of same-precedence operators left-associative. + Quoted text (with doubled-quote escapes) and anything inside `()`, `[]` or `{}` is + skipped so an operator spelled inside a literal or a nested call is not split on. + + Returns: + The `(index, operator)` pair, or `None` when no operator is at the top level. + """ + depth = 0 + quote: str | None = None + found: tuple[int, str] | None = None + index = 0 + while index < len(formula): + char = formula[index] + if quote is not None: + if char == quote: + if index + 1 < len(formula) and formula[index + 1] == quote: + index += 2 + continue + quote = None + index += 1 + continue + if char in ('"', "'"): + quote = char + elif char in "([{": + depth += 1 + elif char in ")]}": + depth = max(0, depth - 1) + elif depth == 0: + for operator in operators: + if formula.startswith(operator, index): + found = (index, operator) + break + index += 1 + return found + + +def _matching_paren_index(formula: str) -> int: + """Return the index of the `)` matching the leading `(`, or -1 when it never closes.""" + depth = 0 + quote: str | None = None + index = 0 + while index < len(formula): + char = formula[index] + if quote is not None: + if char == quote: + if index + 1 < len(formula) and formula[index + 1] == quote: + index += 2 + continue + quote = None + elif char in ('"', "'"): + quote = char + elif char == "(": + depth += 1 + elif char == ")": + depth -= 1 + if depth == 0: + return index + index += 1 + return -1 + + class WorkflowState: """Manages standalone workflow state and expression evaluation. @@ -445,13 +509,7 @@ def _eval_simple(self, formula: str) -> Any: formula = formula.strip() - # Handle negation prefix - if formula.startswith("!"): - inner = formula[1:].strip() - result = self._eval_simple(inner) - return not bool(result) - - # Handle Not() function + # Handle Not() function (a whole-call formula, so no operator precedence is involved) not_args = whole_call_args(formula, "Not") if not_args is not None: result = self._eval_simple(not_args.strip()) @@ -470,95 +528,79 @@ def _eval_simple(self, formula: str) -> Any: logger.warning(f"Function {func_name} failed: {e}") return formula + # Binary operators, lowest to highest precedence. Each level splits on the *last* + # top-level occurrence so chains are left-associative (`10 - 2 - 3` is `(10 - 2) - 3`), + # and operators inside string literals or brackets are never treated as operators. + # Handle Or operator (lowest precedence) + found = _find_top_level_operator(formula, (" || ", " Or ")) + if found is not None: + index, op = found + left = self._eval_simple(formula[:index]) + right = self._eval_simple(formula[index + len(op) :]) + return bool(left) or bool(right) + # Handle And operator - if " And " in formula: - parts = formula.split(" And ", 1) - left = self._eval_simple(parts[0]) - right = self._eval_simple(parts[1]) + found = _find_top_level_operator(formula, (" And ",)) + if found is not None: + index, op = found + left = self._eval_simple(formula[:index]) + right = self._eval_simple(formula[index + len(op) :]) return bool(left) and bool(right) - # Handle Or operator (||) - if " || " in formula or " Or " in formula: - parts = formula.split(" || ", 1) if " || " in formula else formula.split(" Or ", 1) - left = self._eval_simple(parts[0]) - right = self._eval_simple(parts[1]) - return bool(left) or bool(right) - # Handle comparison operators - for op in [" < ", " > ", " <= ", " >= ", " <> ", " = "]: - if op in formula: - parts = formula.split(op, 1) - left = self._eval_simple(parts[0].strip()) - right = self._eval_simple(parts[1].strip()) - if op == " < ": - return left < right - if op == " > ": - return left > right - if op == " <= ": - return left <= right - if op == " >= ": - return left >= right - if op == " <> ": - return left != right - if op == " = ": - return left == right - - # Handle arithmetic operators - if " + " in formula: - parts = formula.split(" + ", 1) - left = self._eval_simple(parts[0].strip()) - right = self._eval_simple(parts[1].strip()) - # Treat None as 0 for arithmetic (PowerFx behavior) - if left is None: - left = 0 - if right is None: - right = 0 - # Try numeric addition first, fall back to string concat - try: - return float(left) + float(right) - except (ValueError, TypeError): - return str(left) + str(right) - - if " - " in formula: - parts = formula.split(" - ", 1) - left = self._eval_simple(parts[0].strip()) - right = self._eval_simple(parts[1].strip()) + found = _find_top_level_operator(formula, (" < ", " > ", " <= ", " >= ", " <> ", " = ")) + if found is not None: + index, op = found + left = self._eval_simple(formula[:index].strip()) + right = self._eval_simple(formula[index + len(op) :].strip()) + if op == " < ": + return left < right + if op == " > ": + return left > right + if op == " <= ": + return left <= right + if op == " >= ": + return left >= right + if op == " <> ": + return left != right + return left == right + + # Handle addition and subtraction (same precedence, left-associative) + found = _find_top_level_operator(formula, (" + ", " - ")) + if found is not None: + index, op = found + left = self._eval_simple(formula[:index].strip()) + right = self._eval_simple(formula[index + len(op) :].strip()) # Treat None as 0 for arithmetic (PowerFx behavior) if left is None: left = 0 if right is None: right = 0 + if op == " + ": + # Try numeric addition first, fall back to string concat + try: + return float(left) + float(right) + except (ValueError, TypeError): + return str(left) + str(right) try: return float(left) - float(right) except (ValueError, TypeError): return formula - # Handle multiplication - if " * " in formula: - parts = formula.split(" * ", 1) - left = self._eval_simple(parts[0].strip()) - right = self._eval_simple(parts[1].strip()) - # Treat None as 0 for arithmetic (PowerFx behavior) - if left is None: - left = 0 - if right is None: - right = 0 - try: - return float(left) * float(right) - except (ValueError, TypeError): - return formula - - # Handle division with div-by-zero protection - if " / " in formula: - parts = formula.split(" / ", 1) - left = self._eval_simple(parts[0].strip()) - right = self._eval_simple(parts[1].strip()) + # Handle multiplication and division (same precedence, left-associative) + found = _find_top_level_operator(formula, (" * ", " / ")) + if found is not None: + index, op = found + left = self._eval_simple(formula[:index].strip()) + right = self._eval_simple(formula[index + len(op) :].strip()) # Treat None as 0 for arithmetic (PowerFx behavior) if left is None: left = 0 if right is None: right = 0 try: + if op == " * ": + return float(left) * float(right) right_float = float(right) if right_float == 0: # PowerFx returns Error for division by zero; we return None (Blank) @@ -568,6 +610,16 @@ def _eval_simple(self, formula: str) -> Any: except (ValueError, TypeError): return formula + # Handle negation prefix. It binds tighter than comparison and arithmetic operators. + if formula.startswith("!"): + inner = formula[1:].strip() + result = self._eval_simple(inner) + return not bool(result) + + # Handle a fully parenthesized sub-expression + if formula.startswith("(") and _matching_paren_index(formula) == len(formula) - 1: + return self._eval_simple(formula[1:-1]) + # Handle string literals if (formula.startswith('"') and formula.endswith('"')) or (formula.startswith("'") and formula.endswith("'")): return formula[1:-1] diff --git a/python/packages/declarative/tests/test_workflow_state.py b/python/packages/declarative/tests/test_workflow_state.py index 4cc8859eafc..f4138a1cb49 100644 --- a/python/packages/declarative/tests/test_workflow_state.py +++ b/python/packages/declarative/tests/test_workflow_state.py @@ -6,7 +6,7 @@ import pytest -from agent_framework_declarative._workflows import _state as state_module +import agent_framework_declarative._workflows._state as state_module from agent_framework_declarative._workflows._state import WorkflowState @@ -750,3 +750,134 @@ def test_each_instance_generates_unique_id(self): state1 = WorkflowState() state2 = WorkflowState() assert state1.get("System.ConversationId") != state2.get("System.ConversationId") + + +class TestWorkflowStateEvalSimpleOperatorPrecedence: + """The no-PowerFx fallback evaluator must honour operator precedence and associativity.""" + + @pytest.fixture + def state(self, monkeypatch: pytest.MonkeyPatch) -> WorkflowState: + # Force the pure-Python fallback regardless of whether PowerFx is installed. + import agent_framework_declarative._workflows._state as state_module + + monkeypatch.setattr(state_module, "_powerfx_engine", None) + workflow_state = WorkflowState() + for name, value in {"a": True, "b": False, "c": False, "x": 10, "text": "a And b"}.items(): + workflow_state.set(f"Local.{name}", value) + return workflow_state + + @pytest.mark.parametrize( + ("expression", "expected"), + [ + # And binds tighter than Or, whichever side the And sits on. + ("=Local.a Or Local.b And Local.c", True), + ("=Local.b And Local.c Or Local.a", True), + ("=Local.a || Local.b And Local.c", True), + ("=Local.x = 10 Or Local.x = 11 And Local.b", True), + # Parentheses override precedence. + ("=(Local.a Or Local.b) And Local.c", False), + # Negation binds tighter than And. + ("=!Local.b And Local.a", True), + ("=!Local.a And Local.a", False), + ], + ) + def test_logical_operator_precedence(self, state: WorkflowState, expression: str, expected: bool) -> None: + assert state.eval(expression) is expected + + @pytest.mark.parametrize( + ("expression", "expected"), + [ + ("=10 - 2 - 3", 5.0), + ("=Local.x - 2 - 3", 5.0), + ("=100 / 10 / 2", 5.0), + ("=10 - 2 + 3", 11.0), + ("=10 - 4 / 2", 8.0), + ("=2 + 3 * 4", 14.0), + ("=2 * 3 + 4", 10.0), + ], + ) + def test_arithmetic_is_left_associative(self, state: WorkflowState, expression: str, expected: float) -> None: + assert state.eval(expression) == expected + + def test_operator_inside_string_literal_is_not_split(self, state: WorkflowState) -> None: + assert state.eval('=Local.text = "a And b"') is True + assert state.eval('="a - b"') == "a - b" + assert state.eval('="x" = "x Or y"') is False + + +class TestWorkflowStateEvalSimpleNegationPrecedence: + """Unary negation must bind tighter than comparison and arithmetic operators.""" + + @pytest.fixture + def state(self, monkeypatch: pytest.MonkeyPatch) -> WorkflowState: + # Force the pure-Python fallback regardless of whether PowerFx is installed. + import agent_framework_declarative._workflows._state as state_module + + monkeypatch.setattr(state_module, "_powerfx_engine", None) + workflow_state = WorkflowState() + for name, value in {"x": 5, "y": 10, "a": True, "b": False}.items(): + workflow_state.set(f"Local.{name}", value) + return workflow_state + + def test_negation_with_comparison(self, state: WorkflowState) -> None: + # !Local.x = 1 should evaluate as (!Local.x) = 1, not !(Local.x = 1) + # With Local.x = 5: (!5) = 1 = False = 1 = False + assert state.eval("=!Local.x = 1") is False + # With Local.x = 5: (!5) = 0 = False = 0 = True (False == 0 in Python) + assert state.eval("=!Local.x = 0") is True + + def test_negation_with_multiplication(self, state: WorkflowState) -> None: + # !Local.x * 2 should evaluate as (!Local.x) * 2 + # With Local.x = 5: (!5) * 2 = False * 2 = 0 + assert state.eval("=!Local.x * 2") == 0.0 + + def test_negation_with_division(self, state: WorkflowState) -> None: + # !Local.x / 2 should evaluate as (!Local.x) / 2 + # With Local.x = 5: (!5) / 2 = False / 2 = 0 + assert state.eval("=!Local.x / 2") == 0.0 + + def test_negation_with_addition(self, state: WorkflowState) -> None: + # !Local.x + 2 should evaluate as (!Local.x) + 2 + # With Local.x = 5: (!5) + 2 = False + 2 = 2 + assert state.eval("=!Local.x + 2") == 2.0 + + def test_negation_with_subtraction(self, state: WorkflowState) -> None: + # !Local.x - 2 should evaluate as (!Local.x) - 2 + # With Local.x = 5: (!5) - 2 = False - 2 = -2 + assert state.eval("=!Local.x - 2") == -2.0 + + def test_negation_with_logical_and(self, state: WorkflowState) -> None: + # !Local.a And Local.b should evaluate as (!Local.a) And Local.b + # With Local.a = True, Local.b = False: (!True) And False = False And False = False + assert state.eval("=!Local.a And Local.b") is False + # With Local.a = False, Local.b = True: (!False) And True = True And True = True + assert state.eval("=!Local.b And Local.a") is True + + def test_negation_with_logical_or(self, state: WorkflowState) -> None: + # !Local.a Or Local.b should evaluate as (!Local.a) Or Local.b + # With Local.a = True, Local.b = False: (!True) Or False = False Or False = False + assert state.eval("=!Local.a Or Local.b") is False + # With Local.a = False, Local.b = True: (!False) Or True = True Or True = True + assert state.eval("=!Local.b Or Local.a") is True + + def test_combined_negation_and_logical(self, state: WorkflowState) -> None: + # !Local.a And !Local.b should evaluate as (!Local.a) And (!Local.b) + # With Local.a = True, Local.b = False: (!True) And (!False) = False And True = False + assert state.eval("=!Local.a And !Local.b") is False + # With Local.a = False, Local.b = False: (!False) And (!False) = True And True = True + assert state.eval("=!Local.b And !Local.b") is True + + def test_parenthesized_negation_with_comparison(self, state: WorkflowState) -> None: + # !(Local.x = 1) should still work correctly + # With Local.x = 5: !(5 = 1) = !False = True + assert state.eval("=!(Local.x = 1)") is True + + def test_parenthesized_negation_with_arithmetic(self, state: WorkflowState) -> None: + # !(Local.x + 2) should still work correctly + # With Local.x = 5: !(5 + 2) = !7 = False + assert state.eval("=!(Local.x + 2)") is False + + def test_parenthesized_negation_with_logical(self, state: WorkflowState) -> None: + # !(Local.a And Local.b) should still work correctly + # With Local.a = True, Local.b = False: !(True And False) = !False = True + assert state.eval("=!(Local.a And Local.b)") is True