From fa42611da261b8ad563b58c85287055dd6b7fece Mon Sep 17 00:00:00 2001 From: qq2514568380 <45842347+qq2514568380@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:42:11 +0800 Subject: [PATCH 1/4] fix(workflows): contain step expression failures --- src/specify_cli/workflows/_execution.py | 9 ++- tests/workflows/test_composition_execution.py | 59 +++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/src/specify_cli/workflows/_execution.py b/src/specify_cli/workflows/_execution.py index 7cd2c1b51d..9727f92438 100644 --- a/src/specify_cli/workflows/_execution.py +++ b/src/specify_cli/workflows/_execution.py @@ -711,7 +711,14 @@ 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 ValueError: + # Expression errors can include evaluated input values. + return StepResult( + StepStatus.FAILED, + error="Step execution failed: check the configuration and expression inputs.", + ) expansion = {} if kind == "fan-out": # Definitions belong to the tree, never to JSON result records. diff --git a/tests/workflows/test_composition_execution.py b/tests/workflows/test_composition_execution.py index 3c2303f98b..7a581ad73d 100644 --- a/tests/workflows/test_composition_execution.py +++ b/tests/workflows/test_composition_execution.py @@ -64,6 +64,65 @@ 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"] == ( + "Step execution failed: check the configuration and expression inputs." + ) + assert "workflow_failed" not in _logged_events(state) + + +def test_step_value_error_does_not_persist_exception_contents(tmp_path, monkeypatch): + secret = "private-value-in-error-message" + + class InvalidStep(StepBase): + type_key = "invalid" + + def execute(self, config, context): + raise ValueError(secret) + + monkeypatch.setitem(STEP_REGISTRY, "invalid", InvalidStep()) + state = WorkflowEngine(tmp_path).execute( + definition("private-errors", [{"id": "invalid", "type": "invalid"}]) + ) + assert state.status == RunStatus.FAILED + assert state.step_results["invalid"]["status"] == "failed" + for name in ("state.json", "log.jsonl"): + assert secret not in (state.runs_dir / name).read_text(encoding="utf-8") + + def test_declared_output_and_scope_isolation(tmp_path, probe): child = definition( "child", From a46545b874e5a274ce4db9fd9f36b645b401c424 Mon Sep 17 00:00:00 2001 From: qq2514568380 <45842347+qq2514568380@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:06:32 +0800 Subject: [PATCH 2/4] test(workflows): preserve runtime error propagation --- tests/test_workflows.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_workflows.py b/tests/test_workflows.py index 56baaa7b16..fe835d602c 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -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) From 44a11922537ca299fa7420005eeca9555277e7de Mon Sep 17 00:00:00 2001 From: sen <45842347+qq2514568380@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:06:37 -0800 Subject: [PATCH 3/4] fix(workflows): isolate JSON expression errors from adapter failures --- src/specify_cli/workflows/_execution.py | 6 +++--- .../workflows/expressions/filters.py | 10 ++++++--- tests/workflows/test_composition_execution.py | 21 +++++++------------ 3 files changed, 17 insertions(+), 20 deletions(-) diff --git a/src/specify_cli/workflows/_execution.py b/src/specify_cli/workflows/_execution.py index 9727f92438..bb6a266596 100644 --- a/src/specify_cli/workflows/_execution.py +++ b/src/specify_cli/workflows/_execution.py @@ -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 @@ -713,11 +714,10 @@ def execute_step(self, occurrence): return MissingImplementation(error) try: result = impl.execute(config, context) - except ValueError: - # Expression errors can include evaluated input values. + except FromJsonError: return StepResult( StepStatus.FAILED, - error="Step execution failed: check the configuration and expression inputs.", + error="from_json: invalid JSON input", ) expansion = {} if kind == "fan-out": diff --git a/src/specify_cli/workflows/expressions/filters.py b/src/specify_cli/workflows/expressions/filters.py index 7dcee8d825..4a069038c1 100644 --- a/src/specify_cli/workflows/expressions/filters.py +++ b/src/specify_cli/workflows/expressions/filters.py @@ -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: @@ -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: diff --git a/tests/workflows/test_composition_execution.py b/tests/workflows/test_composition_execution.py index 7a581ad73d..d9391ffbb0 100644 --- a/tests/workflows/test_composition_execution.py +++ b/tests/workflows/test_composition_execution.py @@ -98,29 +98,22 @@ def test_expression_failure_is_a_step_result( if succeeds: assert state.step_results["parse"]["output"]["value"] == {"value": 1} else: - assert state.step_results["parse"]["error"] == ( - "Step execution failed: check the configuration and expression inputs." - ) + assert state.step_results["parse"]["error"] == "from_json: invalid JSON input" assert "workflow_failed" not in _logged_events(state) -def test_step_value_error_does_not_persist_exception_contents(tmp_path, monkeypatch): - secret = "private-value-in-error-message" - +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(secret) + raise ValueError("adapter failure") monkeypatch.setitem(STEP_REGISTRY, "invalid", InvalidStep()) - state = WorkflowEngine(tmp_path).execute( - definition("private-errors", [{"id": "invalid", "type": "invalid"}]) - ) - assert state.status == RunStatus.FAILED - assert state.step_results["invalid"]["status"] == "failed" - for name in ("state.json", "log.jsonl"): - assert secret not in (state.runs_dir / name).read_text(encoding="utf-8") + 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): From 7c6f644e0614aef59d966195f34e5e5864f28787 Mon Sep 17 00:00:00 2001 From: qq2514568380 <45842347+qq2514568380@users.noreply.github.com> Date: Sun, 6 Dec 2026 11:23:31 +0900 Subject: [PATCH 4/4] fix(workflows): contain evaluator failures and preserve safe diagnostics Assisted-by: OpenAI Codex (model: GPT-6, autonomous) --- src/specify_cli/workflows/_execution.py | 8 ++- .../workflows/expressions/__init__.py | 3 +- src/specify_cli/workflows/expressions/api.py | 12 +++- .../specify_cli/workflows/test_command_run.py | 12 ++-- tests/workflows/test_composition_execution.py | 56 +++++++++++++++++++ 5 files changed, 81 insertions(+), 10 deletions(-) diff --git a/src/specify_cli/workflows/_execution.py b/src/specify_cli/workflows/_execution.py index bb6a266596..5449192866 100644 --- a/src/specify_cli/workflows/_execution.py +++ b/src/specify_cli/workflows/_execution.py @@ -24,7 +24,7 @@ resolve_target, validate_runtime_call, ) -from .expressions import evaluate_condition, evaluate_expression +from .expressions import ExpressionEvaluationError, evaluate_condition, evaluate_expression from .expressions.filters import FromJsonError HALTING = {"paused", "failed", "aborted"} @@ -719,6 +719,12 @@ def execute_step(self, occurrence): StepStatus.FAILED, error="from_json: invalid JSON input", ) + except ExpressionEvaluationError: + # Evaluated inputs can appear in exception details. + return StepResult( + StepStatus.FAILED, + error="Expression evaluation failed: check the workflow inputs.", + ) expansion = {} if kind == "fan-out": # Definitions belong to the tree, never to JSON result records. diff --git a/src/specify_cli/workflows/expressions/__init__.py b/src/specify_cli/workflows/expressions/__init__.py index e7af5e0806..fd1895df33 100644 --- a/src/specify_cli/workflows/expressions/__init__.py +++ b/src/specify_cli/workflows/expressions/__init__.py @@ -18,7 +18,7 @@ from __future__ import annotations -from .api import evaluate_condition, evaluate_expression +from .api import ExpressionEvaluationError, evaluate_condition, evaluate_expression from .diagnostics import ( condition_has_malformed_expression_block, condition_is_interpolated_to_text, @@ -48,6 +48,7 @@ from .template import _strip_stray_delimiters __all__ = [ + "ExpressionEvaluationError", "condition_has_malformed_expression_block", "condition_is_interpolated_to_text", "condition_is_never_evaluated", diff --git a/src/specify_cli/workflows/expressions/api.py b/src/specify_cli/workflows/expressions/api.py index db61519c65..9e4c404dd5 100644 --- a/src/specify_cli/workflows/expressions/api.py +++ b/src/specify_cli/workflows/expressions/api.py @@ -10,9 +10,14 @@ from typing import Any from .engine import _evaluate_template +from .filters import FromJsonError from .namespace import _build_namespace +class ExpressionEvaluationError(ValueError): + """A workflow template could not be evaluated.""" + + def evaluate_expression(template: str, context: Any) -> Any: """Evaluate a template string with ``{{ ... }}`` expressions. @@ -37,7 +42,12 @@ def evaluate_expression(template: str, context: Any) -> Any: return template namespace = _build_namespace(context) - return _evaluate_template(template, namespace) + try: + return _evaluate_template(template, namespace) + except FromJsonError: + raise + except ValueError as exc: + raise ExpressionEvaluationError(str(exc)) from exc def evaluate_condition(condition: str, context: Any) -> bool: diff --git a/tests/specify_cli/workflows/test_command_run.py b/tests/specify_cli/workflows/test_command_run.py index bbef842053..68e7cda1fe 100644 --- a/tests/specify_cli/workflows/test_command_run.py +++ b/tests/specify_cli/workflows/test_command_run.py @@ -598,10 +598,8 @@ def test_run_json_failed_includes_error(self, project_dir): assert payload["status"] == "failed" assert payload.get("error") - def test_run_json_step_exception_reports_failed_run(self, project_dir): - # A step that raises (here `from_json` on invalid JSON) also fails the - # run: the engine persists `failed` and the error before re-raising, so - # stdout must carry that run's payload rather than nothing at all. + def test_run_json_expression_error_reports_failed_run(self, project_dir): + # A bad expression becomes a failed step and appears in the JSON run. wf = self._write_wf(project_dir, self._WF_RAISE, "raise") result = self._invoke(project_dir, ["workflow", "run", str(wf), "--json"]) assert result.exit_code == 1 @@ -637,12 +635,12 @@ def crash(self, config, context): assert payload["error"] == "shell step crashed" assert result.stderr == "" - def test_run_step_exception_reports_failed_run_in_text(self, project_dir): + def test_run_expression_error_reports_failed_run_in_text(self, project_dir): wf = self._write_wf(project_dir, self._WF_RAISE, "raise-text") result = self._invoke(project_dir, ["workflow", "run", str(wf)]) assert result.exit_code == 1 - assert "Workflow failed:" in result.stdout - assert "from_json: invalid JSON" in result.stdout + assert "Status: failed" in result.stdout + assert "Error: from_json: invalid JSON input" in result.stdout def test_run_json_missing_required_input_is_not_a_run_outcome( self, project_dir diff --git a/tests/workflows/test_composition_execution.py b/tests/workflows/test_composition_execution.py index d9391ffbb0..063d86ffd5 100644 --- a/tests/workflows/test_composition_execution.py +++ b/tests/workflows/test_composition_execution.py @@ -16,6 +16,7 @@ WorkflowEngine, validate_workflow, ) +from specify_cli.workflows.expressions import ExpressionEvaluationError def definition(name, steps, **fields): @@ -102,6 +103,61 @@ def test_expression_failure_is_a_step_result( assert "workflow_failed" not in _logged_events(state) +@pytest.mark.parametrize("continue_on_error", [False, True]) +def test_non_json_expression_failure_is_contained(tmp_path, probe, continue_on_error): + state = WorkflowEngine(tmp_path).execute( + definition( + "non-json-expression-error", + [ + {"id": "emit", "type": "probe", "value": 12}, + { + "id": "invalid", + "type": "probe", + "value": "{{ steps.emit.output.value | length }}", + "continue_on_error": continue_on_error, + }, + {"id": "after", "type": "probe", "value": "continued"}, + ], + ) + ) + + assert state.step_results["invalid"]["status"] == "failed" + assert state.status == ( + RunStatus.COMPLETED if continue_on_error else RunStatus.FAILED + ) + assert probe["after"] == int(continue_on_error) + + +@pytest.mark.parametrize("continue_on_error", [False, True]) +def test_expression_error_keeps_exception_contents_out_of_storage( + tmp_path, monkeypatch, continue_on_error +): + private_marker = "fixture-value-outside-workflow-inputs" + + class InvalidExpressionStep(StepBase): + type_key = "invalid-expression" + + def execute(self, config, context): + raise ExpressionEvaluationError(private_marker) + + monkeypatch.setitem(STEP_REGISTRY, "invalid-expression", InvalidExpressionStep()) + state = WorkflowEngine(tmp_path).execute( + definition( + "private-expression-error", + [ + { + "id": "invalid", + "type": "invalid-expression", + "continue_on_error": continue_on_error, + }, + ], + ) + ) + assert state.step_results["invalid"]["status"] == "failed" + for name in ("state.json", "log.jsonl"): + assert private_marker not in (state.runs_dir / name).read_text(encoding="utf-8") + + def test_unrelated_step_value_error_preserves_exception_handling(tmp_path, monkeypatch): class InvalidStep(StepBase): type_key = "invalid"