Skip to content

Commit 9b79e81

Browse files
committed
fix(workflows): let a declared case key keep its literal expression
The guard read the expression text alone, so `expression: inputs.mode` was rejected even when an `inputs.mode:` case was declared -- a switch that dispatches that case on every run, because `execute` matches the resolved value, which for a braceless expression is that very text, stripped, against `str(case_key)`. Constant, not unevaluated. `switch_expression_is_never_evaluated` now takes the declared keys and flags a namespace reference only when none of them declares it, which is the shape that can do nothing but fall through to `default`. The `{{`-verbatim branch is unchanged: there the emitted text is not the source text, so a key cannot vouch for it. Tests assert `execute` really dispatches the declared case before asserting `validate` accepts it, then withdraw that one key and require the error back. Reverting either the predicate or the call site turns the new test red.
1 parent 34c6fa9 commit 9b79e81

3 files changed

Lines changed: 90 additions & 4 deletions

File tree

‎src/specify_cli/workflows/expressions.py‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
import json
1111
import re
12+
from collections.abc import Iterable
1213
from contextvars import ContextVar
1314
from typing import Any
1415

@@ -892,7 +893,9 @@ def condition_is_never_evaluated(condition: Any) -> bool:
892893
return _first_unclosable_block(stripped) == "verbatim"
893894

894895

895-
def switch_expression_is_never_evaluated(expression: Any) -> bool:
896+
def switch_expression_is_never_evaluated(
897+
expression: Any, case_keys: Iterable[Any] = ()
898+
) -> bool:
896899
"""True when a switch *expression* is a reference written without its braces.
897900
898901
``condition_is_never_evaluated`` cannot be reused here as it stands. It flags
@@ -907,13 +910,24 @@ def switch_expression_is_never_evaluated(expression: Any) -> bool:
907910
It is matched against the case keys as its own source text, so it falls through
908911
to ``default`` on every run. An opening ``{{`` the interpolator emits verbatim
909912
is flagged for the same reason, exactly as it is for a condition.
913+
914+
*case_keys* are the keys the switch declares, and they decide that last point
915+
rather than the expression text alone. Text reading like a reference is still a
916+
literal the author may have meant: ``expression: inputs.mode`` against a declared
917+
``inputs.mode:`` case dispatches it on every run, because ``SwitchStep.execute``
918+
compares the resolved value -- for a braceless expression, this very text,
919+
stripped -- against ``str(case_key)``. Such a switch is constant, not unevaluated,
920+
so it is left alone. Only a reference matching no declared key can do nothing but
921+
fall through, which is the authoring mistake this guards.
910922
"""
911923
if not isinstance(expression, str):
912924
return False
913925
stripped = expression.strip()
914926
if "{{" in stripped:
915927
return _first_unclosable_block(stripped) == "verbatim"
916-
return _NAMESPACE_REFERENCE.match(stripped) is not None
928+
if _NAMESPACE_REFERENCE.match(stripped) is None:
929+
return False
930+
return all(str(key) != stripped for key in case_keys)
917931

918932

919933
def condition_is_interpolated_to_text(condition: Any) -> bool:
@@ -1146,6 +1160,9 @@ def _has_incomplete_operand(text: str) -> bool:
11461160
_NAMESPACE_ROOTS = ("inputs", "steps", "item", "fan_in", "context")
11471161

11481162
# Text that opens by walking into one of those roots: `inputs.mode`, `item[0]`.
1163+
# Matching this is necessary but not sufficient to call a switch expression
1164+
# unevaluated: the same text declared as a case key is a literal the switch really
1165+
# does dispatch, so `switch_expression_is_never_evaluated` checks the keys too.
11491166
_NAMESPACE_REFERENCE = re.compile(
11501167
r"(?:%s)(?:\.[\w-]|\[\d)" % "|".join(_NAMESPACE_ROOTS)
11511168
)

