From 348945e7895f58cc55d273be2b7e85c0222be5b2 Mon Sep 17 00:00:00 2001 From: ArmSL Date: Thu, 3 Dec 2026 14:49:22 +0100 Subject: [PATCH 1/2] feat(backend): check relational OCL invariants before each commit A Pydantic schema sees one payload, so an OCL invariant that navigates associations was left as a TODO and nothing enforced it in the generated backend. The generated database.py now checks the invariants it can translate before each commit, on the records the request loaded or changed and their direct neighbours, and refuses a violating change with HTTP 422 naming the rule. Translated subset (besser/generators/backend/ocl_invariants.py, over the B-OCL parse tree): navigation from self, isEmpty/notEmpty/size/includes/ excludes/isUnique, comparisons of numbers/strings/booleans, and/or/xor/ implies/not, literals. Anything else keeps its TODO, and so does a rule that would fail while an end whose records need self first is still empty (it would make the record impossible to create). The schema comment now says the rule is checked at commit, and the Spec-Driven Agent no longer seeds an "enforce this rule" task for it on the scaffolds that carry the check (FastAPI backend, web app). --- besser/generators/backend/api_generator.py | 8 +- besser/generators/backend/ocl_invariants.py | 240 ++++++++++++++++++ .../backend/templates/database.py.j2 | 99 ++++++++ .../generators/pydantic_classes/ocl_utils.py | 13 + .../pydantic_classes_generator.py | 17 +- .../pipeline/orchestrator.py | 9 + docs/source/generators/backend.rst | 25 ++ docs/source/generators/pydantic.rst | 7 +- .../backend/test_ocl_invariant_checks.py | 174 +++++++++++++ tests/spec_driven_agent/test_ocl_rule_seed.py | 41 ++- 10 files changed, 628 insertions(+), 5 deletions(-) create mode 100644 besser/generators/backend/ocl_invariants.py create mode 100644 tests/generators/backend/test_ocl_invariant_checks.py diff --git a/besser/generators/backend/api_generator.py b/besser/generators/backend/api_generator.py index 4e18354c9..aa9eb0f45 100644 --- a/besser/generators/backend/api_generator.py +++ b/besser/generators/backend/api_generator.py @@ -45,6 +45,7 @@ from besser.generators.default_literals import register_default_literals from besser.generators.action_language.RESTGenerator import bal_to_rest from besser.generators.backend.nn_methods import collect_nn_modules, nn_method_code +from besser.generators.backend.ocl_invariants import collect_invariants from besser.generators.structural_utils import ( get_deferred_fk_associations, get_foreign_keys, @@ -306,7 +307,12 @@ def generate_modular_api( # database.py: engine/session setup shared by main_api.py and every router. database_template = env.get_template("database.py.j2") - write("database.py", database_template.render(name=model.name)) + # The OCL rules the schemas cannot check are checked by database.py before each commit. + invariants = [ + {**inv, "name_repr": repr(inv["name"]), "expression_repr": repr(inv["expression"])} + for inv in collect_invariants(model) + ] + write("database.py", database_template.render(name=model.name, invariants=invariants)) # bal_stdlib.py: BESSER Action Language standard-library helpers, shared # by any router whose class methods use them. diff --git a/besser/generators/backend/ocl_invariants.py b/besser/generators/backend/ocl_invariants.py new file mode 100644 index 000000000..5c9ef8fd9 --- /dev/null +++ b/besser/generators/backend/ocl_invariants.py @@ -0,0 +1,240 @@ +"""OCL invariants that navigate associations, as Python checks the generated backend runs at commit. + +A Pydantic schema sees one request payload, so ``pydantic_classes/ocl_utils.py`` leaves a TODO for a +rule that needs other rows. The generated backend has the rows: ``database.py`` checks each rule +translated here on the records a change touched, and their direct neighbours, before the change is +committed, and refuses a violating change with HTTP 422 naming the rule. + +Translated subset, over the parse tree of B-OCL: navigation from ``self`` through attributes and +association ends; ``isEmpty``, ``notEmpty``, ``size``, ``includes``, ``excludes`` and ``isUnique``; +comparisons of numbers, strings and booleans; ``and``, ``or``, ``xor``, ``implies`` and ``not``; +literals. A rule using anything else (iterators such as ``forAll`` or ``select``, ``collect``, +``sum``, enumeration literals, dates) keeps its TODO. + +One kind of rule inside the subset keeps its TODO too: one that can fail while an end of ``self`` +whose records each need ``self`` first is still empty (``self.items->notEmpty()`` when every item +needs its order). Enforced at commit, it would refuse creating the record at all. +""" + +import ast +import logging +import re +from typing import Dict, List, Optional, Tuple + +from antlr4 import CommonTokenStream, InputStream + +from besser.BUML.metamodel.ocl.ocl import ( + BooleanLiteralExpression, InfixOperator, IntegerLiteralExpression, OperationCallExpression, + PropertyCallExpression, RealLiteralExpression, StringLiteralExpression, VariableExp, +) +from besser.BUML.metamodel.structural import Class, DomainModel, Property +from besser.BUML.notations.ocl.BOCLLexer import BOCLLexer +from besser.BUML.notations.ocl.BOCLParser import BOCLParser +from besser.BUML.notations.ocl.error_handling import BOCLErrorListener +from besser.BUML.notations.ocl.visitor import BOCLVisitorImpl +from besser.generators.pydantic_classes.ocl_utils import parse_ocl_constraint + +logger = logging.getLogger(__name__) + +_INVARIANT_HEADER = re.compile(r"^\s*context\s+\w+\s+inv\b") + +_COMPARISONS = {"=": "==", "<>": "!=", "<": "<", "<=": "<=", ">": ">", ">=": ">="} +_PRIMITIVE_KINDS = {"int": "num", "float": "num", "str": "str", "bool": "bool"} + +#: The only operations a rule on an end whose records need ``self`` first may use: each holds on an +#: empty collection, and none negates another (``not``, ``implies``, ``= false`` would turn +#: ``isEmpty`` into a minimum that refuses creating ``self``). +_HOLD_ON_EMPTY = {"isempty", "isunique", "excludes", "and", "or"} + +#: AST nodes a translated check may contain; everything else means a translation bug. +_ALLOWED_NODES = ( + ast.Expression, ast.BoolOp, ast.UnaryOp, ast.Compare, ast.Call, ast.Name, ast.Constant, ast.Load, + ast.And, ast.Or, ast.Not, ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE, ast.In, ast.NotIn, +) +_ALLOWED_NAMES = {"obj", "len", "_nav", "_coll", "_is_unique"} + + +class _Unsupported(Exception): + """The rule uses something outside the translated subset.""" + + +def collect_invariants(model: DomainModel) -> List[Dict[str, str]]: + """The invariants of ``model`` the backend enforces at commit, ordered by name. + + Each is ``{"class_name", "name", "expression", "python"}``: ``python`` is an expression over + ``obj``, a record of ``class_name`` (or of a subclass), true when the rule holds. Only rules + the Pydantic schemas skip are included, so no rule is checked twice. + """ + invariants = [] + for constraint in sorted(model.constraints, key=lambda c: c.name or ""): + if constraint.language != "OCL" or not isinstance(constraint.context, Class): + continue + if not _INVARIANT_HEADER.match(constraint.expression or ""): + continue + parsed = parse_ocl_constraint(constraint, model) + if not (parsed and parsed.get("skipped")): + continue + python = translate_invariant(constraint, model) + if python is not None: + invariants.append({ + "class_name": constraint.context.name, + "name": constraint.name, + "expression": " ".join(constraint.expression.split()), + "python": python, + }) + return invariants + + +def translate_invariant(constraint, model: DomainModel) -> Optional[str]: + """``constraint`` as a Python expression over ``obj``, or None when it is outside the subset.""" + root = _parse(constraint, model) + if root is None: + return None + translator = _Translator(constraint.context) + try: + python, kind, _ = translator.expr(root) + except _Unsupported as reason: + logger.debug("OCL invariant %s not translated: %s", constraint.name, reason) + return None + if kind != "bool" or (translator.part_ends and translator.ops - _HOLD_ON_EMPTY): + return None + _check_safe(python) + return python + + +def _parse(constraint, model): + """The B-OCL parse tree of ``constraint``, or None when it does not parse.""" + listener = BOCLErrorListener() + lexer = BOCLLexer(InputStream(constraint.expression)) + lexer.removeErrorListeners() + lexer.addErrorListener(listener) + parser = BOCLParser(CommonTokenStream(lexer)) + parser.removeErrorListeners() + parser.addErrorListener(listener) + try: + tree = parser.oclFile() + if listener.has_errors(): + return None + return BOCLVisitorImpl(model, None, constraint.context).visit(tree) + except Exception: # the visitor raises on what it cannot type; that rule keeps its TODO + logger.debug("OCL invariant %s does not parse", constraint.name, exc_info=True) + return None + + +def _check_safe(python: str) -> None: + """Refuse to emit anything but the expression shapes the translator writes.""" + tree = ast.parse(python, mode="eval") + for node in ast.walk(tree): + if not isinstance(node, _ALLOWED_NODES) or (isinstance(node, ast.Name) and node.id not in _ALLOWED_NAMES): + raise ValueError(f"unexpected node in translated OCL: {ast.dump(node)}") + + +class _Translator: + """Walks a B-OCL tree into Python; each step returns ``(code, kind, element class)``. + + ``kind`` is ``"bool"``, ``"num"``, ``"str"``, ``"obj"`` (at most one record), ``"objs"`` + (records) or ``"other"``; the element + class is the class of the records a navigation yields, for ``isUnique``'s key. + """ + + def __init__(self, context: Class): + self.context = context + self.ops = set() + self.part_ends = set() + + def expr(self, node) -> Tuple[str, str, Optional[Class]]: + if isinstance(node, BooleanLiteralExpression): + return repr(bool(node.value)), "bool", None + if isinstance(node, (IntegerLiteralExpression, RealLiteralExpression)): + return repr(node.value), "num", None + if isinstance(node, StringLiteralExpression): + return repr(str(node.value)), "str", None + if isinstance(node, Property): + return self._navigate("obj", self.context, node, from_self=True) + if isinstance(node, PropertyCallExpression): + return self._property_call(node) + if isinstance(node, OperationCallExpression): + return self._operation(node) + raise _Unsupported(type(node).__name__) + + def _property_call(self, node: PropertyCallExpression): + if node.source is None: + return self._navigate("obj", self.context, node.property, from_self=True) + base, kind, owner = self.expr(node.source) + if kind not in ("obj", "objs") or owner is None: + raise _Unsupported(f"navigation from a {kind}") + code, step_kind, element = self._navigate(base, owner, node.property, from_self=False) + # Navigating from several records collects from each of them, as OCL does. + if kind == "objs": + step_kind = "objs" if step_kind in ("obj", "objs") else "other" + return code, step_kind, element + + def _navigate(self, base: str, owner: Class, prop: Property, from_self: bool): + end = next((e for e in owner.all_association_ends() if e.name == prop.name), None) + if end is not None: + opposite = end.opposite_end() + if from_self and opposite.multiplicity.min >= 1 and opposite.multiplicity.max == 1: + self.part_ends.add(end.name) + kind = "objs" if end.multiplicity.max > 1 else "obj" + return f"_nav({base}, {end.name!r})", kind, end.type + attribute = next((a for a in owner.all_attributes() if a.name == prop.name), None) + if attribute is None: + raise _Unsupported(f"{prop.name} is not a feature of {owner.name}") + return f"_nav({base}, {attribute.name!r})", _PRIMITIVE_KINDS.get(attribute.type.name, "other"), None + + def _operation(self, node: OperationCallExpression): + op = str(node.operation).lower() + self.ops.add(op) + args = list(node.arguments or []) + if op in ("and", "or", "xor", "implies"): + left, right = (self._boolean(a) for a in args) + joined = {"and": f"({left} and {right})", "or": f"({left} or {right})", + "xor": f"({left} != {right})", "implies": f"(not {left} or {right})"}[op] + return joined, "bool", None + if op == "not": + return f"(not {self._boolean(args[0])})", "bool", None + if op in _COMPARISONS: + return self._comparison(op, args) + if op in ("isempty", "notempty", "size", "includes", "excludes", "isunique"): + return self._collection(op, node.source, args) + raise _Unsupported(op) + + def _boolean(self, node) -> str: + code, kind, _ = self.expr(node) + if kind != "bool": + raise _Unsupported(f"{kind} used as a condition") + return code + + def _comparison(self, op: str, args: list): + operands = [a for a in args if not isinstance(a, InfixOperator)] + if len(operands) != 2: + raise _Unsupported("comparison shape") + (left, left_kind, _), (right, right_kind, _) = (self.expr(a) for a in operands) + same = left_kind == right_kind and left_kind in ("num", "str", "bool") + identity = left_kind == right_kind == "obj" and op in ("=", "<>") + if not (same or identity): + raise _Unsupported(f"comparison of {left_kind} and {right_kind}") + return f"({left} {_COMPARISONS[op]} {right})", "bool", None + + def _collection(self, op: str, source, args: list): + if source is None: + raise _Unsupported(f"{op} without a source") + items, _, element = self.expr(source) + items = f"_coll({items})" + if op == "isempty": + return f"(len({items}) == 0)", "bool", None + if op == "notempty": + return f"(len({items}) > 0)", "bool", None + if op == "size": + return f"len({items})", "num", None + if op == "isunique": + key = args[0] if args else None + name = key.name if isinstance(key, (VariableExp, Property)) else None + features = set() + if element is not None: + features = {a.name for a in element.all_attributes()} | {e.name for e in element.all_association_ends()} + if name not in features: + raise _Unsupported("isUnique key") + return f"_is_unique({items}, {name!r})", "bool", None + value, _, _ = self.expr(args[0]) + return f"({value} {'in' if op == 'includes' else 'not in'} {items})", "bool", None diff --git a/besser/generators/backend/templates/database.py.j2 b/besser/generators/backend/templates/database.py.j2 index 799e8e49d..92596ad7d 100644 --- a/besser/generators/backend/templates/database.py.j2 +++ b/besser/generators/backend/templates/database.py.j2 @@ -6,6 +6,10 @@ from fastapi.exceptions import RequestValidationError from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sql_alchemy import Base, _configure_sqlite_engine +{% if invariants %} +from sqlalchemy import event, inspect as sa_inspect +import sql_alchemy as _models +{% endif %} logger = logging.getLogger(__name__) @@ -81,3 +85,98 @@ def integrity_error_detail(exc) -> str: if "foreign key constraint" in lowered: return "The record refers to a record that does not exist, or another record still refers to it" return re.split(r"\n|\s*DETAIL:", driver_text, maxsplit=1)[0] +{% if invariants %} + + +############################################ +# +# Model rules checked before each commit +# +############################################ + +# The OCL rules of the model that span associations; pydantic_classes.py checks the others. +# Each is (class, rule name, OCL, check): the check is true when the rule holds for a record. +OCL_INVARIANTS = [ +{% for inv in invariants %} + (_models.{{ inv.class_name }}, {{ inv.name_repr }}, {{ inv.expression_repr }}, + lambda obj: {{ inv.python }}), +{% endfor %} +] +_RULE_CLASSES = tuple({rule[0] for rule in OCL_INVARIANTS}) + + +def _coll(value): + """A navigation as a list: OCL treats one value as a one-element collection.""" + if value is None: + return [] + return list(value) if isinstance(value, (list, tuple, set)) else [value] + + +def _nav(value, name): + """``value.name``; from several records, the values of all of them, as OCL collects.""" + if value is None: + return None + if isinstance(value, (list, tuple, set)): + return [item for record in value for item in _coll(getattr(record, name))] + return getattr(value, name) + + +def _is_unique(records, name): + keys = [getattr(record, name) for record in records] + keys = [id(key) if hasattr(key, "_sa_instance_state") else ("value", key) for key in keys] + return len(keys) == len(set(keys)) + + +def _gone(record): + state = sa_inspect(record) + return state.deleted or state.detached or state.was_deleted + + +def _neighbours(record): + """The records directly linked to ``record`` that a rule may be about.""" + for relationship in sa_inspect(record).mapper.relationships: + target = relationship.mapper.class_ + if any(issubclass(target, cls) or issubclass(cls, target) for cls in _RULE_CLASSES): + yield from _coll(getattr(record, relationship.key)) + + +@event.listens_for(SessionLocal, "before_flush") +def _remember_links_of_deleted(session, flush_context, instances): + """A deleted record takes its links with it: keep the records it was linked to, to check them.""" + remembered = session.info.setdefault("ocl_linked_to_deleted", []) + for record in session.deleted: + remembered.extend(_neighbours(record)) + + +@event.listens_for(SessionLocal, "before_commit") +def _check_invariants(session): + """Refuse a commit (HTTP 422) that leaves a record it touched, or one linked to it, breaking a rule. + + Checks reach one link away from what the request loaded or changed: a rule that a change + further away breaks is not caught. + """ + session.flush() + touched = list(session.identity_map.values()) + session.info.pop("ocl_linked_to_deleted", []) + # Links written with SQL statements are not in the loaded collections: read them again. + session.expire_all() + records = {} + for record in touched: + if _gone(record): + continue + records[id(record)] = record + for neighbour in _neighbours(record): + if not _gone(neighbour): + records[id(neighbour)] = neighbour + for record in records.values(): + for cls, name, ocl, check in OCL_INVARIANTS: + if not isinstance(record, cls): + continue + key = ", ".join(str(part) for part in sa_inspect(record).identity or ()) + try: + holds = check(record) + except TypeError: # an ordering comparison with an empty value: OCL leaves it undefined + logger.warning("Rule %s could not be evaluated on %s %s", name, type(record).__name__, key) + continue + if not holds: + raise HTTPException(status_code=422, detail=f"{type(record).__name__} {key} breaks the rule {name}: {ocl}") +{% endif %} diff --git a/besser/generators/pydantic_classes/ocl_utils.py b/besser/generators/pydantic_classes/ocl_utils.py index 891f316c0..ea5c00aae 100644 --- a/besser/generators/pydantic_classes/ocl_utils.py +++ b/besser/generators/pydantic_classes/ocl_utils.py @@ -113,6 +113,13 @@ "related rows via the database session. Do not add this check here." ) +#: Emitted instead of :data:`SKIP_COMMENT_TEMPLATE` for a constraint the generated backend +#: checks before each commit (``besser/generators/backend/ocl_invariants.py``). +ENFORCED_AT_COMMIT_TEMPLATE = ( + "OCL constraint '{name}' is enforced when a change is committed (database.py).\n" + "OCL: {expression}" +) + #: Reason text for a constraint that reached this module but could not be #: translated (as opposed to one rejected upstream by the OCL converter, #: which carries its own reason -- see ``get_rejected_constraints_for_class``). @@ -131,6 +138,12 @@ def _format_unenforced_comment(name: Optional[str], expression: str, reason: str return [f"# {line}".rstrip() for line in text.splitlines()] +def format_enforced_at_commit_comment(name: Optional[str], expression: str) -> List[str]: + """:data:`ENFORCED_AT_COMMIT_TEMPLATE` as ``#``-prefixed lines, one prefix per line.""" + text = ENFORCED_AT_COMMIT_TEMPLATE.format(name=name or "unnamed", expression=expression) + return [f"# {line}".rstrip() for line in text.splitlines()] + + # --------------------------------------------------------------------------- # Public API # --------------------------------------------------------------------------- diff --git a/besser/generators/pydantic_classes/pydantic_classes_generator.py b/besser/generators/pydantic_classes/pydantic_classes_generator.py index 131737944..6625d58d0 100644 --- a/besser/generators/pydantic_classes/pydantic_classes_generator.py +++ b/besser/generators/pydantic_classes/pydantic_classes_generator.py @@ -13,7 +13,9 @@ is_server_owned_attribute, is_shadowed_by_association_end, ) -from besser.generators.pydantic_classes.ocl_utils import build_constraints_map +from besser.generators.pydantic_classes.ocl_utils import ( + build_constraints_map, format_enforced_at_commit_comment, +) from besser.utilities.utils import sort_by_timestamp from besser.utilities.generation_trace import traced_environment @@ -45,6 +47,17 @@ def __init__(self, model: DomainModel, backend: bool = False, nested_creations: self.backend = backend self.nested_creations = nested_creations + def _note_rules_checked_at_commit(self, constraints_map: dict) -> None: + """Replace the TODO of each skipped rule the backend's database.py checks before a commit.""" + # Imported here: the backend package imports this generator. + from besser.generators.backend.ocl_invariants import collect_invariants + checked = {inv["name"] for inv in collect_invariants(self.domain_model)} + for entries in constraints_map.values(): + for entry in entries: + if entry.get("skipped") and entry.get("constraint_name") in checked: + entry["comment_lines"] = format_enforced_at_commit_comment( + entry["constraint_name"], " ".join(entry["constraint"].expression.split())) + @property def domain_model(self) -> DomainModel: """DomainModel: The model being generated. It is ``model``, not a copy of it, so that the model @@ -97,6 +110,8 @@ def ascii_identifier(name: str) -> str: constraints_map = build_constraints_map( self.domain_model, include_model_level=True, include_skipped=True ) + if self.backend: + self._note_rules_checked_at_commit(constraints_map) class_names = {cls.name for cls in sorted_classes} diff --git a/besser/spec_driven_agent/pipeline/orchestrator.py b/besser/spec_driven_agent/pipeline/orchestrator.py index 46226f57c..602601aa7 100644 --- a/besser/spec_driven_agent/pipeline/orchestrator.py +++ b/besser/spec_driven_agent/pipeline/orchestrator.py @@ -4091,6 +4091,9 @@ def _verify_workspace(self, sweep: bool = False) -> list[ValidationIssue]: "generate_django": "django", } + #: Scaffolds whose database.py checks the OCL rules the schemas cannot (ocl_invariants.py). + _COMMIT_CHECKING_GENERATORS = ("generate_fastapi_backend", "generate_web_app") + def _scaffold_family(self) -> str | None: return self._SCAFFOLD_FAMILIES.get(self._generator_used or "") @@ -4545,13 +4548,19 @@ def _unenforced_rule_tasks(self) -> list[str]: """ if self._scaffold_family() != "fastapi" or self.domain_model is None: return [] + from besser.generators.backend.ocl_invariants import collect_invariants from besser.generators.pydantic_classes.ocl_utils import parse_ocl_constraint from besser.spec_driven_agent.planning.model_rules import deferred_collection_minimum + # The modular backend's database.py checks these before each commit. + checked_at_commit = ({inv["name"] for inv in collect_invariants(self.domain_model)} + if self._generator_used in self._COMMIT_CHECKING_GENERATORS else set()) tasks: list[str] = [] for constraint in list(getattr(self.domain_model, "constraints", None) or []): context = getattr(constraint, "context", None) if context is None or getattr(constraint, "language", "OCL") != "OCL": continue + if constraint.name in checked_at_commit: + continue try: parsed = parse_ocl_constraint(constraint, self.domain_model) except Exception: diff --git a/docs/source/generators/backend.rst b/docs/source/generators/backend.rst index ebb044dd1..cfc02dc0a 100644 --- a/docs/source/generators/backend.rst +++ b/docs/source/generators/backend.rst @@ -311,6 +311,31 @@ For many-to-many relationships, additional endpoints are generated: - Remove a relationship +Model Rules Across Associations +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +An OCL invariant that compares attributes of one record becomes a validator in ``pydantic_classes.py`` (see +:doc:`pydantic`). One that navigates associations needs other records, so ``database.py`` checks it before +each commit instead, and refuses a change that breaks it with HTTP 422 naming the rule: + +.. code-block:: text + + context Result inv LabelBelongsToRequest: + self.request->isEmpty() or self.request.labels->includes(self.label) + context Request inv OneResultPerLabel: + self.results->isUnique(label) + +It checks the records the request loaded or changed and the records directly linked to them, so a change +to a request's labels also re-checks that request's results. + +The rules it can check navigate from ``self`` through attributes and association ends and use +``isEmpty``, ``notEmpty``, ``size``, ``includes``, ``excludes``, ``isUnique``, comparisons of numbers, +strings and booleans, ``and``, ``or``, ``xor``, ``implies``, ``not`` and literals. Any other rule +(``forAll``, ``select``, ``collect``, ``sum``, enumeration literals, dates, …) keeps a ``TODO`` comment +in ``pydantic_classes.py``. So does a minimum on an end whose records each need ``self`` first +(``self.items->notEmpty()`` when every item needs its order): checked at commit, it would refuse creating +the record at all. + Class Methods Endpoints ^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/docs/source/generators/pydantic.rst b/docs/source/generators/pydantic.rst index 879e658f8..0280d65ca 100644 --- a/docs/source/generators/pydantic.rst +++ b/docs/source/generators/pydantic.rst @@ -133,5 +133,8 @@ OCL constraint support details validators. - Constraints that involve collections or relationships (``->size()``, ``->collect()``, ``->sum()``, …) cannot be enforced on a Create payload; the - generator emits an explanatory ``# NOTE:`` comment instead of broken code, and - every emitted validator is syntax-checked before it is written. + generator emits an explanatory ``# TODO:`` comment instead of broken code, and + every emitted validator is syntax-checked before it is written. Under the + :doc:`backend` generator, the ``database.py`` it generates checks many of these + rules before each commit, and the comment says so instead (see "Model Rules + Across Associations" there). diff --git a/tests/generators/backend/test_ocl_invariant_checks.py b/tests/generators/backend/test_ocl_invariant_checks.py new file mode 100644 index 000000000..c9d149a08 --- /dev/null +++ b/tests/generators/backend/test_ocl_invariant_checks.py @@ -0,0 +1,174 @@ +"""OCL invariants that navigate associations, enforced by the generated backend. + +The Pydantic schemas cannot check a rule that needs other rows, so the backend +used to leave a TODO for such a rule and nothing enforced it. The rules here +come from the CaseLens model (a classification request, its labels, and one +result per label), where both were shipped as TODOs: + + context Result inv LabelBelongsToRequest: + self.request->isEmpty() or self.request.labels->includes(self.label) + context Request inv OneResultPerLabel: + self.results->isUnique(label) +""" +import pytest + +from besser.BUML.metamodel.structural import ( + BinaryAssociation, Class, Constraint, DomainModel, IntegerType, Multiplicity, Property, StringType, +) +from besser.generators.backend.ocl_invariants import collect_invariants + +LABEL_BELONGS = ("context Result inv LabelBelongsToRequest: " + "self.request->isEmpty() or self.request.labels->includes(self.label)") +ONE_PER_LABEL = "context Request inv OneResultPerLabel: self.results->isUnique(label)" + + +def _caselens_model(*extra: tuple) -> DomainModel: + request = Class(name="Request", attributes={Property(name="number", type=IntegerType)}) + label = Class(name="Label", attributes={Property(name="name", type=StringType)}) + result = Class(name="Result", attributes={Property(name="score", type=IntegerType)}) + associations = { + BinaryAssociation(name="Labelling", ends={ + Property(name="labels", type=label, multiplicity=Multiplicity(0, "*")), + Property(name="requests", type=request, multiplicity=Multiplicity(0, "*")), + }), + BinaryAssociation(name="Outcome", ends={ + Property(name="request", type=request, multiplicity=Multiplicity(0, 1)), + Property(name="results", type=result, multiplicity=Multiplicity(0, "*")), + }), + BinaryAssociation(name="Labelled", ends={ + Property(name="label", type=label, multiplicity=Multiplicity(1, 1)), + Property(name="label_results", type=result, multiplicity=Multiplicity(0, "*")), + }), + } + classes = {c.name: c for c in (request, label, result)} + constraints = { + Constraint(name=text.split(" inv ")[1].split(":")[0], context=classes[text.split()[1]], + expression=text, language="OCL") + for text in (LABEL_BELONGS, ONE_PER_LABEL) + extra + } + return DomainModel(name="CaseLens", types=set(classes.values()), associations=associations, + constraints=constraints) + + +def _order_model(rule: str) -> DomainModel: + """An order whose items each need their order: an item cannot exist before it.""" + order = Class(name="Order", attributes={Property(name="code", type=StringType)}) + item = Class(name="Item", attributes={Property(name="qty", type=IntegerType)}) + BinaryAssociation(name="Lines", ends={ + Property(name="order", type=order, multiplicity=Multiplicity(1, 1)), + Property(name="items", type=item, multiplicity=Multiplicity(0, "*")), + }) + constraint = Constraint(name="Rule", context=order, expression=rule, language="OCL") + return DomainModel(name="Shop", types={order, item}, associations=set(order.associations), + constraints={constraint}) + + +def _translated(model) -> dict: + return {inv["name"]: inv["python"] for inv in collect_invariants(model)} + + +def test_the_caselens_rules_are_translated(): + assert set(_translated(_caselens_model())) == {"LabelBelongsToRequest", "OneResultPerLabel"} + + +@pytest.mark.parametrize("rule", [ + # A minimum on records that need the order first: no order could ever be created. + "context Order inv Rule: self.items->notEmpty()", + "context Order inv Rule: self.items->size() >= 1", + "context Order inv Rule: not self.items->isEmpty()", + "context Order inv Rule: self.items->isEmpty() = false", + "context Order inv Rule: self.items->isEmpty() implies self.code = 'draft'", + # Outside the translated subset. + "context Order inv Rule: self.items->forAll(i | i.qty > 0)", + "context Order inv Rule: self.items->collect(qty)->sum() < 100", +]) +def test_a_rule_outside_the_subset_is_left_to_the_todo(rule): + assert _translated(_order_model(rule)) == {} + + +def test_a_rule_that_holds_on_empty_parts_is_translated(): + assert set(_translated(_order_model("context Order inv Rule: self.items->isUnique(qty)"))) == {"Rule"} + + +def test_the_schema_no_longer_hands_the_rules_over_as_todos(tmp_path): + from besser.generators.backend import BackendGenerator + BackendGenerator(model=_caselens_model(), output_dir=str(tmp_path)).generate() + schemas = (tmp_path / "pydantic_classes.py").read_text(encoding="utf-8") + assert "TODO: OCL constraint" not in schemas + assert "OCL constraint 'OneResultPerLabel' is enforced when a change is committed (database.py)" in schemas + + +CLIENT = """ + def create(path, body): + response = client.post(path, json=body) + return response.status_code, response.json() + + a = create("/label/", {"name": "a"})[1]["label"]["id"] + b = create("/label/", {"name": "b"})[1]["label"]["id"] + c = create("/label/", {"name": "c"})[1]["label"]["id"] + request = create("/request/", {"number": 1, "labels": [a, b]})[1]["request"]["id"] + results = { + "inside": create("/result/", {"score": 1, "request": request, "label": a}), + "outside": create("/result/", {"score": 1, "request": request, "label": c}), + "second_for_label": create("/result/", {"score": 1, "request": request, "label": a}), + "no_request": create("/result/", {"score": 1, "label": c}), + } + # Removing label a from the request would leave its result outside the request. + shrink = client.put(f"/request/{request}/", json={"number": 1, "labels": [b]}) + after_shrink = client.get(f"/request/{request}/").json()["label_ids"] + keep =client.put(f"/request/{request}/", json={"number": 2, "labels": [a, b, c]}) + print(json.dumps({ + "status": {name: status for name, (status, _) in results.items()}, + "detail": {name: body.get("detail") for name, (_, body) in results.items()}, + "shrink": [shrink.status_code, shrink.json().get("detail")], + "keep": keep.status_code, + "results": len(client.get("/result/").json()), + "labels_after_shrink": sorted(after_shrink), + "labels": [a, b], + })) +""" + + +@pytest.fixture(scope="module") +def outcome(tmp_path_factory): + import json + import subprocess + import sys + import textwrap + from besser.generators.backend import BackendGenerator + from tests.generators.backend.conftest import _PREAMBLE + + pytest.importorskip("fastapi") + pytest.importorskip("httpx") + out = tmp_path_factory.mktemp("ocl_invariants") + BackendGenerator(model=_caselens_model(), output_dir=str(out)).generate() + run = subprocess.run([sys.executable, "-c", _PREAMBLE + textwrap.dedent(CLIENT)], cwd=str(out), + capture_output=True, text=True, timeout=120) + assert run.returncode == 0, run.stderr + return json.loads(run.stdout.strip().splitlines()[-1]) + + +def test_a_result_for_a_label_of_its_request_is_created(outcome): + assert outcome["status"]["inside"] == 200 + assert outcome["status"]["no_request"] == 200 + + +def test_a_result_for_a_label_outside_its_request_is_refused(outcome): + assert outcome["status"]["outside"] == 422 + assert "LabelBelongsToRequest" in outcome["detail"]["outside"] + + +def test_a_second_result_for_the_same_label_is_refused(outcome): + assert outcome["status"]["second_for_label"] == 422 + assert "OneResultPerLabel" in outcome["detail"]["second_for_label"] + + +def test_a_change_on_the_other_side_is_checked_too(outcome): + assert outcome["shrink"][0] == 422 + assert "LabelBelongsToRequest" in outcome["shrink"][1] + assert outcome["keep"] == 200 + + +def test_a_refused_change_leaves_nothing_behind(outcome): + assert outcome["results"] == 2 + assert outcome["labels_after_shrink"] == sorted(outcome["labels"]) diff --git a/tests/spec_driven_agent/test_ocl_rule_seed.py b/tests/spec_driven_agent/test_ocl_rule_seed.py index c07ef73ae..84107d8f3 100644 --- a/tests/spec_driven_agent/test_ocl_rule_seed.py +++ b/tests/spec_driven_agent/test_ocl_rule_seed.py @@ -156,7 +156,46 @@ def test_an_exact_size_keeps_its_upper_bound_enforced(tmp_path): ]) def test_every_other_collection_rule_is_still_enforced(tmp_path, expression, book_needs_library, books_in_one_library): - seeds = _seeds(_library(expression, book_needs_library, books_in_one_library), tmp_path) + """On the plain REST API, which has no check at commit (see the tests at the end).""" + seeds = _seeds(_library(expression, book_needs_library, books_in_one_library), tmp_path, + generator_used="generate_rest_api") assert len(seeds) == 1, seeds assert "create and update endpoints of routers/library.py" in seeds[0] assert "HTTP 400" in seeds[0] + + +def _requests(rule: str): + """A request and its results, one per label (the CaseLens model).""" + request = Class(name="Request") + request.attributes = {Property(name="number", type=PrimitiveDataType("int"))} + result = Class(name="Result") + result.attributes = {Property(name="label", type=PrimitiveDataType("str"))} + outcome = BinaryAssociation(name="Outcome", ends={ + Property(name="request", type=request, multiplicity=Multiplicity(0, 1)), + Property(name="results", type=result, multiplicity=Multiplicity(0, "*")), + }) + model = DomainModel(name="CaseLens", types={request, result}, associations={outcome}) + model.constraints = {Constraint(name="OneResultPerLabel", context=request, expression=rule, language="OCL")} + return model + + +@pytest.mark.parametrize("generator_used", ["generate_fastapi_backend", "generate_web_app"]) +def test_a_rule_the_backend_checks_at_commit_is_not_seeded(tmp_path, generator_used): + """The modular backend's database.py refuses a commit that breaks this rule.""" + model = _requests("context Request inv OneResultPerLabel: self.results->isUnique(label)") + assert _seeds(model, tmp_path, generator_used=generator_used) == [] + + +def test_the_plain_rest_api_has_no_commit_check_so_the_rule_is_seeded(tmp_path): + model = _requests("context Request inv OneResultPerLabel: self.results->isUnique(label)") + seeds = _seeds(model, tmp_path, generator_used="generate_rest_api") + assert len(seeds) == 1 and "OneResultPerLabel" in seeds[0] + + +@pytest.mark.parametrize("book_needs_library, books_in_one_library", [(False, True), (True, False)]) +def test_a_minimum_the_create_can_meet_is_checked_at_commit_not_seeded(tmp_path, book_needs_library, + books_in_one_library): + """The Books can exist before the Library, so the backend refuses a Library without one.""" + model = _library("context Library inv books_at_least_1: self.books->size() >= 1", + book_needs_library, books_in_one_library) + assert _seeds(model, tmp_path) == [] From 733f648eea248b5b783dcd19c56701b0ff24b37d Mon Sep 17 00:00:00 2001 From: ArmSL Date: Fri, 4 Dec 2026 13:16:16 +0100 Subject: [PATCH 2/2] fix(backend): review fixes for the commit-time OCL checks - A minimum on an end whose records each need a record of the rule's class keeps its TODO whatever that end's upper bound: with "one or more" it made the first record impossible to create. - size(), isEmpty() and the other collection operations on a string keep their TODO; size() of a string was checked as a collection of one. - isUnique by an end with several records per element keeps its TODO. - An ordering comparison that meets an empty value leaves the rule undefined for that record instead of a TypeError being caught and logged; other errors are no longer swallowed. - The check covers the records a change writes (and those a changed or deleted link pointed to), not every record the request loaded, and loads links in batches: SQL statements per write no longer grow with the data (808 -> 35 for a label linked to 400 requests). - The "checked at commit" note is written only by BackendGenerator, which generates the database.py that checks it. --- .../generators/backend/backend_generator.py | 3 +- besser/generators/backend/ocl_invariants.py | 29 ++-- .../backend/templates/database.py.j2 | 124 ++++++++++++++---- .../pydantic_classes_generator.py | 7 +- docs/source/generators/backend.rst | 21 +-- .../backend/test_ocl_invariant_checks.py | 88 ++++++++++++- tests/spec_driven_agent/test_ocl_rule_seed.py | 6 +- 7 files changed, 227 insertions(+), 51 deletions(-) diff --git a/besser/generators/backend/backend_generator.py b/besser/generators/backend/backend_generator.py index 0275b2606..0db9e6838 100644 --- a/besser/generators/backend/backend_generator.py +++ b/besser/generators/backend/backend_generator.py @@ -148,7 +148,8 @@ def generate(self): sql_alchemy = SQLAlchemyGenerator(model=self.model, output_dir=backend_folder_path) sql_alchemy.generate() - pydantic_model = PydanticGenerator(model=self.model, output_dir=backend_folder_path, backend=True, nested_creations=self.nested_creations) + pydantic_model = PydanticGenerator(model=self.model, output_dir=backend_folder_path, backend=True, nested_creations=self.nested_creations, + rules_checked_at_commit=True) pydantic_model.generate() # The files of the generators this one is built from, by path in the output folder. diff --git a/besser/generators/backend/ocl_invariants.py b/besser/generators/backend/ocl_invariants.py index 5c9ef8fd9..7e6bfe9a7 100644 --- a/besser/generators/backend/ocl_invariants.py +++ b/besser/generators/backend/ocl_invariants.py @@ -12,8 +12,11 @@ ``sum``, enumeration literals, dates) keeps its TODO. One kind of rule inside the subset keeps its TODO too: one that can fail while an end of ``self`` -whose records each need ``self`` first is still empty (``self.items->notEmpty()`` when every item -needs its order). Enforced at commit, it would refuse creating the record at all. +whose records each need a record of ``self``'s class is still empty (``self.items->notEmpty()`` +when every item needs an order). Enforced at commit, it would refuse creating the first record. + +An ordering comparison (``<``, ``<=``, ``>``, ``>=``) that meets an empty value leaves the rule +undefined, and it is not applied to that record; ``=`` and ``<>`` compare an empty value as ``null``. """ import ast @@ -51,7 +54,7 @@ ast.Expression, ast.BoolOp, ast.UnaryOp, ast.Compare, ast.Call, ast.Name, ast.Constant, ast.Load, ast.And, ast.Or, ast.Not, ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE, ast.In, ast.NotIn, ) -_ALLOWED_NAMES = {"obj", "len", "_nav", "_coll", "_is_unique"} +_ALLOWED_NAMES = {"obj", "len", "_nav", "_coll", "_is_unique", "_cmp"} class _Unsupported(Exception): @@ -133,7 +136,7 @@ class _Translator: """Walks a B-OCL tree into Python; each step returns ``(code, kind, element class)``. ``kind`` is ``"bool"``, ``"num"``, ``"str"``, ``"obj"`` (at most one record), ``"objs"`` - (records) or ``"other"``; the element + (records), ``"vals"`` (attribute values of several records) or ``"other"``; the element class is the class of the records a navigation yields, for ``isUnique``'s key. """ @@ -166,14 +169,15 @@ def _property_call(self, node: PropertyCallExpression): code, step_kind, element = self._navigate(base, owner, node.property, from_self=False) # Navigating from several records collects from each of them, as OCL does. if kind == "objs": - step_kind = "objs" if step_kind in ("obj", "objs") else "other" + step_kind = "objs" if step_kind in ("obj", "objs") else "vals" return code, step_kind, element def _navigate(self, base: str, owner: Class, prop: Property, from_self: bool): end = next((e for e in owner.all_association_ends() if e.name == prop.name), None) if end is not None: opposite = end.opposite_end() - if from_self and opposite.multiplicity.min >= 1 and opposite.multiplicity.max == 1: + # Each record there needs one of ``self``'s class, so none exists before the first ``self``. + if from_self and opposite.multiplicity.min >= 1: self.part_ends.add(end.name) kind = "objs" if end.multiplicity.max > 1 else "obj" return f"_nav({base}, {end.name!r})", kind, end.type @@ -214,12 +218,16 @@ def _comparison(self, op: str, args: list): identity = left_kind == right_kind == "obj" and op in ("=", "<>") if not (same or identity): raise _Unsupported(f"comparison of {left_kind} and {right_kind}") - return f"({left} {_COMPARISONS[op]} {right})", "bool", None + if op in ("=", "<>"): + return f"({left} {_COMPARISONS[op]} {right})", "bool", None + return f"_cmp({left}, {_COMPARISONS[op]!r}, {right})", "bool", None def _collection(self, op: str, source, args: list): if source is None: raise _Unsupported(f"{op} without a source") - items, _, element = self.expr(source) + items, kind, element = self.expr(source) + if kind not in ("obj", "objs", "vals"): # String::size() is a length, not a collection's size + raise _Unsupported(f"{op} on a {kind}") items = f"_coll({items})" if op == "isempty": return f"(len({items}) == 0)", "bool", None @@ -231,8 +239,9 @@ def _collection(self, op: str, source, args: list): key = args[0] if args else None name = key.name if isinstance(key, (VariableExp, Property)) else None features = set() - if element is not None: - features = {a.name for a in element.all_attributes()} | {e.name for e in element.all_association_ends()} + if element is not None: # a key with several values per record has no single value to compare + features = ({a.name for a in element.all_attributes()} + | {e.name for e in element.all_association_ends() if e.multiplicity.max == 1}) if name not in features: raise _Unsupported("isUnique key") return f"_is_unique({items}, {name!r})", "bool", None diff --git a/besser/generators/backend/templates/database.py.j2 b/besser/generators/backend/templates/database.py.j2 index 92596ad7d..ee6056764 100644 --- a/besser/generators/backend/templates/database.py.j2 +++ b/besser/generators/backend/templates/database.py.j2 @@ -7,7 +7,9 @@ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sql_alchemy import Base, _configure_sqlite_engine {% if invariants %} -from sqlalchemy import event, inspect as sa_inspect +import operator +from sqlalchemy import event, inspect as sa_inspect, select +from sqlalchemy.orm import selectinload import sql_alchemy as _models {% endif %} @@ -127,56 +129,134 @@ def _is_unique(records, name): return len(keys) == len(set(keys)) +_ORDER = {"<": operator.lt, "<=": operator.le, ">": operator.gt, ">=": operator.ge} + + +class _Undefined(Exception): + """An ordering comparison met an empty value: OCL leaves the rule undefined for that record.""" + + +def _cmp(left, op, right): + if left is None or right is None: + raise _Undefined + return _ORDER[op](left, right) + + def _gone(record): state = sa_inspect(record) return state.deleted or state.detached or state.was_deleted +def _related(relationship): + target = relationship.mapper.class_ + return any(issubclass(target, cls) or issubclass(cls, target) for cls in _RULE_CLASSES) + + def _neighbours(record): """The records directly linked to ``record`` that a rule may be about.""" for relationship in sa_inspect(record).mapper.relationships: - target = relationship.mapper.class_ - if any(issubclass(target, cls) or issubclass(cls, target) for cls in _RULE_CLASSES): + if _related(relationship): + yield from _coll(getattr(record, relationship.key)) + + +def _linked(records): + """Every record directly linked to one of ``records``.""" + for record in records: + for relationship in sa_inspect(record).mapper.relationships: yield from _coll(getattr(record, relationship.key)) +def _preload(session, records): + """Load the links of ``records`` with a few queries per class, not one per record and link.""" + ids = {} + for record in records: + state = sa_inspect(record) + if state.identity is not None and len(state.identity) == 1 and not _gone(record): + ids.setdefault(state.mapper, set()).add(state.identity[0]) + for mapper, keys in ids.items(): + keys = sorted(keys, key=repr) + for start in range(0, len(keys), 500): + session.execute( + select(mapper.class_).where(mapper.primary_key[0].in_(keys[start:start + 500])) + .options(selectinload("*")).execution_options(populate_existing=True) + ).scalars().all() + + +def _former_links(session, record): + """``(class, key)`` of each record a changed foreign key of ``record`` pointed to: losing the + link may break a rule of that record.""" + state = sa_inspect(record) + for relationship in state.mapper.relationships: + if relationship.direction.name != "MANYTOONE" or len(relationship.local_columns) != 1: + continue + if not _related(relationship): + continue + column = next(iter(relationship.local_columns)) + attribute = state.mapper.get_property_by_column(column).key + for old in state.attrs[attribute].history.deleted: + if old is not None: + yield relationship.mapper.class_, old + + @event.listens_for(SessionLocal, "before_flush") -def _remember_links_of_deleted(session, flush_context, instances): - """A deleted record takes its links with it: keep the records it was linked to, to check them.""" - remembered = session.info.setdefault("ocl_linked_to_deleted", []) +def _remember_changes(session, flush_context, instances): + """Keep the records this flush writes, those a deleted record was linked to, and those a + changed link pointed to: the rules are checked on them at commit.""" + changed = session.info.setdefault("ocl_changed", []) + changed.extend(session.new) + changed.extend(session.dirty) + former = session.info.setdefault("ocl_former_links", set()) + for record in session.dirty: + former.update(_former_links(session, record)) for record in session.deleted: - remembered.extend(_neighbours(record)) + changed.extend(_neighbours(record)) + + +@event.listens_for(SessionLocal, "do_orm_execute") +def _remember_link_writes(state): + """Links written with SQL statements (many-to-many) are not on any changed record: note the table.""" + table = getattr(state.statement, "table", None) + if (state.is_insert or state.is_delete or state.is_update) and table is not None: + state.session.info.setdefault("ocl_link_tables", set()).add(table.name) @event.listens_for(SessionLocal, "before_commit") def _check_invariants(session): - """Refuse a commit (HTTP 422) that leaves a record it touched, or one linked to it, breaking a rule. + """Refuse a commit (HTTP 422) that leaves a record it changed, or one linked to it, breaking a rule. - Checks reach one link away from what the request loaded or changed: a rule that a change - further away breaks is not caught. + Checks reach one link away from what the request changed: a rule that a change further + away breaks is not caught. """ session.flush() - touched = list(session.identity_map.values()) + session.info.pop("ocl_linked_to_deleted", []) + changed = session.info.pop("ocl_changed", []) + former = session.info.pop("ocl_former_links", set()) + link_tables = session.info.pop("ocl_link_tables", set()) + if link_tables: + changed.extend( + record for record in session.identity_map.values() + if any(r.secondary is not None and r.secondary.name in link_tables + for r in sa_inspect(record).mapper.relationships) + ) # Links written with SQL statements are not in the loaded collections: read them again. session.expire_all() - records = {} - for record in touched: - if _gone(record): - continue - records[id(record)] = record - for neighbour in _neighbours(record): - if not _gone(neighbour): - records[id(neighbour)] = neighbour + changed.extend(record for record in (session.get(cls, key) for cls, key in former) if record is not None) + records = {id(record): record for record in changed if not _gone(record)} + _preload(session, records.values()) + neighbours = {id(n): n for record in records.values() for n in _neighbours(record) + if id(n) not in records and not _gone(n)} + _preload(session, neighbours.values()) + # A rule of a neighbour may read one link further: load those links in one go too. + _preload(session, _linked(neighbours.values())) + records.update(neighbours) for record in records.values(): for cls, name, ocl, check in OCL_INVARIANTS: if not isinstance(record, cls): continue - key = ", ".join(str(part) for part in sa_inspect(record).identity or ()) try: holds = check(record) - except TypeError: # an ordering comparison with an empty value: OCL leaves it undefined - logger.warning("Rule %s could not be evaluated on %s %s", name, type(record).__name__, key) + except _Undefined: continue if not holds: + key = ", ".join(str(part) for part in sa_inspect(record).identity or ()) raise HTTPException(status_code=422, detail=f"{type(record).__name__} {key} breaks the rule {name}: {ocl}") {% endif %} diff --git a/besser/generators/pydantic_classes/pydantic_classes_generator.py b/besser/generators/pydantic_classes/pydantic_classes_generator.py index 6625d58d0..437ce2980 100644 --- a/besser/generators/pydantic_classes/pydantic_classes_generator.py +++ b/besser/generators/pydantic_classes/pydantic_classes_generator.py @@ -42,9 +42,12 @@ class PydanticGenerator(GeneratorInterface): """ regenerable = True - def __init__(self, model: DomainModel, backend: bool = False, nested_creations: bool = False, output_dir: str = None): + def __init__(self, model: DomainModel, backend: bool = False, nested_creations: bool = False, output_dir: str = None, + rules_checked_at_commit: bool = False): super().__init__(model, output_dir) self.backend = backend + # Set by BackendGenerator, whose database.py checks the rules collect_invariants translates. + self.rules_checked_at_commit = rules_checked_at_commit self.nested_creations = nested_creations def _note_rules_checked_at_commit(self, constraints_map: dict) -> None: @@ -110,7 +113,7 @@ def ascii_identifier(name: str) -> str: constraints_map = build_constraints_map( self.domain_model, include_model_level=True, include_skipped=True ) - if self.backend: + if self.rules_checked_at_commit: self._note_rules_checked_at_commit(constraints_map) class_names = {cls.name for cls in sorted_classes} diff --git a/docs/source/generators/backend.rst b/docs/source/generators/backend.rst index cfc02dc0a..386ef6008 100644 --- a/docs/source/generators/backend.rst +++ b/docs/source/generators/backend.rst @@ -325,16 +325,21 @@ each commit instead, and refuses a change that breaks it with HTTP 422 naming th context Request inv OneResultPerLabel: self.results->isUnique(label) -It checks the records the request loaded or changed and the records directly linked to them, so a change -to a request's labels also re-checks that request's results. +It checks the records the request changed and the records directly linked to them, so a change to a +request's labels also re-checks that request's results. A record that already breaks a rule (for example +in a database created before the rule was added) is refused again on any change that touches it or a +record linked to it. The rules it can check navigate from ``self`` through attributes and association ends and use -``isEmpty``, ``notEmpty``, ``size``, ``includes``, ``excludes``, ``isUnique``, comparisons of numbers, -strings and booleans, ``and``, ``or``, ``xor``, ``implies``, ``not`` and literals. Any other rule -(``forAll``, ``select``, ``collect``, ``sum``, enumeration literals, dates, …) keeps a ``TODO`` comment -in ``pydantic_classes.py``. So does a minimum on an end whose records each need ``self`` first -(``self.items->notEmpty()`` when every item needs its order): checked at commit, it would refuse creating -the record at all. +``isEmpty``, ``notEmpty``, ``size``, ``includes``, ``excludes``, ``isUnique`` (on an attribute or a +single-valued end), comparisons of numbers, strings and booleans, ``and``, ``or``, ``xor``, ``implies``, +``not`` and literals. An ordering comparison (``<``, ``<=``, ``>``, ``>=``) that meets an empty +value leaves the rule undefined, so it is not applied to that record; ``=`` and ``<>`` treat an empty +value as ``null``. Any other rule +(``forAll``, ``select``, ``collect``, ``sum``, the length of a string, enumeration literals, dates, …) +keeps a ``TODO`` comment in ``pydantic_classes.py``. So does a minimum on an end whose records each need +a record of the rule's class (``self.items->notEmpty()`` when every item needs an order): checked at +commit, it would refuse creating the first record. Class Methods Endpoints ^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/generators/backend/test_ocl_invariant_checks.py b/tests/generators/backend/test_ocl_invariant_checks.py index c9d149a08..be136a433 100644 --- a/tests/generators/backend/test_ocl_invariant_checks.py +++ b/tests/generators/backend/test_ocl_invariant_checks.py @@ -50,15 +50,16 @@ def _caselens_model(*extra: tuple) -> DomainModel: constraints=constraints) -def _order_model(rule: str) -> DomainModel: - """An order whose items each need their order: an item cannot exist before it.""" +def _order_model(rule: str, orders_per_item=1) -> DomainModel: + """An order whose items each need an order: no item can exist before the first order.""" order = Class(name="Order", attributes={Property(name="code", type=StringType)}) item = Class(name="Item", attributes={Property(name="qty", type=IntegerType)}) BinaryAssociation(name="Lines", ends={ - Property(name="order", type=order, multiplicity=Multiplicity(1, 1)), + Property(name="order", type=order, multiplicity=Multiplicity(1, orders_per_item)), Property(name="items", type=item, multiplicity=Multiplicity(0, "*")), }) - constraint = Constraint(name="Rule", context=order, expression=rule, language="OCL") + context = {"Order": order, "Item": item}[rule.split()[1]] + constraint = Constraint(name="Rule", context=context, expression=rule, language="OCL") return DomainModel(name="Shop", types={order, item}, associations=set(order.associations), constraints={constraint}) @@ -86,6 +87,22 @@ def test_a_rule_outside_the_subset_is_left_to_the_todo(rule): assert _translated(_order_model(rule)) == {} +def test_a_minimum_on_items_that_need_one_of_several_orders_is_left_to_the_todo(): + """Review of #877: each item needs at least one order, so the first order could never be created.""" + assert _translated(_order_model("context Order inv Rule: self.items->size() >= 1", orders_per_item="*")) == {} + + +def test_the_size_of_a_string_is_left_to_the_todo(): + """Review of #877: ``size()`` of a string is its length, which was checked as a collection of one.""" + assert _translated(_order_model("context Item inv Rule: self.order.code.size() = 3")) == {} + + +def test_uniqueness_by_an_end_with_several_records_is_left_to_the_todo(): + """Review of #877: a key with several values per record has no single value to compare.""" + model = _caselens_model("context Label inv ByLabels: self.requests->isUnique(labels)") + assert "ByLabels" not in _translated(model) + + def test_a_rule_that_holds_on_empty_parts_is_translated(): assert set(_translated(_order_model("context Order inv Rule: self.items->isUnique(qty)"))) == {"Rule"} @@ -172,3 +189,66 @@ def test_a_change_on_the_other_side_is_checked_too(outcome): def test_a_refused_change_leaves_nothing_behind(outcome): assert outcome["results"] == 2 assert outcome["labels_after_shrink"] == sorted(outcome["labels"]) + + +COST_CLIENT = """ + from sqlalchemy import event + import database + + statements = {"n": 0} + event.listen(database.SessionLocal.kw["bind"], "before_cursor_execute", + lambda *args: statements.__setitem__("n", statements["n"] + 1)) + + def count(call): + statements["n"] = 0 + status = call().status_code + return status, statements["n"] + + a = client.post("/label/", json={"name": "a"}).json()["label"]["id"] + sizes = {} + for total in (3, 30): + while len(client.get("/request/").json()) < total: + n = len(client.get("/request/").json()) + 1 + request = client.post("/request/", json={"number": n, "labels": [a]}).json()["request"]["id"] + client.post("/result/", json={"score": 1, "request": request, "label": a}) + sizes[total] = { + "rename": count(lambda: client.put(f"/label/{a}/", json={"name": f"a{total}"})), + "create": count(lambda: client.post("/result/", json={"score": 1, "label": a})), + } + print(json.dumps(sizes)) +""" + + +def test_the_check_costs_the_same_however_many_records_are_linked(tmp_path): + """Review of #877: renaming a label linked to 400 requests ran 808 statements, one per record and link. + + The extra rule compares with the number of a request a result may not have: with none, the rule + does not apply (``not`` must not turn the undefined comparison into a refusal). + """ + import json + import subprocess + import sys + import textwrap + from besser.generators.backend import BackendGenerator + from tests.generators.backend.conftest import _PREAMBLE + + pytest.importorskip("fastapi") + pytest.importorskip("httpx") + model = _caselens_model("context Result inv WithinNumber: not (self.score > self.request.number)") + BackendGenerator(model=model, output_dir=str(tmp_path)).generate() + run = subprocess.run([sys.executable, "-c", _PREAMBLE + textwrap.dedent(COST_CLIENT)], cwd=str(tmp_path), + capture_output=True, text=True, timeout=180) + assert run.returncode == 0, run.stderr + sizes = json.loads(run.stdout.strip().splitlines()[-1]) + assert sizes["3"]["rename"][0] == sizes["30"]["rename"][0] == 200 + assert sizes["3"]["create"][0] == sizes["30"]["create"][0] == 200 + assert sizes["30"]["rename"][1] == sizes["3"]["rename"][1] + assert sizes["30"]["create"][1] == sizes["3"]["create"][1] + + +def test_pydantic_schemas_on_their_own_keep_the_todo(tmp_path): + """Review of #877: without the backend's database.py nothing checks the rule, whatever ``backend`` says.""" + from besser.generators.pydantic_classes import PydanticGenerator + PydanticGenerator(model=_caselens_model(), backend=True, output_dir=str(tmp_path)).generate() + schemas = (tmp_path / "pydantic_classes.py").read_text(encoding="utf-8") + assert "TODO: OCL constraint 'OneResultPerLabel'" in schemas diff --git a/tests/spec_driven_agent/test_ocl_rule_seed.py b/tests/spec_driven_agent/test_ocl_rule_seed.py index 84107d8f3..bbfc17f33 100644 --- a/tests/spec_driven_agent/test_ocl_rule_seed.py +++ b/tests/spec_driven_agent/test_ocl_rule_seed.py @@ -192,10 +192,8 @@ def test_the_plain_rest_api_has_no_commit_check_so_the_rule_is_seeded(tmp_path): assert len(seeds) == 1 and "OneResultPerLabel" in seeds[0] -@pytest.mark.parametrize("book_needs_library, books_in_one_library", [(False, True), (True, False)]) -def test_a_minimum_the_create_can_meet_is_checked_at_commit_not_seeded(tmp_path, book_needs_library, - books_in_one_library): +def test_a_minimum_the_create_can_meet_is_checked_at_commit_not_seeded(tmp_path): """The Books can exist before the Library, so the backend refuses a Library without one.""" model = _library("context Library inv books_at_least_1: self.books->size() >= 1", - book_needs_library, books_in_one_library) + book_needs_library=False) assert _seeds(model, tmp_path) == []