From feb936f62337713ebbeeac640521996b037b7b51 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:48:52 +0530 Subject: [PATCH 1/4] Support exponent numbers, chained list indexing, and reject invalid leading-index paths Closes #5073. After the Lark grammar landed in #5171, three expression-evaluator gaps from #5073 remained on main: - Integer-mantissa exponent literals (such as 1e3, 1E3, -2e+3, 5e-2) were rejected by the NUMBER terminal and _BuildAst.number, even though decimal exponents like 1.5e3 were accepted. - _coerce_number only tried float() when a string contained ".", so exponent-form numeric strings like "1e3" silently failed to coerce in ordering and equality comparisons (evaluating "1e3" > 100 to False while WorkflowEngine._coerce_input coerces "1e3" to 1000). Coercing via int() first and finite float() for digit-bearing strings aligns expression comparisons with workflow input coercion while keeping non-finite strings ("inf", "nan", overflow) as plain strings. - _INDEXED_SEGMENT matched only one [index] suffix, rejecting chained list indexing such as steps.plan.output.matrix[0][1] and item[0][1]. Widening _INDEXED_SEGMENT and walking each bracketed index in _resolve_dot_path propagates automatically to the Lark PATH terminal and condition diagnostics. - The first-segment PATH regex did not apply its leading-digit/hyphen and reserved-word guards to the indexed branch, allowing 1[0], and[0], and not[0] to silently resolve as missing paths (None) instead of raising a syntax error (or, for not[0], negating the list literal [0]). Assisted-by: Antigravity (model: Gemini 4 Neon (XHigh), autonomous) --- .../workflows/expressions/engine.py | 23 ++-- .../workflows/expressions/namespace.py | 28 ++-- .../workflows/expressions/operators.py | 14 +- tests/test_workflows.py | 124 ++++++++++++++++-- tests/unit/test_condition_expression_block.py | 21 +-- 5 files changed, 170 insertions(+), 40 deletions(-) diff --git a/src/specify_cli/workflows/expressions/engine.py b/src/specify_cli/workflows/expressions/engine.py index 88ae8c3760..375552479c 100644 --- a/src/specify_cli/workflows/expressions/engine.py +++ b/src/specify_cli/workflows/expressions/engine.py @@ -86,13 +86,14 @@ def _path_terminal_pattern(plain_pattern: str, indexed_pattern: str) -> str: """The ``PATH`` regex, built from the namespace's own segment definitions. ``_PLAIN_SEGMENT`` (``^[\\w-]+$``) and ``_INDEXED_SEGMENT`` - (``^([\\w-]+)\\[(-?\\d+)\\]$``) are stripped of their anchors and combined: - every segment is a plain or an indexed one. The *first* segment excludes a - leading digit (so ``123`` keeps lexing as a number) and the reserved word - operators (``and``, ``or``, ``not``, ``in``, so they never lex as a path - where an operand is expected); that is the only difference from the - namespace pattern, and it is why this derivation reads the pattern instead - of re-describing the shape. + (``^([\\w-]+)((?:\\[-?\\d+\\])+)$``) are stripped of their anchors and + combined: every segment is a plain or an indexed one. The *first* segment + excludes a leading digit or hyphen (so ``123`` keeps lexing as a number + and ``1[0]`` does not silently resolve as a path) and the reserved word + operators (``and``, ``or``, ``not``, ``in``, so neither ``and`` nor + ``and[0]`` ever lexes as a path where an operand is expected); that is the + only difference from the namespace pattern, and it is why this derivation + reads the pattern instead of re-describing the shape. ``_INDEXED_SEGMENT`` is read through ``namespace`` at call time, so the parser cache below rebuilds when it is widened -- the drift guard @@ -101,7 +102,7 @@ def _path_terminal_pattern(plain_pattern: str, indexed_pattern: str) -> str: plain = plain_pattern.strip("^$") indexed = indexed_pattern.strip("^$") later = f"(?:{indexed}|{plain})" - first = f"(?:{indexed}|(?!(?:and|or|not|in)(?![\\w-]))[^\\W\\d]{plain[:-1]}*)" + first = f"(?!(?:and|or|not|in)(?![\\w-]))(?=[^\\W\\d])(?:{indexed}|{plain})" return f"{first}(?:\\.{later})*" @@ -157,7 +158,7 @@ def _grammar(path_pattern: str) -> str: FILTER_NAME: /[A-Za-z_][\w-]*/ PATH: /""" + path_pattern + r"""/ STRING: /'[^']*'/ | /"[^"]*"/ -NUMBER: /[+-]?(?:(?:\d(?:_?\d)*\.(?:\d(?:_?\d)*)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|\d(?:_?\d)*)/ +NUMBER: /[+-]?(?:(?:\d(?:_?\d)*\.(?:\d(?:_?\d)*)?|\.\d(?:_?\d)*)|\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?/ %import common.WS %ignore WS """ @@ -201,7 +202,9 @@ def string(self, token: Token) -> tuple[str, str]: def number(self, token: Token) -> tuple[str, Any]: text = str(token) - return ("lit", float(text) if "." in text else int(text)) + if "." in text or "e" in text or "E" in text: + return ("lit", float(text)) + return ("lit", int(text)) def path(self, token: Token) -> tuple[str, str]: return ("path", str(token)) diff --git a/src/specify_cli/workflows/expressions/namespace.py b/src/specify_cli/workflows/expressions/namespace.py index 596c45fb39..6f56e7e86b 100644 --- a/src/specify_cli/workflows/expressions/namespace.py +++ b/src/specify_cli/workflows/expressions/namespace.py @@ -16,7 +16,8 @@ # against it, and the condition gate below reuses it rather than describing the # same shape a second time, so widening what indexing accepts cannot leave the # evaluator and the gate disagreeing. -_INDEXED_SEGMENT = re.compile(r"^([\w-]+)\[(-?\d+)\]$") +_INDEXED_SEGMENT = re.compile(r"^([\w-]+)((?:\[-?\d+\])+)$") +_INDEX_BRACKET = re.compile(r"\[([^\]]+)\]") _PLAIN_SEGMENT = re.compile(r"^[\w-]+$") @@ -24,24 +25,33 @@ def _resolve_dot_path(obj: Any, path: str) -> Any: """Resolve a dotted path like ``steps.specify.output.file`` against *obj*. - Supports dict key access and list indexing, including the negative form - Python and Jinja2 both accept (e.g., ``task_list[0]``, ``task_list[-1]``). + Supports dict key access and single or chained list indexing, including the + negative form Python and Jinja2 both accept (e.g., ``task_list[0]``, + ``task_list[-1]``, ``matrix[0][1]``). """ parts = path.split(".") current = obj for part in parts: - # Handle list indexing: name[0], name[-1] + # Handle single or chained list indexing: name[0], name[-1], matrix[0][1] idx_match = _INDEXED_SEGMENT.match(part) if idx_match: - key, idx = idx_match.group(1), int(idx_match.group(2)) + key = idx_match.group(1) if isinstance(current, dict): current = current.get(key) else: return None - if isinstance(current, list) and -len(current) <= idx < len(current): - current = current[idx] - else: - return None + raw_indices = idx_match.group(2) + indices = ( + _INDEX_BRACKET.findall(raw_indices) + if raw_indices.startswith("[") + else [raw_indices] + ) + for raw_idx in indices: + idx = int(raw_idx) + if isinstance(current, list) and -len(current) <= idx < len(current): + current = current[idx] + else: + return None elif isinstance(current, dict): current = current.get(part) else: diff --git a/src/specify_cli/workflows/expressions/operators.py b/src/specify_cli/workflows/expressions/operators.py index 3cd2a7585d..6c01abb6cc 100644 --- a/src/specify_cli/workflows/expressions/operators.py +++ b/src/specify_cli/workflows/expressions/operators.py @@ -6,16 +6,24 @@ from __future__ import annotations +import math from typing import Any def _coerce_number(value: Any) -> Any: - """Return *value* as int/float if it is a numeric string, else unchanged.""" + """Return *value* as int/float if it is a finite numeric string, else unchanged.""" if isinstance(value, str): try: - return float(value) if "." in value else int(value) + return int(value) except ValueError: - return value + pass + if any(ch.isdigit() for ch in value): + try: + parsed = float(value) + except ValueError: + return value + if math.isfinite(parsed): + return parsed return value diff --git a/tests/test_workflows.py b/tests/test_workflows.py index 56baaa7b16..d9077e536a 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -1802,36 +1802,140 @@ def test_comparisons_share_one_level_and_group_left_to_right(self): ) is True def test_number_literal_forms(self): - """Every number form the former engine read through ``int()``/``float()``. - - A ``.`` makes a float (exponents need one too, as before); a sign and - digit-group underscores are allowed. - """ + """Integer, decimal, and exponent-form numeric literals evaluate with + matching Python types; signs and digit-group underscores are allowed.""" from specify_cli.workflows.expressions import evaluate_expression from specify_cli.workflows.base import StepContext - ctx = StepContext(inputs={"ratio": 0.7}) + ctx = StepContext(inputs={"ratio": 0.7, "n": 5}) for text, expected in [ ("5", 5), ("-5", -5), ("+5", 5), ("1_000", 1000), ("0.5", 0.5), (".5", 0.5), ("-.5", -0.5), ("5.", 5.0), ("1.5e3", 1500.0), (".5E-1", 0.05), ("1_000.5", 1000.5), + ("1e3", 1000.0), ("1E3", 1000.0), ("+1e3", 1000.0), + ("-2e+3", -2000.0), ("5e-2", 0.05), ("1_000e2", 100000.0), ]: result = evaluate_expression("{{ " + text + " }}", ctx) assert result == expected and type(result) is type(expected), text assert evaluate_expression("{{ inputs.ratio > .5 }}", ctx) is True - assert evaluate_expression("{{ [.5, +1] }}", ctx) == [0.5, 1] + assert evaluate_expression("{{ inputs.n < 1e3 }}", ctx) is True + assert evaluate_expression("{{ [.5, +1, 1e3] }}", ctx) == [0.5, 1, 1000.0] def test_malformed_number_literals_are_refused(self): - """Forms ``int()``/``float()`` refuse (or, for ``1e3``, the former engine - never read as a number) do not lex as one either.""" + """Malformed numeric literals (including incomplete or malformed + exponents) raise ``ValueError`` instead of falling through.""" import pytest from specify_cli.workflows.expressions import evaluate_expression from specify_cli.workflows.base import StepContext - for text in ("1__0", "1_", "1e3", "5..", "."): + for text in ( + "1__0", "1_", "5..", ".", + "1e", "1E", "1e+", "1e-", "1e3e4", "1e3.5", "1e_3", "1_e3", "1e3_", + ): with pytest.raises(ValueError, match="invalid expression"): evaluate_expression("{{ " + text + " }}", StepContext(inputs={})) + def test_exponent_numeric_string_coercion_in_comparisons(self): + """Exponent-form numeric strings coerce in ordering and equality + comparisons just like workflow input coercion, while non-finite and + non-numeric strings stay strings.""" + from specify_cli.workflows.base import StepContext + from specify_cli.workflows.engine import WorkflowEngine + from specify_cli.workflows.expressions import ( + evaluate_condition, + evaluate_expression, + ) + + ctx = StepContext( + inputs={ + "s": "1e3", + "upper": "2E3", + "small": "5e-2", + "neg": "-1e2", + "inf_str": "inf", + "ninf_str": "-inf", + "infinity_str": "Infinity", + "nan_str": "nan", + "overflow_str": "1e400", + "overflow_dot": "1.0e400", + "bad_exp": "1e", + } + ) + assert WorkflowEngine._coerce_input("x", "1e3", {"type": "number"}) == 1000 + assert evaluate_condition("{{ inputs.s > 100 }}", ctx) is True + assert evaluate_condition("{{ inputs.s == 1000 }}", ctx) is True + assert evaluate_condition("{{ inputs.s == 1e3 }}", ctx) is True + assert evaluate_condition("{{ inputs.s == '1000' }}", ctx) is True + assert evaluate_condition("{{ inputs.upper > '900' }}", ctx) is True + assert evaluate_condition("{{ inputs.small < 0.1 }}", ctx) is True + assert evaluate_condition("{{ inputs.neg < 0 }}", ctx) is True + assert evaluate_condition("{{ inputs.s != 1000 }}", ctx) is False + # Non-finite strings and malformed exponents must not coerce to float. + assert evaluate_condition("{{ inputs.inf_str > 100 }}", ctx) is False + assert evaluate_condition("{{ inputs.ninf_str < 0 }}", ctx) is False + assert evaluate_condition("{{ inputs.infinity_str > 0 }}", ctx) is False + assert evaluate_condition("{{ inputs.nan_str == inputs.nan_str }}", ctx) is True + assert evaluate_condition("{{ inputs.overflow_str > 100 }}", ctx) is False + assert evaluate_condition("{{ inputs.overflow_dot > 100 }}", ctx) is False + assert evaluate_condition("{{ inputs.bad_exp > 0 }}", ctx) is False + assert evaluate_expression("{{ inputs.s == 'abc' }}", ctx) is False + + def test_chained_list_indexing_and_unsupported_index_syntax(self): + """Chained list indices resolve across nested lists and dot segments; + missing/non-list indices yield None while invalid index syntax raises.""" + import pytest + from specify_cli.workflows.base import StepContext + from specify_cli.workflows.expressions import ( + evaluate_condition, + evaluate_expression, + ) + + ctx = StepContext( + inputs={"name": "it's", "a": "x", "b": True}, + steps={ + "plan": { + "output": { + "matrix": [["a", "b"], ["c", "d"]], + "cube": [[[{"label": "ok"}]]], + } + } + }, + item=[["first", "second"], ["third", "fourth"]], + ) + assert evaluate_expression("{{ steps.plan.output.matrix[0][1] }}", ctx) == "b" + assert evaluate_expression("{{ steps.plan.output.matrix[-1][-2] }}", ctx) == "c" + assert ( + evaluate_expression("{{ steps.plan.output.cube[0][0][0].label }}", ctx) + == "ok" + ) + assert evaluate_expression("{{ item[0][1] }}", ctx) == "second" + assert evaluate_expression("{{ item[-1][0] }}", ctx) == "third" + # Out-of-range and non-list targets are missing data, not syntax errors. + assert evaluate_expression("{{ steps.plan.output.matrix[0][9] }}", ctx) is None + assert evaluate_expression("{{ steps.plan.output.matrix[9][0] }}", ctx) is None + assert evaluate_expression("{{ steps.plan.output.matrix[0][1][0] }}", ctx) is None + # Malformed index syntax and digit-/keyword-led indexing raise. + for bad in ( + "steps.plan.output.matrix[0][]", + "steps.plan.output.matrix[0][a]", + "steps.plan.output.matrix[0][1.5]", + "1[0]", + "and[0]", + "or[0]", + "in[0]", + r"'it\'s'", + r"inputs.name == 'it\'s'", + ): + with pytest.raises(ValueError, match="invalid expression"): + evaluate_expression("{{ " + bad + " }}", ctx) + # `not` before a list literal without a space negates the list literal + # rather than lexing as a path named `not[0]`. + assert evaluate_expression("{{ not[0] }}", ctx) is False + assert evaluate_expression("{{ not[] }}", ctx) is True + # Word operators adjacent to quotes still parse and evaluate cleanly. + assert evaluate_condition("{{ inputs.a=='x'and inputs.b }}", ctx) is True + assert evaluate_condition("{{ 'x'in inputs.a }}", ctx) is True + def test_integer_conversion_error_is_reported_as_invalid_expression(self): """The integer conversion limit is reported as an expression error.""" import sys diff --git a/tests/unit/test_condition_expression_block.py b/tests/unit/test_condition_expression_block.py index e4d3e2934e..50f11834c2 100644 --- a/tests/unit/test_condition_expression_block.py +++ b/tests/unit/test_condition_expression_block.py @@ -771,7 +771,8 @@ def test_the_probe_reports_what_the_evaluator_reports(): # _resolve_dot_path keys on [w-]+, so a key literally named "2bad" resolves. ("inputs.2bad", False), ("inputs.tags[foo]", True), - ("inputs.matrix[0][1]", True), + ("inputs.matrix[0][1]", False), + ("inputs.matrix[0][foo]", True), # Round 7: an operand one level down, which the single-term gate never saw. ("inputs.a === inputs.b", True), ("bogus", True), @@ -827,12 +828,13 @@ def test_filter_wiring_errors_are_still_rejections(condition): ("42", True), ("3.14", True), ("-7", True), - # `1e3` has no "." so the evaluator calls int() on it, which fails; it then - # falls through to a path lookup and resolves to None. The gate used to - # decide this for itself with a float() test that accepted `1e3`, and the - # correction turned a truthy condition false. Now the evaluator reaches the - # dot-path resolution with `1e3` and reports it, so the two cannot disagree. - ("1e3", False), + ("1e3", True), + ("1e", False), + ("steps.plan.output.matrix[0][1]", True), + ("item[0][1]", True), + ("inputs[0][1]", False), + ("1[0]", False), + ("and[0]", False), ("'one'", True), ('"one"', True), # Two literals, not one: the evaluator requires the opening quote's match to @@ -860,8 +862,11 @@ def test_literal_handling_comes_from_the_evaluator(condition, resolvable): # `_build_namespace` hands back mappings, so an indexed root always resolves # to None however the index is written. "inputs[0]", + "inputs[0][1]", "steps[1]", - "1e3", + "1e", + "1[0]", + "and[0]", "'a' 'b'", ], ) From 774012ffc581bfc24f88704ca791cc4764851798 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:06:32 +0530 Subject: [PATCH 2/4] Restrict _coerce_number float fallback to decimal and exponent spellings When an integer string exceeds Python's configured int-to-str digit limit, int() raises ValueError. Restrict the float() fallback to strings containing '.', 'e', or 'E' so overlong integer strings remain unchanged instead of silently rounding through float() during comparisons. Add a conversion-limit regression test covering _coerce_number and evaluate_condition. Assisted-by: Antigravity (model: Gemini 4 Neon (High), autonomous) --- .../workflows/expressions/operators.py | 5 +++- tests/test_workflows.py | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/specify_cli/workflows/expressions/operators.py b/src/specify_cli/workflows/expressions/operators.py index 6c01abb6cc..166d937d0d 100644 --- a/src/specify_cli/workflows/expressions/operators.py +++ b/src/specify_cli/workflows/expressions/operators.py @@ -17,7 +17,10 @@ def _coerce_number(value: Any) -> Any: return int(value) except ValueError: pass - if any(ch.isdigit() for ch in value): + if ( + ("." in value or "e" in value or "E" in value) + and any(ch.isdigit() for ch in value) + ): try: parsed = float(value) except ValueError: diff --git a/tests/test_workflows.py b/tests/test_workflows.py index d9077e536a..e771801638 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -1955,6 +1955,30 @@ def test_integer_conversion_error_is_reported_as_invalid_expression(self): finally: sys.set_int_max_str_digits(previous_limit) + def test_overlong_integer_string_does_not_fallback_to_float(self): + """Integer strings exceeding Python's digit limit stay strings instead + of silently rounding through ``float()`` during comparison.""" + import sys + + from specify_cli.workflows.base import StepContext + from specify_cli.workflows.expressions import evaluate_condition + from specify_cli.workflows.expressions.operators import _coerce_number + + previous_limit = sys.get_int_max_str_digits() + limit = sys.int_info.str_digits_check_threshold + overlong = "0" * (limit + 1) + "9007199254740993" + try: + sys.set_int_max_str_digits(limit) + assert _coerce_number(overlong) == overlong + assert isinstance(_coerce_number(overlong), str) + ctx = StepContext(inputs={"huge": overlong}) + assert evaluate_condition("{{ inputs.huge == 9007199254740992 }}", ctx) is False + assert evaluate_condition("{{ inputs.huge == 9007199254740993 }}", ctx) is False + assert evaluate_condition("{{ inputs.huge > 0 }}", ctx) is False + assert evaluate_condition("{{ inputs.huge == inputs.huge }}", ctx) is True + finally: + sys.set_int_max_str_digits(previous_limit) + def test_not_on_the_right_of_a_comparison(self): """``a == not b`` compares against the negation, as before.""" import pytest From 23bd09c840a2c622e132cb55f9344d3dd5b22efa Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:42:25 +0530 Subject: [PATCH 3/4] Remove exponent-string coercion, raise on invalid chained indexing, and document expression syntax Addresses maintainer review feedback on #5523: - Revert implicit exponent-string coercion in operators.py so "1e3" stays a string during comparisons while exponent numeric literals like 1e3 evaluate as float. - Raise IndexError on out-of-range chained list indices and TypeError on non-list chained indexing targets instead of silently returning None. - Document exponent literals and chained indexing (including expected errors) in docs/workflows/expressions.md and expand positive and expected-error tests. Assisted-by: Antigravity (model: Gemini 4 Neon (XHigh), autonomous) --- docs/workflows/expressions.md | 8 +- .../workflows/expressions/namespace.py | 30 +++- .../workflows/expressions/operators.py | 17 +- tests/test_workflows.py | 165 +++++++++++------- tests/unit/test_condition_expression_block.py | 24 ++- 5 files changed, 155 insertions(+), 89 deletions(-) diff --git a/docs/workflows/expressions.md b/docs/workflows/expressions.md index 3269e910f1..9d37f94cd6 100644 --- a/docs/workflows/expressions.md +++ b/docs/workflows/expressions.md @@ -44,8 +44,8 @@ handler, so resume is at-least-once. | Form | Example | | --- | --- | -| Dot-path lookup | `{{ inputs.name }}`, `{{ steps.test.output.exit_code }}` | -| Literals | Strings, numbers, `true`, `false`, `none`/`null`, and lists such as `[1, 2]` | +| Dot-path lookup | `{{ inputs.name }}`, `{{ steps.test.output.exit_code }}`, `{{ steps.plan.output.matrix[0][1] }}` | +| Literals | Strings, numbers (including exponent literals such as `1e3`), `true`, `false`, `none`/`null`, and lists such as `[1, 2]` | | Comparisons | `==`, `!=`, `>`, `<`, `>=`, `<=` | | Boolean logic | `and`, `or`, `not` | | Membership | `in`, `not in` | @@ -93,7 +93,9 @@ Notes on the newer filters: Operators bind from loosest to tightest as `or`, `and`, `not`, then the comparisons. All comparisons (`==`, `!=`, `>`, `<`, `>=`, `<=`, `in`, `not in`) share one level and are evaluated left to right; none has priority over another. `{{ a == b > 0 }}` therefore means `{{ (a == b) > 0 }}`. To combine comparisons, use parentheses or `and`/`or`. -The body of every `{{ }}` block must be a valid expression. Text that is not one, such as prose (`{{ some text }}`), a key with characters other than letters, digits, `_` and `-` (`{{ inputs.weird:key }}`), or arithmetic (`{{ count + 1 }}`), raises a `ValueError` naming the offending token. Numbers may be written as `5`, `-5`, `+5`, `1_000`, `0.5`, `.5`, `5.`, or `1.5e3`. +The body of every `{{ }}` block must be a valid expression. Text that is not one, such as prose (`{{ some text }}`), a key with characters other than letters, digits, `_` and `-` (`{{ inputs.weird:key }}`), or arithmetic (`{{ count + 1 }}`), raises a `ValueError` naming the offending token. Numbers may be written as `5`, `-5`, `+5`, `1_000`, `0.5`, `.5`, `5.`, `1.5e3`, `1e3`, `-2e+3`, or `5e-2`. Exponent literals evaluate to `float`; malformed exponent forms such as `1e` or `1e3.5` raise `ValueError`, and exponent-form strings such as `"1e3"` are not implicitly converted to numbers during comparisons. + +Path segments support integer list indexing, including negative indices and chained indexing (for example, `{{ steps.plan.output.matrix[0][1] }}`, `{{ steps.plan.output.matrix[-1][-2] }}`, or `{{ item[0][1] }}`). Malformed index syntax (such as `matrix[0][]` or `matrix[0][a]`) raises `ValueError`. For chained indexing, an out-of-range index raises `IndexError` and indexing a non-list value raises `TypeError` instead of returning `None`. > **Compatibility:** Earlier releases could resolve an expression such as `{{ inputs.weird:key }}` when the key existed; this expression now fails at runtime. Rename keys you control (for example, `weird:key` to `weird_key`) and update their references. Quoted-key lookup is not supported. Workflow validation may not detect these expressions before execution. diff --git a/src/specify_cli/workflows/expressions/namespace.py b/src/specify_cli/workflows/expressions/namespace.py index 6f56e7e86b..aba3e23f58 100644 --- a/src/specify_cli/workflows/expressions/namespace.py +++ b/src/specify_cli/workflows/expressions/namespace.py @@ -28,6 +28,11 @@ def _resolve_dot_path(obj: Any, path: str) -> Any: Supports dict key access and single or chained list indexing, including the negative form Python and Jinja2 both accept (e.g., ``task_list[0]``, ``task_list[-1]``, ``matrix[0][1]``). + + For chained indexing (two or more bracketed indices on one segment), + invalid access raises ``IndexError`` for out-of-range list indices and + ``TypeError`` when the target is not a list, rather than silently + returning ``None``. """ parts = path.split(".") current = obj @@ -39,25 +44,38 @@ def _resolve_dot_path(obj: Any, path: str) -> Any: if isinstance(current, dict): current = current.get(key) else: - return None + current = None raw_indices = idx_match.group(2) indices = ( _INDEX_BRACKET.findall(raw_indices) if raw_indices.startswith("[") else [raw_indices] ) + chained = len(indices) > 1 for raw_idx in indices: idx = int(raw_idx) - if isinstance(current, list) and -len(current) <= idx < len(current): + if not isinstance(current, list): + if chained: + raise TypeError( + f"cannot index {type(current).__name__} in '{path}': " + "chained indexing requires a list" + ) + current = None + break + if -len(current) <= idx < len(current): current = current[idx] + elif chained: + raise IndexError( + f"list index {idx} out of range in '{path}' " + f"(length {len(current)})" + ) else: - return None + current = None + break elif isinstance(current, dict): current = current.get(part) else: - return None - if current is None: - return None + current = None return current diff --git a/src/specify_cli/workflows/expressions/operators.py b/src/specify_cli/workflows/expressions/operators.py index 166d937d0d..3cd2a7585d 100644 --- a/src/specify_cli/workflows/expressions/operators.py +++ b/src/specify_cli/workflows/expressions/operators.py @@ -6,27 +6,16 @@ from __future__ import annotations -import math from typing import Any def _coerce_number(value: Any) -> Any: - """Return *value* as int/float if it is a finite numeric string, else unchanged.""" + """Return *value* as int/float if it is a numeric string, else unchanged.""" if isinstance(value, str): try: - return int(value) + return float(value) if "." in value else int(value) except ValueError: - pass - if ( - ("." in value or "e" in value or "E" in value) - and any(ch.isdigit() for ch in value) - ): - try: - parsed = float(value) - except ValueError: - return value - if math.isfinite(parsed): - return parsed + return value return value diff --git a/tests/test_workflows.py b/tests/test_workflows.py index e771801638..1d81f27788 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -1835,12 +1835,11 @@ def test_malformed_number_literals_are_refused(self): with pytest.raises(ValueError, match="invalid expression"): evaluate_expression("{{ " + text + " }}", StepContext(inputs={})) - def test_exponent_numeric_string_coercion_in_comparisons(self): - """Exponent-form numeric strings coerce in ordering and equality - comparisons just like workflow input coercion, while non-finite and - non-numeric strings stay strings.""" + def test_exponent_strings_are_not_implicitly_coerced_in_comparisons(self): + """Exponent-form strings stay strings during comparisons rather than + being implicitly converted to floats, while exponent numeric literals + compare as numbers.""" from specify_cli.workflows.base import StepContext - from specify_cli.workflows.engine import WorkflowEngine from specify_cli.workflows.expressions import ( evaluate_condition, evaluate_expression, @@ -1852,51 +1851,57 @@ def test_exponent_numeric_string_coercion_in_comparisons(self): "upper": "2E3", "small": "5e-2", "neg": "-1e2", - "inf_str": "inf", - "ninf_str": "-inf", - "infinity_str": "Infinity", - "nan_str": "nan", - "overflow_str": "1e400", - "overflow_dot": "1.0e400", - "bad_exp": "1e", + "n": 1000, } ) - assert WorkflowEngine._coerce_input("x", "1e3", {"type": "number"}) == 1000 - assert evaluate_condition("{{ inputs.s > 100 }}", ctx) is True - assert evaluate_condition("{{ inputs.s == 1000 }}", ctx) is True - assert evaluate_condition("{{ inputs.s == 1e3 }}", ctx) is True - assert evaluate_condition("{{ inputs.s == '1000' }}", ctx) is True - assert evaluate_condition("{{ inputs.upper > '900' }}", ctx) is True - assert evaluate_condition("{{ inputs.small < 0.1 }}", ctx) is True - assert evaluate_condition("{{ inputs.neg < 0 }}", ctx) is True - assert evaluate_condition("{{ inputs.s != 1000 }}", ctx) is False - # Non-finite strings and malformed exponents must not coerce to float. - assert evaluate_condition("{{ inputs.inf_str > 100 }}", ctx) is False - assert evaluate_condition("{{ inputs.ninf_str < 0 }}", ctx) is False - assert evaluate_condition("{{ inputs.infinity_str > 0 }}", ctx) is False - assert evaluate_condition("{{ inputs.nan_str == inputs.nan_str }}", ctx) is True - assert evaluate_condition("{{ inputs.overflow_str > 100 }}", ctx) is False - assert evaluate_condition("{{ inputs.overflow_dot > 100 }}", ctx) is False - assert evaluate_condition("{{ inputs.bad_exp > 0 }}", ctx) is False - assert evaluate_expression("{{ inputs.s == 'abc' }}", ctx) is False - - def test_chained_list_indexing_and_unsupported_index_syntax(self): - """Chained list indices resolve across nested lists and dot segments; - missing/non-list indices yield None while invalid index syntax raises.""" + # Exponent-form strings do not implicitly coerce to numbers. + assert evaluate_expression("{{ inputs.s == 1000 }}", ctx) is False + assert evaluate_expression("{{ inputs.s == 1e3 }}", ctx) is False + assert evaluate_expression("{{ inputs.s != 1000 }}", ctx) is True + assert evaluate_expression("{{ inputs.s != 1e3 }}", ctx) is True + assert evaluate_expression("{{ inputs.s == '1000' }}", ctx) is False + assert evaluate_expression("{{ inputs.s == '1e3' }}", ctx) is True + assert evaluate_condition("{{ inputs.s > 100 }}", ctx) is False + assert evaluate_condition("{{ inputs.s < 100 }}", ctx) is False + assert evaluate_condition("{{ inputs.small < 0.1 }}", ctx) is False + assert evaluate_condition("{{ inputs.neg < 0 }}", ctx) is False + # String-to-string ordering stays lexicographic ("1e3" < "2e1", "2E3" < "900"). + assert evaluate_expression("{{ inputs.s > '2e1' }}", ctx) is False + assert evaluate_expression("{{ inputs.upper > '900' }}", ctx) is False + # Exponent numeric literals still compare numerically. + assert evaluate_expression("{{ 1e3 == 1000 }}", ctx) is True + assert evaluate_expression("{{ 1e3 > 100 }}", ctx) is True + assert evaluate_expression("{{ inputs.n == 1e3 }}", ctx) is True + assert evaluate_expression("{{ 5e-2 < 0.1 }}", ctx) is True + + def test_chained_list_indexing_and_expected_errors(self): + """Chained list indices resolve across nested lists (including negative + indices) and dot segments; invalid chained access raises IndexError or + TypeError instead of returning None, and invalid syntax raises ValueError.""" import pytest from specify_cli.workflows.base import StepContext from specify_cli.workflows.expressions import ( evaluate_condition, evaluate_expression, ) + from specify_cli.workflows.step.if_then import IfThenStep ctx = StepContext( - inputs={"name": "it's", "a": "x", "b": True}, + inputs={ + "name": "it's", + "a": "x", + "b": True, + "scalar": 42, + "empty": [], + "rows": [None, {"k": "v"}], + }, steps={ "plan": { "output": { "matrix": [["a", "b"], ["c", "d"]], "cube": [[[{"label": "ok"}]]], + "null_cell": [[None]], + "falsy_cells": [[False, 0, ""]], } } }, @@ -1904,17 +1909,73 @@ def test_chained_list_indexing_and_unsupported_index_syntax(self): ) assert evaluate_expression("{{ steps.plan.output.matrix[0][1] }}", ctx) == "b" assert evaluate_expression("{{ steps.plan.output.matrix[-1][-2] }}", ctx) == "c" + assert evaluate_expression("{{ steps.plan.output.matrix[0][-1] }}", ctx) == "b" + assert evaluate_expression("{{ steps.plan.output.matrix[-2][0] }}", ctx) == "a" assert ( evaluate_expression("{{ steps.plan.output.cube[0][0][0].label }}", ctx) == "ok" ) + assert ( + evaluate_expression("{{ steps.plan.output.cube[-1][-1][-1].label }}", ctx) + == "ok" + ) + assert evaluate_expression("{{ steps.plan.output.null_cell[0][0] }}", ctx) is None + assert evaluate_expression("{{ steps.plan.output.falsy_cells[0][0] }}", ctx) is False + assert evaluate_expression("{{ steps.plan.output.falsy_cells[0][1] }}", ctx) == 0 + assert evaluate_expression("{{ steps.plan.output.falsy_cells[0][2] }}", ctx) == "" assert evaluate_expression("{{ item[0][1] }}", ctx) == "second" assert evaluate_expression("{{ item[-1][0] }}", ctx) == "third" - # Out-of-range and non-list targets are missing data, not syntax errors. - assert evaluate_expression("{{ steps.plan.output.matrix[0][9] }}", ctx) is None - assert evaluate_expression("{{ steps.plan.output.matrix[9][0] }}", ctx) is None - assert evaluate_expression("{{ steps.plan.output.matrix[0][1][0] }}", ctx) is None - # Malformed index syntax and digit-/keyword-led indexing raise. + assert evaluate_expression("{{ item[-1][-1] }}", ctx) == "fourth" + assert evaluate_condition("{{ steps.plan.output.matrix[0][1] == 'b' }}", ctx) is True + # Short-circuit boolean guards prevent evaluating an invalid chained index. + assert evaluate_condition("{{ false and steps.plan.output.matrix[0][9] }}", ctx) is False + assert evaluate_condition("{{ true or steps.plan.output.matrix[0][9] }}", ctx) is True + + # Out-of-range chained indices raise IndexError instead of returning None. + for bad_index in ( + "steps.plan.output.matrix[0][9]", + "steps.plan.output.matrix[0][-9]", + "steps.plan.output.matrix[9][0]", + "steps.plan.output.matrix[-9][0]", + "inputs.empty[0][0]", + "item[0][9]", + "item[-9][0]", + ): + with pytest.raises(IndexError, match="out of range"): + evaluate_expression("{{ " + bad_index + " }}", ctx) + # Conditions and workflow branches surface the error instead of picking the wrong branch. + with pytest.raises(IndexError, match="out of range"): + evaluate_condition("{{ steps.plan.output.matrix[0][9] != 'b' }}", ctx) + with pytest.raises(IndexError, match="out of range"): + IfThenStep().execute( + { + "id": "branch", + "condition": "{{ steps.plan.output.matrix[0][9] == 'b' }}", + "then": [], + "else": [], + }, + ctx, + ) + with pytest.raises(IndexError, match="out of range"): + evaluate_expression("cell={{ steps.plan.output.matrix[0][9] }}", ctx) + + # Chained indexing into non-list values raises TypeError instead of returning None. + for bad_target in ( + "steps.plan.output.matrix[0][1][0]", + "steps.plan.output.null_cell[0][0][0]", + "steps.plan.output.missing[0][1]", + "steps.missing.output.matrix[0][1]", + "inputs.scalar[0][1]", + "inputs.rows[0][0]", + "inputs.rows[1][0]", + "inputs[0][1]", + ): + with pytest.raises(TypeError, match="chained indexing requires a list"): + evaluate_expression("{{ " + bad_target + " }}", ctx) + with pytest.raises(TypeError, match="chained indexing requires a list"): + evaluate_expression("{{ item[0][1] }}", StepContext()) + + # Malformed index syntax and digit-/keyword-led indexing raise ValueError. for bad in ( "steps.plan.output.matrix[0][]", "steps.plan.output.matrix[0][a]", @@ -1955,30 +2016,6 @@ def test_integer_conversion_error_is_reported_as_invalid_expression(self): finally: sys.set_int_max_str_digits(previous_limit) - def test_overlong_integer_string_does_not_fallback_to_float(self): - """Integer strings exceeding Python's digit limit stay strings instead - of silently rounding through ``float()`` during comparison.""" - import sys - - from specify_cli.workflows.base import StepContext - from specify_cli.workflows.expressions import evaluate_condition - from specify_cli.workflows.expressions.operators import _coerce_number - - previous_limit = sys.get_int_max_str_digits() - limit = sys.int_info.str_digits_check_threshold - overlong = "0" * (limit + 1) + "9007199254740993" - try: - sys.set_int_max_str_digits(limit) - assert _coerce_number(overlong) == overlong - assert isinstance(_coerce_number(overlong), str) - ctx = StepContext(inputs={"huge": overlong}) - assert evaluate_condition("{{ inputs.huge == 9007199254740992 }}", ctx) is False - assert evaluate_condition("{{ inputs.huge == 9007199254740993 }}", ctx) is False - assert evaluate_condition("{{ inputs.huge > 0 }}", ctx) is False - assert evaluate_condition("{{ inputs.huge == inputs.huge }}", ctx) is True - finally: - sys.set_int_max_str_digits(previous_limit) - def test_not_on_the_right_of_a_comparison(self): """``a == not b`` compares against the negation, as before.""" import pytest diff --git a/tests/unit/test_condition_expression_block.py b/tests/unit/test_condition_expression_block.py index 50f11834c2..72c3bde866 100644 --- a/tests/unit/test_condition_expression_block.py +++ b/tests/unit/test_condition_expression_block.py @@ -859,8 +859,9 @@ def test_literal_handling_comes_from_the_evaluator(condition, resolvable): @pytest.mark.parametrize( "condition", [ - # `_build_namespace` hands back mappings, so an indexed root always resolves - # to None however the index is written. + # `_build_namespace` hands back mappings, so an indexed mapping root + # never resolves to a list (single indexing yields None; chained + # indexing raises TypeError). "inputs[0]", "inputs[0][1]", "steps[1]", @@ -990,6 +991,25 @@ def test_indexing_an_always_mapping_root_still_loses_the_correction(condition): assert evaluate_condition("{{ " + condition + " }}", ctx) is False +@pytest.mark.parametrize( + "condition", ["inputs[0][1]", "steps[1][0]", "fan_in[0][0]", "context[0][0]"] +) +def test_chained_indexing_an_always_mapping_root_loses_correction_and_raises(condition): + """Chained indexing on an always-mapping root withholds correction and raises TypeError.""" + ctx = StepContext(inputs={"a": 1}, item=[["x", "y"]]) + assert CORRECTION_OFFERED not in format_condition_remediation(condition) + with pytest.raises(TypeError, match="chained indexing requires a list"): + evaluate_condition("{{ " + condition + " }}", ctx) + + +@pytest.mark.parametrize("condition", ["item[0][1] == 'y'", "item[-1][-2] == 'x'"]) +def test_chained_indexed_item_root_keeps_the_correction(condition): + """Chained indexing on a nested list ``item`` keeps the correction and evaluates.""" + ctx = StepContext(inputs={"a": 1}, item=[["x", "y"]]) + assert CORRECTION_OFFERED in format_condition_remediation(condition) + assert evaluate_condition("{{ " + condition + " }}", ctx) is True + + # --- what the leaf walk rests on ---------------------------------------------- From 2048e21707c8044f099c237521326f687c599dee Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:05:17 +0530 Subject: [PATCH 4/4] Clarify exponent-string coercion semantics in expression docs and tests Addresses Copilot review feedback on #5523 (discussion_r4701012470): - Distinguish integer-mantissa exponent strings without a decimal point (such as "1e3", which are not coerced during comparisons) from decimal-mantissa exponent strings containing "." (such as "1.0e3" or "1.5e3", which retain existing float() coercion in operators._coerce_number). - Add clarifying assertions in test_workflows.py covering both forms while leaving operators.py unchanged relative to main. Assisted-by: Antigravity (model: Gemini 4 Neon (XHigh), autonomous) --- docs/workflows/expressions.md | 2 +- tests/test_workflows.py | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/docs/workflows/expressions.md b/docs/workflows/expressions.md index 9d37f94cd6..670a7e7f9e 100644 --- a/docs/workflows/expressions.md +++ b/docs/workflows/expressions.md @@ -93,7 +93,7 @@ Notes on the newer filters: Operators bind from loosest to tightest as `or`, `and`, `not`, then the comparisons. All comparisons (`==`, `!=`, `>`, `<`, `>=`, `<=`, `in`, `not in`) share one level and are evaluated left to right; none has priority over another. `{{ a == b > 0 }}` therefore means `{{ (a == b) > 0 }}`. To combine comparisons, use parentheses or `and`/`or`. -The body of every `{{ }}` block must be a valid expression. Text that is not one, such as prose (`{{ some text }}`), a key with characters other than letters, digits, `_` and `-` (`{{ inputs.weird:key }}`), or arithmetic (`{{ count + 1 }}`), raises a `ValueError` naming the offending token. Numbers may be written as `5`, `-5`, `+5`, `1_000`, `0.5`, `.5`, `5.`, `1.5e3`, `1e3`, `-2e+3`, or `5e-2`. Exponent literals evaluate to `float`; malformed exponent forms such as `1e` or `1e3.5` raise `ValueError`, and exponent-form strings such as `"1e3"` are not implicitly converted to numbers during comparisons. +The body of every `{{ }}` block must be a valid expression. Text that is not one, such as prose (`{{ some text }}`), a key with characters other than letters, digits, `_` and `-` (`{{ inputs.weird:key }}`), or arithmetic (`{{ count + 1 }}`), raises a `ValueError` naming the offending token. Numbers may be written as `5`, `-5`, `+5`, `1_000`, `0.5`, `.5`, `5.`, `1.5e3`, `1e3`, `-2e+3`, or `5e-2`. Exponent literals evaluate to `float`; malformed exponent forms such as `1e` or `1e3.5` raise `ValueError`. During comparisons, integer-mantissa exponent strings without a decimal point (such as `"1e3"`) remain strings and are not converted to numbers, whereas decimal-mantissa exponent strings containing `.` (such as `"1.0e3"` or `"1.5e3"`) are coerced to `float` when compared with a number or numeric string. Path segments support integer list indexing, including negative indices and chained indexing (for example, `{{ steps.plan.output.matrix[0][1] }}`, `{{ steps.plan.output.matrix[-1][-2] }}`, or `{{ item[0][1] }}`). Malformed index syntax (such as `matrix[0][]` or `matrix[0][a]`) raises `ValueError`. For chained indexing, an out-of-range index raises `IndexError` and indexing a non-list value raises `TypeError` instead of returning `None`. diff --git a/tests/test_workflows.py b/tests/test_workflows.py index 1d81f27788..ebd2b9a161 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -1836,9 +1836,10 @@ def test_malformed_number_literals_are_refused(self): evaluate_expression("{{ " + text + " }}", StepContext(inputs={})) def test_exponent_strings_are_not_implicitly_coerced_in_comparisons(self): - """Exponent-form strings stay strings during comparisons rather than - being implicitly converted to floats, while exponent numeric literals - compare as numbers.""" + """Integer-mantissa exponent strings stay strings during comparisons + rather than being implicitly converted to floats, while existing + decimal-mantissa float coercion and exponent numeric literals remain + unchanged.""" from specify_cli.workflows.base import StepContext from specify_cli.workflows.expressions import ( evaluate_condition, @@ -1851,10 +1852,12 @@ def test_exponent_strings_are_not_implicitly_coerced_in_comparisons(self): "upper": "2E3", "small": "5e-2", "neg": "-1e2", + "dec_eq": "1.0e3", + "dec_gt": "1.5e3", "n": 1000, } ) - # Exponent-form strings do not implicitly coerce to numbers. + # Integer-mantissa exponent strings do not implicitly coerce to numbers. assert evaluate_expression("{{ inputs.s == 1000 }}", ctx) is False assert evaluate_expression("{{ inputs.s == 1e3 }}", ctx) is False assert evaluate_expression("{{ inputs.s != 1000 }}", ctx) is True @@ -1868,6 +1871,12 @@ def test_exponent_strings_are_not_implicitly_coerced_in_comparisons(self): # String-to-string ordering stays lexicographic ("1e3" < "2e1", "2E3" < "900"). assert evaluate_expression("{{ inputs.s > '2e1' }}", ctx) is False assert evaluate_expression("{{ inputs.upper > '900' }}", ctx) is False + # Decimal-mantissa exponent strings keep existing float() coercion. + assert evaluate_expression("{{ inputs.dec_eq == 1000 }}", ctx) is True + assert evaluate_expression("{{ inputs.dec_eq == 1e3 }}", ctx) is True + assert evaluate_expression("{{ inputs.dec_eq == '1000' }}", ctx) is True + assert evaluate_condition("{{ inputs.dec_gt > 100 }}", ctx) is True + assert evaluate_expression("{{ inputs.dec_eq == inputs.s }}", ctx) is False # Exponent numeric literals still compare numerically. assert evaluate_expression("{{ 1e3 == 1000 }}", ctx) is True assert evaluate_expression("{{ 1e3 > 100 }}", ctx) is True