2026-09-14 13:25:06 -06:00
2026-09-08 18:36:40 -06:00
2026-09-14 13:25:06 -06:00
2026-09-08 17:57:51 -06:00
2026-08-28 13:04:26 -06:00
2026-09-14 13:25:06 -06:00
2026-09-08 17:57:51 -06:00

ps_core

Generates, from a folder of YAML spec files:

  • schema.py — a permissive SQLAlchemy storage layer. Every non-primary-key column is nullable, regardless of what the Pydantic contract requires — a row that fails a rule is still saved and flagged, never rejected by the database.
  • validation.py — a Pydantic "check" class per table. Every field is Optional[T] = None; "required" is just one rule among several, applied by that field's own generated checker function. Every rule raises a generic, parameterized message — see "Field rules" below.
  • enums.py — one plain str, Enum class per enum. Normalizing input and checking membership both happen in validation.py, not here.
  • data_dictionary.md — a readable table-by-table reference of every field's SQL type, rule set, foreign key, and required status, plus a plain-English list of each table's cross-field rules.

A separate ps_core.runtime package (not code generation) provides the functions used at data-load time: load_row, validate_row, ingest, and check_foreign_keys.

Spec directory layout

spec_dir/
    enums.yaml          # optional
    cross_rules.yaml    # optional
    tables/
        *.yaml           # required, one file per table

See spec/ in this repo for a small worked example.

Field rules

A field is optional at every layer. It activates a rule by giving it a truthy value (or, for regex/max_length, the parameter itself — the value doubles as the flag):

fields:
    pac_id_hospital:
        type: text
        required: true
        strip: true
        upper: true
    pac_codigo_postal_vigente:
        type: text
        regex: "\\d{5}"
    edad_meses:
        type: float
        range: true
        min: 16.0
        max: 36.0

Rules apply in a fixed order, regardless of the order written in YAML: strip → upper → required → max_length → regex → range → not_future. Which rules are legal depends on the field's type:

type legal rules (besides required)
text strip, upper, regex, max_length
integer, float range (needs min/max)
date not_future
datetime, bool, enum (none — required only)
uuid strip

enum fields always strip + uppercase + check membership.

Messages are generic, not per-field. There is no <rule>_message key in the spec YAML. Each rule raises a message built from the field's own name (its label), by the matching function in constraints.py — matching this shape:

def check_range(v, lo, hi, label="value"):
    if v < lo or v > hi:
        raise ValueError(f"{label} must be between {lo} and {hi}, got {v}")
    return v

To change the wording for every field that uses a given rule — across the whole project — edit that one function in constraints.py. This keeps customization in one place, in code, rather than repeated in every field's YAML.

Using a rule the field's type doesn't support raises ValueError at parse time, naming the file, field, and rule — nothing is silently ignored.

Foreign keys

owner_id:
    type: uuid
    required: true
    foreign_key: users.id

Checked at parse time (the target table and column must exist) but never turned into a database constraint — a bad link is not allowed to block an insert. Call ps_core.runtime.check_foreign_keys after your insert batch to flag orphans the same way any other rule gets flagged (validated=False, errors updated).

Uniqueness

email:
    type: text
    unique: true

Same philosophy as foreign keys, on purpose: never a database UNIQUE constraint, since that could silently reject a row outright rather than let it be saved and flagged. Call ps_core.runtime.check_unique_fields after your insert batch — it flags every row sharing a duplicate value on that column (a NULL is never treated as a duplicate of another NULL), the same way check_foreign_keys flags orphans.

This checks single-column uniqueness only. There is no unique_together for multi-column uniqueness.

Cross-field rules (cross_rules.yaml)

Table name → list of rules, each a fixed, named kind — never a raw condition string. Every field a rule mentions must exist on that table, checked at parse time.

kind required keys checks
order fields: [a, b], op: le|lt|ge|gt a <op> b
equals fields: [a, b] a == b
sum_equals target, parts: [...] target == sum(parts), optional tolerance
ratio_equals target, numerator, denominator target == numerator / denominator**power, optional power (default 1), tolerance
date_offset_equals base, offset_days_field, target target == base + timedelta(days=offset_days_field), optional tolerance_days
date_diff_equals start, end, target target == (end - start).days, optional tolerance_days
comparison_equals target, left, op target == (left <op> right); exactly one of right (a field) or right_value (a literal)
piecewise_lookup source, target, breakpoints, otherwise target matches the bucket source falls into — see below
requires if_field, then_field if the if-condition holds, then_field is set (and optionally equals then_value)
forbidden_if if_field, then_fields: [...] if the if-condition holds, every field in then_fields must be None (or in then_allowed_values)
any_of_implies target, conditions: [...] target == True if any condition holds, else False
conditional_equals if_field, target, value_if_true, value_if_false target equals one of two values depending on the if-condition

All optional keys accept message to override the generated default.

The if-condition language, shared by requires, forbidden_if, and conditional_equals:

  • no if_value → if_field must be truthy
  • scalar if_value → if_field must equal it
  • list if_value → if_field must be a member
  • if_op (eq/lt/le/gt/ge) + numeric if_value → that comparison

A string if_value/then_value/then_allowed_values compared against an enum field is uppercased automatically, so if_value: severa in YAML correctly matches the stored SEVERA — write YAML values in whatever case reads naturally.

piecewise_lookup breakpoints, ascending and non-overlapping:

