Skip to content
Draft
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
2 changes: 2 additions & 0 deletions nextmv/nextmv/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
from .manifest import Manifest as Manifest
from .manifest import ManifestBuild as ManifestBuild
from .manifest import ManifestExecution as ManifestExecution
from .manifest import ManifestInputValidation as ManifestInputValidation
from .manifest import ManifestInputValidationEnforce as ManifestInputValidationEnforce
from .manifest import ManifestOption as ManifestOption
from .manifest import ManifestOptionType as ManifestOptionType
from .manifest import ManifestPython as ManifestPython
Expand Down
2 changes: 2 additions & 0 deletions nextmv/nextmv/cloud/application/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -793,6 +793,8 @@ def _convert_manifest_to_payload(manifest: Manifest) -> dict[str, Any]: # noqa:
output_config["assets_path"] = content.multi_file.output.assets
if content.multi_file.output.solutions:
output_config["solutions_path"] = content.multi_file.output.solutions
if content.validation is not None:
io_config["input_validation"] = content.validation.to_dict()
activation_request["requirements"]["io_configuration"] = io_config

if manifest.configuration is not None and manifest.configuration.options is not None:
Expand Down
106 changes: 105 additions & 1 deletion nextmv/nextmv/manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
from typing import Annotated, Any

import yaml
from pydantic import AliasChoices, BeforeValidator, Field
from pydantic import AliasChoices, BeforeValidator, ConfigDict, Field

from nextmv.account import AccountMemberRole
from nextmv.base_model import BaseModel
Expand Down Expand Up @@ -1081,6 +1081,106 @@ def model_post_init(self, __context) -> None:
)


class ManifestInputValidationEnforce(str, Enum):
"""
How validation findings on the run input are handled.

You can import the `ManifestInputValidationEnforce` class directly from `nextmv`:

```python
from nextmv import ManifestInputValidationEnforce
```

Attributes
----------
NONE : str
The rules are ignored.
WARN : str
Findings are reported, but runs can still be created.
BLOCK : str
Runs are not created when the input has error findings.
"""

NONE = "none"
"""The rules are ignored."""
WARN = "warn"
"""Findings are reported, but runs can still be created."""
BLOCK = "block"
"""Runs are not created when the input has error findings."""


class ManifestInputValidation(BaseModel):
"""
Validation rules for the run input data.

The rules are checked against the input before a run is created. Only the
top-level structure is checked here. The bodies of `sources` and `rules`
are kept as they are, so new kinds of checks don't need a new release of
this package. Unknown top-level keys are kept as well.

You can import the `ManifestInputValidation` class directly from `nextmv`:

```python
from nextmv import ManifestInputValidation
```

Parameters
----------
enforce : ManifestInputValidationEnforce, default="warn"
How findings are handled: `none`, `warn` or `block`.
max_findings : Optional[int], default=None
Maximum number of findings reported per rule.
sources : Optional[dict[str, dict[str, Any]]], default=None
Named tables (for example a sheet of an Excel file) that rules refer to.
rules : Optional[list[dict[str, Any]]], default=None
The validation rules. Each rule needs a unique, non-empty `name`.

Examples
--------
>>> from nextmv import ManifestInputValidation
>>> validation = ManifestInputValidation(
... enforce="block",
... rules=[{"name": "lon-range", "path": ".stops[*].location.lon", "range": [-180, 180]}],
... )
>>> validation.rules[0]["name"]
'lon-range'
"""

model_config = ConfigDict(extra="allow")

enforce: ManifestInputValidationEnforce = ManifestInputValidationEnforce.WARN
"""How findings are handled: `none`, `warn` or `block`."""
max_findings: int | None = None
"""Maximum number of findings reported per rule."""
sources: dict[str, dict[str, Any]] | None = None
"""Named tables (for example a sheet of an Excel file) that rules refer to."""
rules: list[dict[str, Any]] | None = None
"""The validation rules. Each rule needs a unique, non-empty `name`."""

def model_post_init(self, __context) -> None:
"""
Validate the structure of the rules.

Raises
------
ValueError
If `max_findings` is not positive, or a rule has a missing, empty
or duplicate `name`.
"""

if self.max_findings is not None and self.max_findings < 1:
raise ValueError(f"Invalid max_findings value {self.max_findings}. Must be a positive integer.")

seen: set[str] = set()
for index, rule in enumerate(self.rules or []):
name = rule.get("name")
if not isinstance(name, str) or not name.strip():
raise ValueError(f"Input validation rule at index {index} must have a non-empty 'name'.")
if name in seen:
raise ValueError(f"Duplicate input validation rule name '{name}'. Rule names must be unique.")
seen.add(name)


class ManifestContent(BaseModel):
"""
Content configuration for specifying how the app input/output is handled.
Expand All @@ -1097,6 +1197,8 @@ class ManifestContent(BaseModel):
The format of the content. Must be one of "json", "multi-file", or "csv-archive".
multi_file : Optional[ManifestContentMultiFile], default=None
Configuration for multi-file content format.
validation : Optional[ManifestInputValidation], default=None
Validation rules for the run input data.

Examples
--------
Expand Down Expand Up @@ -1132,6 +1234,8 @@ class ManifestContent(BaseModel):
default=None,
)
"""Configuration for multi-file content format."""
validation: ManifestInputValidation | None = None
"""Validation rules for the run input data."""

def model_post_init(self, __context) -> None:
"""
Expand Down
146 changes: 146 additions & 0 deletions nextmv/tests/test_manifest_input_validation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import os
import tempfile
import unittest

