1 Commits

Author SHA1 Message Date
AlbertoPMDM 07d7efe1f4 fixed cross rules error messages 2026-09-14 13:25:06 -06:00
4 changed files with 86 additions and 16 deletions
+14 -1
View File
@@ -236,7 +236,7 @@ for a cross rule). Each entry is `{"rule": <name>, "message": <text>}`:
```json
{
"field2": {"rule": "range", "message": "field2 must be between 1 and 10, got 99"},
"_cross_field": {"rule": "requires", "message": "field3 is required when field6 is true"}
"_cross_field": {"rule": "requires[field6,field3]", "message": "field3 is required when field6 is true"}
}
```
@@ -250,6 +250,19 @@ and `unique` set the same `rule` key by hand, in
`check_foreign_keys`/`check_unique_fields`, since neither ever goes
through Pydantic at all.
A cross-rule's `rule` is not just its kind (`order`, `requires`, ...) —
it's the kind plus every field the rule is about, e.g.
`piecewise_lookup[pnn_edad_gestacional_sem,pnn_clasificacion_eg]`. The
kind alone isn't specific enough: a table can have two different
`requires` rules about entirely different fields, and both would
otherwise collapse into the same reason in any report grouped by `rule`.
This field list is computed once, from the rule's own definition, at
generation time — never from a row's data — so it's identical across
every row that fails that same rule, unlike `message`, which bakes in
the actual failing values and is close to unique per row. Group a report
by `rule`, not by `message`, if you want a count per reason rather than
a near-unique bucket per row.
## A note on cross-rule messages
Field-level rules (`required`, `range`, `regex`, and so on) never take a
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "ps-core"
version = "0.2.3"
version = "0.2.4"
description = "YAML-driven generator for SQLAlchemy storage models, Pydantic validation contracts, and data dictionaries."
readme = "README.md"
requires-python = ">=3.10"
+40 -13
View File
@@ -19,7 +19,7 @@ from __future__ import annotations
from typing import Any
from ps_core.parse_spec import OP_SYMBOLS
from ps_core.parse_spec import OP_SYMBOLS, _referenced_fields_for_kind
from ps_core.templating import env
# ---------------------------------------------------------------------------
@@ -115,15 +115,31 @@ def _raise(error_type: str, template: str, context_src: str, indent: str = "
return f"{indent}raise PydanticCustomError({error_type!r}, {template!r}, {context_src})"
def _error_type_for_rule(rule: dict[str, Any]) -> str:
"""
A cross rule's `kind` alone (e.g. "requires") is not specific enough:
a table can have two different `requires` rules, about different
fields, and both would collapse into the same reason in any report
grouped by error type. This appends the fields the rule is actually
about — computed once, at generation time, from the rule's own
definition — never from a row's data, so it stays identical across
every row that fails this same rule, unlike the message text (which
bakes in the specific failing values and is unique per row).
"""
fields = _referenced_fields_for_kind(rule["kind"], rule)
return f"{rule['kind']}[{','.join(fields)}]"
def _render_order(rule: dict[str, Any], name: str) -> str:
left, right = rule["fields"]
op_symbol = OP_SYMBOLS[rule["op"]]
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
body = [
f"_msg = {msg!r}",
f"if self.{left} is not None and self.{right} is not None:",
f" if not (self.{left} {op_symbol} self.{right}):",
_raise("order", "{_msg}: {left} vs {right}", f"{{'_msg': _msg, 'left': self.{left}, 'right': self.{right}}}"),
_raise(error_type, "{_msg}: {left} vs {right}", f"{{'_msg': _msg, 'left': self.{left}, 'right': self.{right}}}"),
]
return _wrap_method(name, body)
@@ -131,11 +147,12 @@ def _render_order(rule: dict[str, Any], name: str) -> str:
def _render_equals(rule: dict[str, Any], name: str) -> str:
a, b = rule["fields"]
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
body = [
f"_msg = {msg!r}",
f"if self.{a} is not None and self.{b} is not None:",
f" if self.{a} != self.{b}:",
_raise("equals", "{_msg}: {a} vs {b}", f"{{'_msg': _msg, 'a': self.{a}, 'b': self.{b}}}"),
_raise(error_type, "{_msg}: {a} vs {b}", f"{{'_msg': _msg, 'a': self.{a}, 'b': self.{b}}}"),
]
return _wrap_method(name, body)
@@ -145,13 +162,14 @@ def _render_sum_equals(rule: dict[str, Any], name: str) -> str:
sum_expr = " + ".join(f"self.{p}" for p in parts)
none_checks = " and ".join(f"self.{p} is not None" for p in parts)
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
body = [
f"_msg = {msg!r}",
f"if self.{target} is not None and {none_checks}:",
f" _expected = {sum_expr}",
f" if abs(self.{target} - _expected) > {tol!r}:",
_raise(
"sum_equals", "{_msg}: got {got}, expected {expected}",
error_type, "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
@@ -163,13 +181,14 @@ def _render_ratio_equals(rule: dict[str, Any], name: str) -> str:
power, tol = rule.get("power", 1), rule.get("tolerance", 0)
denom_expr = f"self.{den}" + (f" ** {power}" if power != 1 else "")
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
body = [
f"_msg = {msg!r}",
f"if self.{target} is not None and self.{num} is not None and self.{den} not in (None, 0):",
f" _expected = self.{num} / ({denom_expr})",
f" if abs(self.{target} - _expected) > {tol!r}:",
_raise(
"ratio_equals", "{_msg}: got {got}, expected {expected:.4f}",
error_type, "{_msg}: got {got}, expected {expected:.4f}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
@@ -180,13 +199,14 @@ def _render_date_offset_equals(rule: dict[str, Any], name: str) -> str:
base, offset, target = rule["base"], rule["offset_days_field"], rule["target"]
tol = rule.get("tolerance_days", 0)
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
body = [
f"_msg = {msg!r}",
f"if self.{target} is not None and self.{base} is not None and self.{offset} is not None:",
f" _expected = self.{base} + timedelta(days=self.{offset})",
f" if abs((self.{target} - _expected).days) > {tol!r}:",
_raise(
"date_offset_equals", "{_msg}: got {got}, expected {expected}",
error_type, "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
@@ -197,13 +217,14 @@ def _render_date_diff_equals(rule: dict[str, Any], name: str) -> str:
start, end, target = rule["start"], rule["end"], rule["target"]
tol = rule.get("tolerance_days", 0)
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
body = [
f"_msg = {msg!r}",
f"if self.{target} is not None and self.{start} is not None and self.{end} is not None:",
f" _expected = (self.{end} - self.{start}).days",
f" if abs(self.{target} - _expected) > {tol!r}:",
_raise(
"date_diff_equals", "{_msg}: got {got}, expected {expected}",
error_type, "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
@@ -215,6 +236,7 @@ def _render_comparison_equals(rule: dict[str, Any], name: str) -> str:
op_symbol = OP_SYMBOLS[op]
tol = rule.get("tolerance", 0)
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
if "right" in rule:
right_field = rule["right"]
@@ -235,7 +257,7 @@ def _render_comparison_equals(rule: dict[str, Any], name: str) -> str:
f" _expected = bool({cond_expr})",
f" if bool(self.{target}) != _expected:",
_raise(
"comparison_equals", "{_msg}: got {got}, expected {expected}",
error_type, "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
),
]
@@ -246,6 +268,7 @@ def _render_piecewise_lookup(rule: dict[str, Any], name: str) -> str:
source, target = rule["source"], rule["target"]
breakpoints, otherwise = rule["breakpoints"], rule["otherwise"].upper()
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
branch: list[str] = []
for i, bp in enumerate(breakpoints):
@@ -261,7 +284,7 @@ def _render_piecewise_lookup(rule: dict[str, Any], name: str) -> str:
body.append(" if _actual != _expected:")
body.append(
_raise(
"piecewise_lookup", "{_msg}: got {got}, expected {expected} for " + source + "={source_value}",
error_type, "{_msg}: got {got}, expected {expected} for " + source + "={source_value}",
f"{{'_msg': _msg, 'got': _actual, 'expected': _expected, 'source_value': self.{source}}}",
)
)
@@ -271,6 +294,7 @@ def _render_piecewise_lookup(rule: dict[str, Any], name: str) -> str:
def _render_requires(rule: dict[str, Any], name: str) -> str:
if_field, then_field = rule["if_field"], rule["then_field"]
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
cond = _condition_expr(if_field, rule)
body = [f"_msg = {msg!r}", f"if {cond}:"]
if "then_value" in rule:
@@ -280,7 +304,7 @@ def _render_requires(rule: dict[str, Any], name: str) -> str:
body.append(f" if self.{then_field} is None:")
body.append(
_raise(
"requires", "{_msg}",
error_type, "{_msg}",
f"{{'_msg': _msg, 'if_field': self.{if_field}, 'then_field': self.{then_field}}}",
)
)
@@ -291,6 +315,7 @@ def _render_forbidden_if(rule: dict[str, Any], name: str) -> str:
if_field, then_fields = rule["if_field"], rule["then_fields"]
allowed_values = [v.upper() if isinstance(v, str) else v for v in rule.get("then_allowed_values", [])]
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
cond = _condition_expr(if_field, rule)
body = [f"_msg = {msg!r}", f"if {cond}:"]
for tf in then_fields:
@@ -298,7 +323,7 @@ def _render_forbidden_if(rule: dict[str, Any], name: str) -> str:
body.append(f" if _val is not None and _val not in {allowed_values!r}:")
body.append(
_raise(
"forbidden_if", "{_msg}",
error_type, "{_msg}",
f"{{'_msg': _msg, 'if_field': self.{if_field}, 'then_field': self.{tf}, 'value': _val}}",
)
)
@@ -308,6 +333,7 @@ def _render_forbidden_if(rule: dict[str, Any], name: str) -> str:
def _render_any_of_implies(rule: dict[str, Any], name: str) -> str:
target = rule["target"]
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
cond_exprs = [_render_single_condition(c) for c in rule["conditions"]]
body = [f"_msg = {msg!r}", "_components = ("]
body += [f" {ce}," for ce in cond_exprs]
@@ -317,7 +343,7 @@ def _render_any_of_implies(rule: dict[str, Any], name: str) -> str:
body.append(f" if self.{target} != _expected:")
body.append(
_raise(
"any_of_implies", "{_msg}: got {got}, expected {expected}",
error_type, "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
)
)
@@ -329,6 +355,7 @@ def _render_conditional_equals(rule: dict[str, Any], name: str) -> str:
value_if_true, value_if_false = rule["value_if_true"], rule["value_if_false"]
tol = rule.get("tolerance", 0)
msg = rule.get("message") or rule["display"]
error_type = _error_type_for_rule(rule)
cond = _condition_expr(if_field, rule)
body = [
f"_msg = {msg!r}",
@@ -341,7 +368,7 @@ def _render_conditional_equals(rule: dict[str, Any], name: str) -> str:
body.append(f" if self.{target} != _expected:")
body.append(
_raise(
"conditional_equals", "{_msg}: got {got}, expected {expected}",
error_type, "{_msg}: got {got}, expected {expected}",
f"{{'_msg': _msg, 'got': self.{target}, 'expected': _expected}}",
)
)
+31 -1
View File
@@ -295,6 +295,34 @@ def test_render_requires_with_if_op():
M(n=3, flag=False)
def test_error_type_disambiguates_two_rules_of_the_same_kind_on_one_table():
# a table with two different `requires` rules must produce two
# distinguishable error types — the generic "requires" alone would
# make them indistinguishable in any report grouped by type
rule_a = {"kind": "requires", "if_field": "flag_a", "then_field": "x", "message": None, "display": "d1"}
rule_b = {"kind": "requires", "if_field": "flag_b", "then_field": "y", "message": None, "display": "d2"}
body_a = render_cross_rule(rule_a, 0)
body_b = render_cross_rule(rule_b, 1)
ns = _wrap_in_model(
body_a + "\n" + body_b,
" flag_a: Optional[bool] = None\n x: Optional[int] = None\n"
" flag_b: Optional[bool] = None\n y: Optional[int] = None\n",
)
M = ns["M"]
with pytest.raises(ValidationError) as exc_a:
M(flag_a=True, x=None, flag_b=False)
with pytest.raises(ValidationError) as exc_b:
M(flag_a=False, flag_b=True, y=None)
type_a = exc_a.value.errors()[0]["type"]
type_b = exc_b.value.errors()[0]["type"]
assert type_a == "requires[flag_a,x]"
assert type_b == "requires[flag_b,y]"
assert type_a != type_b
def test_render_forbidden_if():
rule = {
"kind": "forbidden_if", "if_field": "flag", "if_value": False, "then_fields": ["a"],
@@ -420,6 +448,8 @@ def test_full_validation_file_behaves_end_to_end(spec_ok_dir):
with pytest.raises(ValidationError, match="field3 is required when field6 is true") as exc_info:
TestTableCheck(field1="x", field4=date(2024, 1, 1), field6=True, field3=None)
assert exc_info.value.errors()[0]["type"] == "requires" # the cross-rule kind, not "value_error"
# the cross-rule kind, not "value_error" — plus the fields it's about,
# since a table could have more than one "requires" rule
assert exc_info.value.errors()[0]["type"] == "requires[field6,field3]"
TestTableCheck(field1="x", field4=date(2024, 1, 1), field6=True, field3=0.5)