- kind: piecewise_lookup
  source: edad_meses
  target: ventana_madurativa
  breakpoints:
      - {max: 23.9, value: v1_16_23}
      - {max: 30.9, value: v2_24_30}
      - {max: 36.0, value: v3_31_36}
  otherwise: fuera_de_rango

If target is an enum field, every breakpoint value and otherwise must be a real member of that enum — checked at parse time.

any_of_implies conditions, each {field, op[, value]} with op one of truthy/eq/lt/le/gt/ge (truthy needs no value):

- kind: any_of_implies
  target: flag_riesgo_neonatal
  conditions:
      - {field: apgar_5min, op: lt, value: 7}
      - {field: ingreso_ucin, op: truthy}

Generating

python -m ps_core.generate_all --spec-dir spec --out-dir generated

generated/ is written as a real package (__init__.py included), so validation.py's from .enums import * resolves whether you import it in-process or load it from disk later.

Loading data at runtime

from generated.schema import Base, TestTable, ForeignTable
from generated.validation import TestTableCheck, ForeignTableCheck
from ps_core.runtime import ingest, check_foreign_keys, check_unique_fields
from ps_core.parse_spec import parse_spec
from sqlalchemy import create_engine
from sqlalchemy.orm import Session

parsed_tables, _, _ = parse_spec("spec")
class_lookup = {"test_table": TestTable, "foreign_table": ForeignTable}

engine = create_engine("sqlite://")
Base.metadata.create_all(engine)

with Session(engine) as session:
    row = ingest({"field1": "hello", "field4": "2024-01-01"}, TestTableCheck, TestTable)
    session.add(row)
    session.commit()

    check_foreign_keys(session, parsed_tables, class_lookup)
    check_unique_fields(session, parsed_tables, class_lookup)
    session.commit()

validate_row (used inside ingest) takes and returns plain data, so it is safe to run in a separate worker process — only check_cls needs to be importable by name on both sides. load_row, check_foreign_keys, and check_unique_fields must run in the process that owns the database session.

The shape of a stored error

errors is a JSON object, one entry per failed field (or _cross_field for a cross rule). Each entry is {"rule": <name>, "message": <text>}:

{
    "field2": {"rule": "range", "message": "field2 must be between 1 and 10, got 99"},
    "_cross_field": {"rule": "requires[field6,field3]", "message": "field3 is required when field6 is true"}
}

rule is never parsed back out of the message — every check in constraints.py and every cross-rule kind raises pydantic_core.PydanticCustomError(rule_name, ...), which is still a real ValueError (so except ValueError keeps working everywhere), but also sets e.errors()[i]["type"] to that exact rule name. ps_core.runtime.validate_row reads that field directly. foreign_key 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 custom message — see "Field rules" above. Cross-field rules are different: each one describes a genuinely distinct relationship between fields, so a single generic template can't cover them all. Their optional message key is inserted into the generated file as a plain string literal (safely repr()'d), regardless of what characters it contains — no injection risk from quotes or braces in the text.

Re-validating data already in the database (ps_core.validate_all)

python -m ps_core.validate_all --spec-dir spec --generated-dir generated

Re-runs the full cascade — Pydantic checks, then foreign keys, then uniqueness — against every row already in the database, rewriting validated/errors for each one. Same --spec-dir/--generated-dir split as ps_core.devdata.fill, for the same reason: --spec-dir is every rule ps_core knows about, --generated-dir only says where the real classes already live.

Use this after a bulk import that didn't go through ps_core.runtime.ingest, after changing a rule in the spec (existing rows were checked under the old rules), or on demand whenever you want current data re-checked without touching a single row's actual values.

Synthetic data for development (ps_core.devdata)

Not imported by anything else in ps_core — a separate subpackage for generating good and deliberately-bad data against a spec, for local development and testing. Its own dependency direction: it reads parse_spec's output and calls into ps_core.runtime, never the other way around, so a plain pip install ps_core needs none of it.

python -m ps_core.devdata.fill --spec-dir spec --generated-dir generated

--generated-dir points at wherever build.py (or generate_all) already wrote schema.py/validation.py/enums.py — this script imports the real classes rather than reconstruct them, and does not regenerate anything itself.

Runs in five phases, across every table together — not table by table — so table order never matters, even with circular or self-referential foreign keys: build every table's skeleton row (every field except foreign keys) → backfill every foreign key, now that every table has rows → run real validation → check foreign keys → check unique fields.

Four independent rate flags, each an independent coin flip per row (a single row can be more than one of these at once):

flag default what it does
--count 20 rows generated per table
--orphan-rate 0.0 fraction of rows whose foreign key(s) point at nothing on purpose
--faulty-rate 0.0 fraction of rows with one randomly chosen field deliberately breaking its own rule
--repeated-rate 0.0 fraction of rows whose unique: true field(s) are copied from an earlier row, on purpose
python -m ps_core.devdata.fill --spec-dir spec --generated-dir generated \
    --count 100 --orphan-rate 0.3 --faulty-rate 0.3 --repeated-rate 0.2

devdata.good builds values by reading field["checks"] directly — no retries, no calls into Pydantic, every value correct by construction. devdata.faulty breaks one field's own rule the same deterministic way. Only cross-field-rule violations need Pydantic at all (faulty_row_for_cross_rule): since a cross rule's condition lives in generated code, not in any field's checks, there's nothing structured to read, so that one function generates candidates and asks check_cls(**row) to say when one actually violates the rule.

S
Description
No description provided
Readme 398 KiB
Release 0.2.4 Latest
2026-09-14 13:29:12 -06:00
Languages
Python 98.2%
Jinja 1.8%