‎src/specify_cli/workflows/step/switch/__init__.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,12 +125,22 @@ def validate(self, config: dict[str, Any]) -> list[str]:
125125
# flagged, not every string without braces. And a composite key such as
126126
# `{{ inputs.a }}-{{ inputs.b }}` is legitimate here even though the same
127127
# shape would be a fault in a boolean condition.
128-
elif switch_expression_is_never_evaluated(config["expression"]):
128+
#
129+
# The declared keys settle the remaining ambiguity, which the expression text
130+
# cannot: `inputs.mode` reads like a reference, but against a declared
131+
# `inputs.mode:` case it is a literal that dispatches that case on every run,
132+
# so it is passed through. Only a reference matching no declared key is left
133+
# with nowhere to go but `default`.
134+
elif switch_expression_is_never_evaluated(
135+
config["expression"],
136+
config["cases"].keys() if isinstance(config.get("cases"), dict) else (),
137+
):
129138
errors.append(
130139
f"Switch step {config.get('id', '?')!r}: 'expression' "
131140
f"{config['expression']!r} has no usable '{{ }}' block, so it is "
132141
"never evaluated: the literal text is matched against the case keys, "
133-
"which falls through to 'default' on every run."
142+
"none of which declares it, so the switch falls through to 'default' "
143+
"on every run."
134144
)
135145
elif condition_has_malformed_expression_block(config["expression"]):
136146
errors.append(

‎tests/test_workflows.py‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3833,6 +3833,65 @@ def test_a_composite_key_expression_stays_accepted(self):
38333833
e for e in SwitchStep().validate(config) if "'expression'" in e
38343834
] == [], expression
38353835

3836+
def test_a_reference_declared_as_a_case_key_stays_accepted(self):
3837+
"""The declared keys decide this, not the shape of the expression text.
3838+
3839+
`expression: inputs.mode` reads like a reference written without its braces,
3840+
but with an `inputs.mode:` case declared it is a literal the switch really
3841+
dispatches, on every run: `execute` matches the resolved value -- for a
3842+
braceless expression, this very text, stripped -- against `str(case_key)`.
3843+
That switch is constant, not unevaluated, so the guard leaves it alone.
3844+
"""
3845+
from specify_cli.workflows.step.switch import SwitchStep
3846+
from specify_cli.workflows.base import StepContext, StepStatus
3847+
3848+
branch = [{"id": "r", "type": "command", "command": "echo"}]
3849+
for expression, declared in (
3850+
("inputs.mode", "inputs.mode"),
3851+
("item[0]", "item[0]"),
3852+
("context.run_id", "context.run_id"),
3853+
# `execute` strips the resolved value before matching, so the padded
3854+
# form dispatches the unpadded key and must be accepted with it.
3855+
(" inputs.mode ", "inputs.mode"),
3856+
):
3857+
cases = {declared: branch, "review": branch}
3858+
config = {"id": "route", "expression": expression, "cases": cases}
3859+
3860+
# Ground truth first: it really does dispatch the declared case.
3861+
result = SwitchStep().execute(config, StepContext(inputs={"mode": "review"}))
3862+
assert result.status == StepStatus.COMPLETED, expression
3863+
assert result.output["matched_case"] == declared, expression
3864+
assert [
3865+
e for e in SwitchStep().validate(config) if "'expression'" in e
3866+
] == [], expression
3867+
3868+
# Withdraw just that key and the same text has nowhere to go but
3869+
# `default`, so the guard must fire again. This is what stops the
3870+
# exemption above from disarming it.
3871+
without = {"id": "route", "expression": expression, "cases": {"review": branch}}
3872+
fallthrough = SwitchStep().execute(without, StepContext(inputs={"mode": "review"}))
3873+
assert fallthrough.output["matched_case"] == "__default__", expression
3874+
errors = [e for e in SwitchStep().validate(without) if "'expression'" in e]
3875+
assert len(errors) == 1, expression
3876+
assert "never evaluated" in errors[0], expression
3877+
3878+
def test_a_reference_is_still_rejected_when_cases_are_unusable(self):
3879+
"""A malformed or absent `cases` cannot exempt anything.
3880+
3881+
The exemption reads the declared keys, and a non-mapping `cases` has none --
3882+
it is itself an error `validate` reports separately. The expression must keep
3883+
its own error rather than fall silent because the keys could not be read.
3884+
"""
3885+
from specify_cli.workflows.step.switch import SwitchStep
3886+
3887+
for cases in ({}, None, [], "review", 3):
3888+
config = {"id": "route", "expression": "inputs.mode"}
3889+
if cases is not None:
3890+
config["cases"] = cases
3891+
errors = [e for e in SwitchStep().validate(config) if "'expression'" in e]
3892+
assert len(errors) == 1, cases
3893+
assert "never evaluated" in errors[0], cases
3894+
38363895

38373896
class TestWhileStep:
38383897
"""Test the while loop step type."""

0 commit comments

Comments
 (0)