from nextmv.cloud.application import _convert_manifest_to_payload
from nextmv.manifest import (
MANIFEST_FILE_NAME,
Manifest,
ManifestContent,
ManifestInputValidation,
ManifestInputValidationEnforce,
)
from pydantic import ValidationError

APP_YAML = """\
type: python
runtime: ghcr.io/nextmv-io/runtime/python:3.11
files:
- main.py
configuration:
content:
format: multi-file
validation:
enforce: block
max_findings: 50
sources:
stops:
file: input.xlsx
sheet: stops
columns:
lon: { required: true, type: number, range: [-180, 180] }
starting-locations:
file: input.xlsx
sheet: starting-locations
rules:
- name: vehicle-has-start-location
in: stops
column: vehicle id
where: { column: status, not_equals: unassigned }
exists_in: { in: starting-locations, column: 1 }
"""


class TestManifestInputValidation(unittest.TestCase):
def test_defaults(self):
validation = ManifestInputValidation()
self.assertEqual(validation.enforce, ManifestInputValidationEnforce.WARN)
self.assertIsNone(validation.max_findings)
self.assertIsNone(validation.sources)
self.assertIsNone(validation.rules)

def test_content_without_validation(self):
content = ManifestContent.from_dict({"format": "json"})
self.assertIsNone(content.validation)
self.assertNotIn("validation", content.to_dict())

def test_from_yaml(self):
with tempfile.TemporaryDirectory() as tmp:
with open(os.path.join(tmp, MANIFEST_FILE_NAME), "w") as f:
f.write(APP_YAML)
manifest = Manifest.from_yaml(tmp)

validation = manifest.configuration.content.validation
self.assertIsInstance(validation, ManifestInputValidation)
self.assertEqual(validation.enforce, ManifestInputValidationEnforce.BLOCK)
self.assertEqual(validation.max_findings, 50)
self.assertEqual(validation.sources["stops"]["columns"]["lon"]["range"], [-180, 180])
self.assertEqual(validation.rules[0]["exists_in"], {"in": "starting-locations", "column": 1})

def test_yaml_round_trip(self):
with tempfile.TemporaryDirectory() as tmp:
with open(os.path.join(tmp, MANIFEST_FILE_NAME), "w") as f:
f.write(APP_YAML)
original = Manifest.from_yaml(tmp)

out = os.path.join(tmp, "out")
os.makedirs(out)
original.to_yaml(out)
reloaded = Manifest.from_yaml(out)

self.assertEqual(
original.configuration.content.validation.to_dict(),
reloaded.configuration.content.validation.to_dict(),
)

def test_unknown_keys_are_kept(self):
validation = ManifestInputValidation.from_dict(
{"enforce": "warn", "future_key": {"a": 1}, "rules": [{"name": "r", "future_check": True}]}
)
data = validation.to_dict()
self.assertEqual(data["future_key"], {"a": 1})
self.assertTrue(data["rules"][0]["future_check"])

def test_invalid_enforce(self):
with self.assertRaises(ValidationError):
ManifestInputValidation.from_dict({"enforce": "all"})

def test_invalid_max_findings(self):
with self.assertRaises(ValidationError):
ManifestInputValidation.from_dict({"max_findings": 0})

def test_rule_without_name(self):
with self.assertRaises(ValidationError) as ctx:
ManifestInputValidation.from_dict({"rules": [{"path": ".a", "required": True}]})
self.assertIn("index 0", str(ctx.exception))

def test_rule_with_empty_name(self):
with self.assertRaises(ValidationError):
ManifestInputValidation.from_dict({"rules": [{"name": " ", "required": True}]})

def test_duplicate_rule_names(self):
with self.assertRaises(ValidationError) as ctx:
ManifestInputValidation.from_dict({"rules": [{"name": "a"}, {"name": "a"}]})
self.assertIn("Duplicate", str(ctx.exception))


class TestInputValidationPayload(unittest.TestCase):
def test_payload_contains_input_validation(self):
with tempfile.TemporaryDirectory() as tmp:
with open(os.path.join(tmp, MANIFEST_FILE_NAME), "w") as f:
f.write(APP_YAML)
manifest = Manifest.from_yaml(tmp)

payload = _convert_manifest_to_payload(manifest=manifest)
input_validation = payload["requirements"]["io_configuration"]["input_validation"]

self.assertEqual(input_validation["enforce"], "block")
self.assertEqual(input_validation["max_findings"], 50)
self.assertIn("stops", input_validation["sources"])
self.assertEqual(input_validation["rules"][0]["name"], "vehicle-has-start-location")

def test_payload_without_input_validation(self):
manifest = Manifest.from_dict(
{
"type": "python",
"runtime": "ghcr.io/nextmv-io/runtime/python:3.11",
"files": ["main.py"],
"configuration": {"content": {"format": "json"}},
}
)
payload = _convert_manifest_to_payload(manifest=manifest)
self.assertNotIn("input_validation", payload["requirements"]["io_configuration"])


if __name__ == "__main__":
unittest.main()
Loading