Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(cli): reject pipeline steps the builder would drop and keep validate --json structured (#2037)

Aldrin Joseph34359a1dd5ff
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 74e717aa..9dc0d4e7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **`semantica pipeline validate` reported a partly malformed file valid, and `--json` had no structured result** (fixes #2026) by @ALDRIN121
+ - `PipelineBuilder.build_pipeline()` keeps a step only when both `name` and `type` are truthy, so a half-written step was dropped before the validator saw it and the file was reported valid. `_load_pipeline_file()` now checks every entry while the index is still known and rejects the file, naming the offending one (`steps[1] ('broken') is missing a non-empty 'type'`). A step that is not a mapping used to reach `dict()` inside `deserialize_pipeline()` and surface as `dictionary update sequence element #0 has length 1; 2 is required`; it is now reported as `steps[0] is not a mapping (got str)`. `pipeline run` loads through the same helper, so it no longer executes a pipeline that is silently missing a step
+ - `validate --json` now always emits `{valid, errors, warnings, pipeline}` on stdout — including when the loader or the builder inside it rejects the file, which previously fell through to the generic `{"error": ...}` envelope on stderr. When the builder raises, its `Pipeline validation failed: [...]` message is split back into one string per error instead of one repr
+ - `--json` now exits non-zero when `valid` is false, matching text mode; a caller no longer has to parse the body to notice a rejected file. New cases in `tests/test_cli_commands.py::TestPipeline` cover the dropped step, the non-mapping step, the builder rejection, and the non-pipeline file, in both modes
+
- **The `semantica pipeline` command group called APIs that do not exist** (fixes #2012) by @nilaymallikk
- `init`, `run`, `status` and `stop` all raised `AttributeError` before doing any work, calling `PipelineTemplateManager.scaffold()` and `ExecutionEngine.run()` / `.status()` / `.stop()`, none of which exist. `validate` reported `Pipeline config valid` for every input, including a file with a missing dependency, because it was handed the file *path string* where `PipelineValidator.validate()` expects a `Pipeline` — a `str` has no steps to complain about
- `init` now calls `create_pipeline_from_template()` and serialises the built `Pipeline` to the output file. Its `--template` choices and default were five names the manager has never registered, so each one would have reached `Template not found` next; they are the four real templates now, pinned against `PipelineTemplateManager.list_templates()` by a test
diff --git a/semantica/cli.py b/semantica/cli.py
index 019bf4ae..c6e9d758 100644
--- a/semantica/cli.py
+++ b/semantica/cli.py
@@ -31,6 +31,7 @@ if sys.platform == "win32":
if sys.stderr is not None and hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
+import ast
from dataclasses import asdict, dataclass, field, is_dataclass
from datetime import datetime, timezone
from pathlib import Path, PurePosixPath, PureWindowsPath
@@ -4860,6 +4861,73 @@ _PIPELINE_TEMPLATES = [
]
+class PipelineFileError(click.ClickException):
+ """A pipeline file that parses but is not a usable pipeline definition.
+
+ ``errors`` keeps the per-entry messages so ``--json`` can report each
+ offending entry instead of one flattened sentence.
+ """
+
+ def __init__(self, message: str, errors: Optional[List[str]] = None) -> None:
+ super().__init__(message)
+ self.errors = list(errors) if errors else [message]
+
+
+def _pipeline_step_errors(payload: Dict[str, Any]) -> List[str]:
+ """Return an error for every step ``PipelineBuilder`` would silently drop.
+
+ ``PipelineBuilder.build_pipeline`` keeps a step only when both ``name`` and
+ ``type`` are truthy (``pipeline_builder.py`` — ``if step_name and
+ step_type``). Every other entry disappears before the validator sees it, so
+ a partly malformed file used to be reported valid. Check the shape here,
+ while the offending index is still known.
+ """
+ steps = payload.get("steps", [])
+ if steps is None:
+ steps = []
+ if not isinstance(steps, list):
+ return [f"'steps' must be a list, got {type(steps).__name__}"]
+ errors: List[str] = []
+ for index, step in enumerate(steps):
+ if not isinstance(step, dict):
+ errors.append(
+ f"steps[{index}] is not a mapping (got {type(step).__name__})"
+ )
+ continue
+ label = f"steps[{index}]"
+ name = step.get("name")
+ if isinstance(name, str) and name.strip():
+ label += f" ('{name}')"
+ for field_name in ("name", "type"):
+ value = step.get(field_name)
+ if not (isinstance(value, str) and value.strip()):
+ errors.append(
+ f"{label} is missing a non-empty '{field_name}'"
+ )
+ return errors
+
+
+def _pipeline_builder_error_messages(exc: BaseException) -> List[str]:
+ """Split the builder's ``Pipeline validation failed: [...]`` message.
+
+ ``PipelineBuilder.build_pipeline`` raises one ``ValidationError`` whose
+ message embeds the list of validation errors as a Python literal, so a
+ ``--json`` caller that only got that string would have to parse it back.
+ """
+ detail = str(exc)
+ prefix = "Pipeline validation failed: "
+ if detail.startswith(prefix):
+ detail = detail[len(prefix):]
+ if detail.startswith("[") and detail.endswith("]"):
+ try:
+ parsed = ast.literal_eval(detail)
+ except (ValueError, SyntaxError):
+ return [detail]
+ if isinstance(parsed, list):
+ return [str(item) for item in parsed]
+ return [detail]
+
+
def _load_pipeline_file(path: str) -> Any:
"""Load a pipeline config file into a ``Pipeline`` object.
@@ -4877,10 +4945,16 @@ def _load_pipeline_file(path: str) -> Any:
except yaml.YAMLError as exc:
raise click.ClickException(f"Could not parse {path} as YAML: {exc}") from exc
if not isinstance(payload, dict):
- raise click.ClickException(
+ raise PipelineFileError(
f"{path} is not a pipeline definition: expected a mapping with a "
f"'steps' list, got {type(payload).__name__}."
)
+ step_errors = _pipeline_step_errors(payload)
+ if step_errors:
+ raise PipelineFileError(
+ f"{path} is not a valid pipeline definition: " + "; ".join(step_errors),
+ errors=step_errors,
+ )
return PipelineSerializer().deserialize_pipeline(payload)
@@ -4930,36 +5004,75 @@ def pipeline_validate(cli_ctx: CLIContext, pipeline_file: str, local_json: bool)
cli_ctx = _require_ctx(cli_ctx)
def _action() -> None:
- pipeline = _load_pipeline_file(pipeline_file)
+ # --json promises its own {valid, errors, warnings, pipeline} object, so a
+ # file the loader (or the builder inside it) rejects must still be reported
+ # in that shape instead of falling through to the generic error envelope.
+ json_mode = _is_json(cli_ctx, local_json)
+ errors: List[str] = []
+ warnings_found: List[str] = []
+ pipeline = None
try:
- from .pipeline import PipelineValidator
- except ImportError as exc:
- raise click.ClickException(f"Pipeline module not available: {exc}") from exc
- # The old wrapper passed the file path straight to validate(). A str has no
- # steps, so it type-checked nothing and reported valid for any input.
- result = PipelineValidator().validate(pipeline)
- errors = [str(e) for e in (getattr(result, "errors", None) or [])]
- warnings_found = [str(w) for w in (getattr(result, "warnings", None) or [])]
- if _is_json(cli_ctx, local_json):
+ pipeline = _load_pipeline_file(pipeline_file)
+ except PipelineFileError as exc:
+ if not json_mode:
+ raise
+ errors = exc.errors
+ except click.ClickException as exc:
+ if not json_mode:
+ raise
+ errors = [str(exc.format_message())]
+ except SemanticaError as exc: # the builder rejected the payload
+ if not json_mode:
+ raise
+ errors = _pipeline_builder_error_messages(exc)
+ except Exception as exc: # malformed in some way we did not anticipate
+ if not json_mode:
+ raise
+ errors = [str(exc)]
+
+ if pipeline is not None:
+ try:
+ from .pipeline import PipelineValidator
+ except ImportError as exc:
+ raise click.ClickException(
+ f"Pipeline module not available: {exc}"
+ ) from exc
+ # The old wrapper passed the file path straight to validate(). A str has
+ # no steps, so it type-checked nothing and reported valid for any input.
+ result = PipelineValidator().validate(pipeline)
+ errors = [str(e) for e in (getattr(result, "errors", None) or [])]
+ warnings_found = [
+ str(w) for w in (getattr(result, "warnings", None) or [])
+ ]
+ valid = bool(getattr(result, "valid", False))
+ else:
+ valid = False
+
+ if json_mode:
_jecho({
- "valid": bool(getattr(result, "valid", False)),
+ "valid": valid,
"errors": errors,
"warnings": warnings_found,
"pipeline": pipeline_file,
})
- elif not getattr(result, "valid", False):
+ if not valid:
+ # Text mode already exits non-zero on an invalid file; JSON mode
+ # used to return 0, so callers had to parse the body to notice.
+ raise SystemExit(1)
+ return
+
+ if not valid:
for err in errors:
_warn(cli_ctx, err)
raise click.ClickException(
f"Pipeline config invalid: {pipeline_file} "
f"({len(errors)} error(s), {len(warnings_found)} warning(s))"
)
- else:
- _ok(
- cli_ctx,
- f"Pipeline config valid: {pipeline_file} "
- f"({len(warnings_found)} warning(s))",
- )
+ _ok(
+ cli_ctx,
+ f"Pipeline config valid: {pipeline_file} "
+ f"({len(warnings_found)} warning(s))",
+ )
_run_with_error_handling(_action)
diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.py
index 3b4ef954..7470b652 100644
--- a/tests/test_cli_commands.py
+++ b/tests/test_cli_commands.py
@@ -2793,6 +2793,130 @@ class TestPipeline:
assert result.exit_code != 0
assert "not a pipeline definition" in _flatten(result.output)
+ def test_validate_rejects_a_step_the_builder_would_drop(self, runner):
+ # build_pipeline() keeps a step only when both name and type are truthy,
+ # so a half-written step vanished before the validator ran and the file
+ # was reported valid (#2026).
+ with runner.isolated_filesystem():
+ with open("pl.yaml", "w") as f:
+ f.write(
+ "steps:\n"
+ " - name: ingest\n"
+ " type: ingest\n"
+ " - name: broken\n"
+ " config: {}\n"
+ )
+ result = runner.invoke(
+ cli_module.main,
+ ["pipeline", "validate", "pl.yaml"],
+ )
+ assert result.exit_code != 0
+ flat = _flatten(result.output)
+ assert "steps[1]" in flat
+ assert "broken" in flat
+ assert "non-empty 'type'" in flat
+
+ def test_validate_json_reports_a_dropped_step_in_its_own_shape(self, runner):
+ # The structured object has to survive the loader rejecting the file,
+ # otherwise --json callers only see the generic error envelope.
+ with runner.isolated_filesystem():
+ with open("pl.yaml", "w") as f:
+ f.write(
+ "steps:\n"
+ " - name: ingest\n"
+ " type: ingest\n"
+ " - name: broken\n"
+ " config: {}\n"
+ )
+ result = runner.invoke(
+ cli_module.main,
+ ["pipeline", "validate", "pl.yaml", "--json"],
+ )
+ assert result.exit_code != 0
+ payload = json.loads([
+ line for line in result.output.splitlines() if line.startswith("{")
+ ][-1])
+ assert payload["valid"] is False
+ assert payload["pipeline"] == "pl.yaml"
+ assert payload["errors"] == ["steps[1] ('broken') is missing a non-empty 'type'"]
+ assert payload["warnings"] == []
+
+ def test_validate_rejects_a_step_that_is_not_a_mapping(self, runner):
+ # Used to reach dict() inside deserialize_pipeline and surface as
+ # "dictionary update sequence element #0 has length 1; 2 is required".
+ with runner.isolated_filesystem():
+ with open("pl.yaml", "w") as f:
+ f.write("steps:\n - just-a-string\n")
+ result = runner.invoke(
+ cli_module.main,
+ ["pipeline", "validate", "pl.yaml"],
+ )
+ assert result.exit_code != 0
+ flat = _flatten(result.output)
+ assert "steps[0] is not a mapping (got str)" in flat
+ assert "dictionary update sequence" not in flat
+
+ def test_validate_json_reports_a_builder_rejection_in_its_own_shape(self, runner):
+ # deserialize_pipeline() runs builder validation, which raises on a
+ # missing dependency. --json used to fall through to the error envelope
+ # on stderr instead of printing {valid, errors, warnings, pipeline}.
+ with runner.isolated_filesystem():
+ with open("pl.yaml", "w") as f:
+ f.write(
+ "steps:\n"
+ " - name: orphan\n"
+ " type: export\n"
+ " dependencies: [does_not_exist]\n"
+ )
+ result = runner.invoke(
+ cli_module.main,
+ ["pipeline", "validate", "pl.yaml", "--json"],
+ )
+ assert result.exit_code != 0
+ payload = json.loads([
+ line for line in result.output.splitlines() if line.startswith("{")
+ ][-1])
+ assert payload["valid"] is False
+ assert payload["errors"] == [
+ "Missing dependency 'does_not_exist' for step 'orphan'"
+ ]
+ assert payload["warnings"] == []
+ assert payload["pipeline"] == "pl.yaml"
+
+ def test_validate_json_keeps_the_object_for_a_non_pipeline_file(self, runner):
+ with runner.isolated_filesystem():
+ with open("pl.yaml", "w") as f:
+ f.write("just a string\n")
+ result = runner.invoke(
+ cli_module.main,
+ ["pipeline", "validate", "pl.yaml", "--json"],
+ )
+ assert result.exit_code != 0
+ payload = json.loads([
+ line for line in result.output.splitlines() if line.startswith("{")
+ ][-1])
+ assert payload["valid"] is False
+ assert "not a pipeline definition" in payload["errors"][0]
+
+ def test_run_rejects_a_step_the_builder_would_drop(self, runner):
+ # run loads through the same helper, so it must not silently execute a
+ # pipeline that is missing a step.
+ with runner.isolated_filesystem():
+ with open("pl.yaml", "w") as f:
+ f.write(
+ "steps:\n"
+ " - name: ingest\n"
+ " type: ingest\n"
+ " - name: broken\n"
+ " config: {}\n"
+ )
+ result = runner.invoke(
+ cli_module.main,
+ ["pipeline", "run", "pl.yaml"],
+ )
+ assert result.exit_code != 0
+ assert "steps[1]" in _flatten(result.output)
+
def test_run_dry_run(self, runner):
with runner.isolated_filesystem():
with open("pl.yaml", "w") as f: