Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/specify_cli/workflows/_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
validate_runtime_call,
)
from .expressions import evaluate_condition, evaluate_expression
from .expressions.filters import FromJsonError

HALTING = {"paused", "failed", "aborted"}
EXECUTION_VERSION = 2
Expand Down Expand Up @@ -711,7 +712,13 @@ def execute_step(self, occurrence):
# The node keeps its result so resume can retry after reinstalling.
error = unknown_step_error(kind)
return MissingImplementation(error)
result = impl.execute(config, context)
try:
result = impl.execute(config, context)
except FromJsonError:
return StepResult(
StepStatus.FAILED,
error="from_json: invalid JSON input",
)
expansion = {}
if kind == "fan-out":
# Definitions belong to the tree, never to JSON result records.
Expand Down
10 changes: 7 additions & 3 deletions src/specify_cli/workflows/expressions/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,13 @@ def _filter_contains(value: Any, substring: Any) -> bool:
return False


class FromJsonError(ValueError):
"""A workflow expression could not decode a JSON value."""


def _reject_json_constant(value: str) -> NoReturn:
"""Reject the non-JSON numeric constants accepted by Python's decoder."""
raise ValueError(f"from_json: invalid JSON constant: {value}")
raise FromJsonError(f"from_json: invalid JSON constant: {value}")


def _filter_from_json(value: Any) -> Any:
Expand All @@ -115,13 +119,13 @@ def _filter_from_json(value: Any) -> Any:
passing the unparsed value through would hide it.
"""
if not isinstance(value, str):
raise ValueError(
raise FromJsonError(
f"from_json: expected a JSON string, got {type(value).__name__}"
)
try:
return json.loads(value, parse_constant=_reject_json_constant)
except json.JSONDecodeError as exc:
raise ValueError(f"from_json: invalid JSON: {exc}") from exc
raise FromJsonError(f"from_json: invalid JSON: {exc}") from exc


def _filter_upper(value: Any) -> str:
Expand Down
4 changes: 2 additions & 2 deletions tests/test_workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -5893,10 +5893,10 @@ def test_unknown_template_type_halts_concurrent_like_sequential(
def test_first_exception_cancels_and_reraises(self, tmp_path, monkeypatch):
def on_item(item):
if item == 0:
raise ValueError("boom")
raise RuntimeError("boom")
return None

with pytest.raises(ValueError, match="boom"):
with pytest.raises(RuntimeError, match="boom"):
self._run(tmp_path, monkeypatch, list(range(4)), 2, on_item)


Expand Down
52 changes: 52 additions & 0 deletions tests/workflows/test_composition_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,58 @@ def execute(self, config, context):
return counts


@pytest.mark.parametrize("continue_on_error", [False, True])
@pytest.mark.parametrize(
("payload", "succeeds"),
[("not-json", False), ('{"value": 1}', True)],
)
def test_expression_failure_is_a_step_result(
tmp_path, probe, continue_on_error, payload, succeeds
):
state = WorkflowEngine(tmp_path).execute(
definition(
"expression-errors",
[
{
"id": "parse",
"type": "probe",
"value": "{{ inputs.payload | from_json }}",
"continue_on_error": continue_on_error,
},
{"id": "after", "type": "probe", "value": "continued"},
],
inputs={"payload": {"type": "string"}},
),
inputs={"payload": payload},
)
assert state.step_results["parse"]["status"] == (
"completed" if succeeds else "failed"
)
assert state.status == (
RunStatus.COMPLETED if succeeds or continue_on_error else RunStatus.FAILED
)
assert probe["after"] == int(succeeds or continue_on_error)
if succeeds:
assert state.step_results["parse"]["output"]["value"] == {"value": 1}
else:
assert state.step_results["parse"]["error"] == "from_json: invalid JSON input"
assert "workflow_failed" not in _logged_events(state)


def test_unrelated_step_value_error_preserves_exception_handling(tmp_path, monkeypatch):
class InvalidStep(StepBase):
type_key = "invalid"

def execute(self, config, context):
raise ValueError("adapter failure")

monkeypatch.setitem(STEP_REGISTRY, "invalid", InvalidStep())
with pytest.raises(ValueError, match="adapter failure"):
WorkflowEngine(tmp_path).execute(
definition("adapter-errors", [{"id": "invalid", "type": "invalid"}])
)


def test_declared_output_and_scope_isolation(tmp_path, probe):
child = definition(
"child",
Expand Down
Loading