The catalog step seeds each domain's mappings, and a mapping is written only if the function still holds

How: `catalog_rows` turns the TOML's study codes, captions and each value's code, label and aliases into the
`catalogo` system's rows; the `catalogs` step adds the system and the forms with no row yet
(`mapeos_nuevos`). `register` normalizes the form and adds the row through `SourceMappingRepository.add`
with `check_stored`, which runs `check_function` on the stored rows of the same form; captions aren't
checked, since one caption may introduce several results. `ctx.repos.silver.mappings` is the domain's
repository.

Implications: the database keeps every mapping across deploys; a person's change is never overwritten, and
a second code for a form in force is refused before it's written. Loads still read the TOML's aliases.
This commit is contained in:
rockdrigo
2026-11-13 15:31:21 -06:00
parent 64d3d721e3
commit 73cbf0cfb8
5 changed files with 138 additions and 11 deletions
+5 -2
View File
@@ -75,7 +75,9 @@ def test_catalogos_deja_en_la_base_las_filas_del_toml(base):
del_toml = {"estudios": len(catalogo.estudios), "resultados": len(catalogo.resultados),
"valores": len(catalogo.valores)}
assert base.run("catalogs")["catalogs"] == {**del_toml, "retirados": 0}
conteos = base.run("catalogs")["catalogs"]
assert conteos.pop("mapeos_nuevos") > 0
assert conteos == {**del_toml, "retirados": 0}
assert filas_del_catalogo(base) == del_toml
@@ -83,7 +85,8 @@ def test_volver_a_correr_catalogos_no_cambia_nada(base):
base.run("catalogs")
antes = filas_del_catalogo(base)
assert base.run("catalogs")["catalogs"]["retirados"] == 0
conteos = base.run("catalogs")["catalogs"]
assert (conteos["retirados"], conteos["mapeos_nuevos"]) == (0, 0)
assert filas_del_catalogo(base) == antes
+54 -3
View File
@@ -1,8 +1,10 @@
"""What this module covers: source forms as a function into the catalog's codes (`reference.source_mapping`):
many forms to one code, no code for an unknown form, the same form read per source system and per date, and two
codes for one form rejected when they're in force together; and every catalog's TOML passing that check.
codes for one form rejected when they're in force together; every catalog's TOML passing that check; and, in each
domain's database, the catalog step seeding `cat_mapeo` without touching a stored row and `register` refusing a
mapping that breaks the function.
Fixtures: none; the rows are built in each test.
Fixtures: `base` (conftest), each domain's migrated fixture database; the other tests build their rows.
"""
import tomllib
@@ -11,7 +13,7 @@ from datetime import date
import pytest
from webapi.orchestration.reference.catalogs import ruta_de_catalogo
from webapi.orchestration.reference.source_mapping import (
SourceForm, ambiguities, check_function, from_result, normalize, resolve,
CATALOG, SourceForm, ambiguities, check_function, from_result, normalize, register, resolve,
)
HER2 = "biopsia.her2"
@@ -63,3 +65,52 @@ def test_every_catalog_s_spellings_are_a_function(proyecto):
for nombre, resultado in estudio.get("resultados", {}).items()
for row in from_result(f"{estudio_id}.{nombre}", resultado)]
check_function(rows)
# --- the stored mappings, in each domain ---
def a_coded_result(base) -> tuple[str, str, str]:
"""A coded result of the domain's catalog with two values: (resultado_id, first valor_id, second valor_id)."""
estudios = tomllib.loads(ruta_de_catalogo(base.proyecto).read_text(encoding="utf-8"))
for estudio_id, estudio in estudios.items():
for nombre, resultado in estudio.get("resultados", {}).items():
valores = resultado.get("valores", ())
if len(valores) >= 2:
return f"{estudio_id}.{nombre}", valores[0]["valor"], valores[1]["valor"]
raise AssertionError("el catálogo no tiene un resultado codificado con dos valores")
def test_the_catalog_step_seeds_the_mappings_and_keeps_what_a_person_changed(base):
"""Pins down: the catalog step adds the catalog's own mappings (each value's code among them) and, run again,
adds nothing and leaves a person's row for a new form as it is. Fails if the step stops seeding or a deploy
replaces stored rows."""
base.run("catalogs")
mappings = base.ctx.repos.silver.mappings
resultado, primero, segundo = a_coded_result(base)
sembradas = mappings.forms(sistema_fuente_id=CATALOG, resultado_id=resultado, clase="valor")
assert {(m.forma, m.valor_id) for m in sembradas} >= {(primero, primero), (segundo, segundo)}
register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma=" forma del curador ", registrado_por="curador",
vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=segundo)
assert base.run("catalogs")["catalogs"]["mapeos_nuevos"] == 0
[mia] = mappings.forms(forma_normalizada="FORMA DEL CURADOR")
assert (mia.forma, mia.valor_id, mia.registrado_por) == ("forma del curador", segundo, "curador")
def test_register_refuses_a_second_code_for_a_form_in_force(base):
"""Pins down: `register` checks the new row against the stored ones: the catalog's own code of one value can't
be mapped to another value, and a lab's form can, once the first row's validity ends before the second's starts.
Fails if the write path stops running `check_function`."""
base.run("catalogs")
mappings = base.ctx.repos.silver.mappings
resultado, primero, segundo = a_coded_result(base)
with pytest.raises(ValueError, match="se escribe igual"):
register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma=primero, registrado_por="curador",
vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=segundo)
viejo = register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma="Código de laboratorio",
registrado_por="curador", vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=primero)
mappings.close(viejo.mapeo_id, date(2026, 12, 31))
nuevo = register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma="codigo de LABORATORIO",
registrado_por="curador", vigente_desde=date(2027, 1, 1), resultado_id=resultado, valor_id=segundo)
filas = mappings.forms(forma_normalizada=normalize("Código de laboratorio"))
assert [f.mapeo_id for f in filas] == [viejo.mapeo_id, nuevo.mapeo_id]
+12 -2
View File
@@ -27,6 +27,7 @@ from webapi.orchestration.reference.support import (
grupos_de_edad_de,
)
from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo
from webapi.orchestration.reference.source_mapping import catalog_rows
from webapi.orchestration.reference.rules import (
RUTA_PARAMETROS,
leer_parametros,
@@ -66,9 +67,18 @@ def migrate(ctx: Context) -> str:
def catalogs(migrate: str, ctx: Context) -> dict[str, int]:
"""`core/catalogos/<proyecto>.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra."""
"""`core/catalogos/<proyecto>.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra.
Then the catalog's own mappings (`cat_mapeo`, system `catalogo`): only the forms with no row yet are added, so a
mapping edited in the application survives every deploy."""
catalogo = catalogo_desde_toml(ruta_de_catalogo(ctx.project), tablas=tablas_de(ctx.project))
return ctx.repos.silver.catalogs.sync(catalogo.estudios, catalogo.resultados, catalogo.valores)
counts = ctx.repos.silver.catalogs.sync(catalogo.estudios, catalogo.resultados, catalogo.valores)
mappings = ctx.repos.silver.mappings
if mappings is not None:
system, rows = catalog_rows(ctx.project, mappings)
mappings.ensure_system(system)
counts["mapeos_nuevos"] = mappings.seed(rows)
return counts
def load(catalogs: dict[str, int], ctx: Context) -> SQLModel:
@@ -13,13 +13,16 @@ A source form (a spelling, an abbreviation, a lab's own code) maps to one `valor
For `f` to be a function, two mappings in force on the same date can't give the same key two codes:
`check_function` rejects that, and `resolve` returns nothing for a key it still finds ambiguous, so the observation
goes back to the out-of-catalog queue instead of keeping a code. Today the mappings come from the catalog's TOML
(`from_result`: one system, always in force); any other store of mappings gives `SourceForm` rows and is checked
and read the same way.
goes back to the out-of-catalog queue instead of keeping a code.
The mappings are stored in `cat_sistema_fuente` and `cat_mapeo`: the `catalogs` step seeds the catalog's own
(`catalog_rows`, system `catalogo`, always in force) and never changes a stored row, and `register` adds one after
checking it against the rows of the same form.
"""
import tomllib
from collections import defaultdict
from datetime import date
from datetime import date, datetime, timezone
from typing import Iterable, NamedTuple
from extraction.nlp.text import fold
@@ -96,3 +99,60 @@ def _overlap(a: SourceForm, b: SourceForm) -> bool:
starts_before_b_ends = a.valid_from is None or b.valid_to is None or a.valid_from <= b.valid_to
b_starts_before_a_ends = b.valid_from is None or a.valid_to is None or b.valid_from <= a.valid_to
return starts_before_b_ends and b_starts_before_a_ends
# --- the mappings stored in `cat_sistema_fuente` and `cat_mapeo` ---
CATALOG_SINCE = date(1900, 1, 1) # the catalog's own mappings hold for every document
def as_source_form(row) -> SourceForm:
"""A `cat_mapeo` row as the function sees it: a study code maps to its `estudio_id`, a spelling to its value."""
return SourceForm(row.sistema_fuente_id, row.resultado_id or "", row.forma, row.valor_id or row.estudio_id,
row.vigente_desde, row.vigente_hasta)
def check_stored(same_form: list, new) -> None:
"""`SourceMappingRepository.add`'s check: a study code or a spelling stays a function with the new row. A
caption may introduce several results (a receptor and its percentage), so it isn't checked."""
if new.clase == "etiqueta":
return
check_function([as_source_form(r) for r in same_form if r.clase == new.clase] + [as_source_form(new)])
def register(repository, *, sistema_fuente_id: str, clase: str, forma: str, registrado_por: str,
vigente_desde: date, estudio_id: str | None = None, resultado_id: str | None = None,
valor_id: str | None = None, motivo: str | None = None):
"""Adds one mapping, rejected with `ValueError` if it makes a form give two codes while both are in force."""
row = repository.model(
sistema_fuente_id=sistema_fuente_id, clase=clase, forma=forma.strip(), forma_normalizada=normalize(forma),
estudio_id=estudio_id, resultado_id=resultado_id, valor_id=valor_id, vigente_desde=vigente_desde,
registrado_por=registrado_por, registrado_en=datetime.now(timezone.utc), motivo=motivo)
return repository.add(row, check=check_stored)
def catalog_rows(project: str, repository) -> tuple[object, list]:
"""The catalog's source system and its mappings, from the TOML: study codes, captions, and each value's code,
label and aliases. What `SourceMappingRepository.seed` adds when they're missing."""
from webapi.orchestration.reference.catalogs import ruta_de_catalogo
system = repository.sistema(sistema_fuente_id=CATALOG, etiqueta="Catálogo del proyecto", fuente_tabla=None,
vigente_desde=CATALOG_SINCE)
now = datetime.now(timezone.utc)
rows = {}
def add(clase, forma, **target):
row = repository.model(sistema_fuente_id=CATALOG, clase=clase, forma=forma, forma_normalizada=normalize(forma),
vigente_desde=CATALOG_SINCE, registrado_por=CATALOG, registrado_en=now, **target)
rows.setdefault((clase, target.get("resultado_id"), target.get("estudio_id"), row.forma_normalizada), row)
for study_id, study in tomllib.loads(ruta_de_catalogo(project).read_text(encoding="utf-8")).items():
for code in study.get("codigos_hospital", ()):
add("estudio", code, estudio_id=study_id)
for name, result in study.get("resultados", {}).items():
result_id = f"{study_id}.{name}"
for caption in result.get("etiquetas_fuente", ()):
add("etiqueta", caption, resultado_id=result_id)
for form in from_result(result_id, result):
add("valor", form.form, resultado_id=result_id, valor_id=form.value_id)
return system, list(rows.values())
+3
View File
@@ -21,6 +21,7 @@ from persistance.edges.silver import (
ObservationRepository,
TimelineRepository,
LinksRepository,
SourceMappingRepository,
ViewsRepository,
)
from persistance.materializer import Materializer
@@ -43,6 +44,7 @@ class Silver:
observation: ObservationRepository
links: LinksRepository
timeline: TimelineRepository | None = None # the patients' timeline: dbt's view, as the models and the strata read it
mappings: SourceMappingRepository | None = None # how each source writes the catalog's codes
@dataclass(frozen=True)
@@ -80,6 +82,7 @@ def repositories_of(proyecto: str) -> Repositories:
observation=dominio.observation_period_repository,
links=dominio.links_repository,
timeline=dominio.timeline_repository,
mappings=dominio.source_mapping_repository,
),
materializer=dominio.materializer,
gold=Gold(