Skip to content

feat(backend): check relational OCL invariants before each commit - #877

Draft
ArmenSl wants to merge 2 commits into
developmentfrom
feat/relational-ocl-router-checks
Draft

ArmenSl wants to merge 2 commits into
developmentfrom
feat/relational-ocl-router-checks

Conversation

@ArmenSl

@ArmenSl ArmenSl commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Why

The Pydantic schemas only see one request payload. So an OCL invariant that navigates associations was skipped, and the generated backend shipped it as a TODO comment that nothing enforced. Found on the CaseLens model: both of these were TODOs, and the generated API accepted every violation.

context DocumentLabelResult inv LabelBelongsToRequest:
    self.document_classification_request->isEmpty() or
    self.document_classification_request.document_labels->includes(self.document_label)
context DocumentClassificationRequest inv OneResultPerLabel:
    self.document_label_results->isUnique(document_label)

What

  • besser/generators/backend/ocl_invariants.py (new) translates these invariants into Python expressions, working from the B-OCL parse tree. It only takes rules the Pydantic path skips, so no rule is checked twice. Every expression is screened against an AST whitelist before it's emitted.
    • Supported: navigation from self through attributes and ends; isEmpty, notEmpty, size, includes, excludes on collections; isUnique by an attribute or a single-valued end; comparisons of numbers, strings and booleans; and, or, xor, implies, not; literals.
    • Still a TODO: everything else (forAll, select, collect, sum, the length of a string, enums, dates).
    • Also still a TODO: a rule that can fail while an end whose records each need a record of the rule's class is still empty, e.g. self.items->notEmpty() when every item needs one order, or one or more. Checked at commit, it would make the first record impossible to create.
    • An ordering comparison (<, >, ...) that meets an empty value leaves the rule undefined, so it isn't applied to that record. = and <> treat an empty value as null.
  • Generated database.py, only when a model has such rules: a before_commit listener flushes and re-reads the changed records, so link rows written by Core insert()/delete() count. It evaluates each rule on the records the change writes, the records a changed or deleted link pointed to, and their direct neighbours. It loads their links in batches, so the number of SQL statements per write doesn't grow with the data. It refuses the commit with HTTP 422 naming the rule (get_db rolls back). The check lives in database.py, not a new file, so the Dockerfile and deploy file lists don't change.
  • pydantic_classes.py: for these rules, the TODO becomes OCL constraint 'X' is enforced when a change is committed (database.py). Only BackendGenerator asks for this note; Pydantic generated on its own keeps the TODO.
  • Spec-Driven Agent: _unenforced_rule_tasks no longer seeds an "Enforce the modeled rule" task for a rule that database.py checks. That applies only to generate_fastapi_backend and generate_web_app; the plain generate_rest_api has no database.py, so it still gets the task.
  • Docs: a "Model Rules Across Associations" section in generators/backend.rst, and a pointer to it from pydantic.rst.

Known limit

  • The check reaches one link from what the request changed. A rule broken by a change two or more links away is not caught.
  • A record that already breaks a rule, for example in a database created before the rule was added, is refused on any change that touches it or a record linked to it.

Both are documented in generators/backend.rst.

Tests

  • tests/generators/backend/test_ocl_invariant_checks.py generates the CaseLens rules into a backend and drives the real API. A result for a label outside its request gets 422. So does a second result for the same label, and so does removing a label that a result still uses (the other-side change). A refused change leaves nothing behind. Before this change, all four violations returned 200, and 4 results were stored instead of 2.
  • Translator cases: minima on part ends (including isEmpty() = false and implies), plus forAll and collect()->sum(), stay TODOs.
  • tests/spec_driven_agent/test_ocl_rule_seed.py: a commit-checked rule is not seeded on the FastAPI backend or the web app, and is seeded on the plain REST API. The existing "still enforced" cases now run against the plain REST API, because on the other two scaffolds the backend enforces those rules itself.
  • Review fixes (second commit), each with a test that fails on the first commit:
    • a minimum on an end whose records need one or more of the rule's class (the first record could never be created);
    • size() of a string;
    • isUnique by a many-valued end;
    • statement count for a label rename and a result create, the same with 3 and 30 linked requests (was 808 statements at 400);
    • Pydantic generated on its own keeps the TODO.
  • The agent seeding test that expected the "one or more" minimum to be checked at commit now covers only the case where the records can exist first.
  • Local runs:
    • tests/generators tests/spec_driven_agent tests/utilities: 15026 passed. 4 failed, and the same 4 fail on unchanged development on this machine (no javac, and no ruff on the test venv's PATH).
    • ruff check besser/ passes, lint-imports keeps all 4 contracts, and docs/check_docs.py --offline passes.

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).
- 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant