Files
models/tests/io/test_extraction_ranker.py
2026-11-13 11:52:51 -06:00

98 lines
4.7 KiB
Python

"""Each domain's extraction ranker in the model registry
(`models.io.extraction_ranker`): every batch it learns from is a new DEV
version continuing the latest, with its five routine records and its saved
model; extraction takes the version in production, else the latest, and
`EXTRACTION_RANKER` can restrict or turn that off.
Fixtures: `mlflow_tracking` (a SQLite MLflow per test) and `_fresh_cache`
(an empty ranker cache and no `EXTRACTION_RANKER`). Batches are built
inline by `_batch` from candidates with the features an extractor gives
them; no document is read.
"""
import json
import mlflow.artifacts
import pytest
from extraction.document import BBox
from extraction.nlp import FieldKind, FieldSpec
from extraction.nlp.fields import Evidence, ExtractedValue
from extraction.nlp.ranking import examples_for
from models.io import extraction_ranker
from models.io.extraction_ranker import Batch, current, learn
from models.io.registry import registry
from models.io.tracking import ROUTINES_PATH
GRADO = FieldSpec("bx_cin_grado", FieldKind.CHOICE, choices={"NIC I": "LIEBG", "NIC II": "LIEAG"})
def _batch(right: str = "LIEBG") -> Batch:
evidence = Evidence("reporte.pdf", 1, "Diagnóstico: NIC I", BBox(0, 0, 1, 0.1).as_list())
candidates = [
ExtractedValue("LIEBG", 0.5, "etiqueta", "NIC I", evidence, {"assertion": "afirmado", "section": "resultado"}),
ExtractedValue("LIEAG", 0.6, "texto_libre", "NIC II", evidence, {"assertion": "afirmado", "section": "general"}),
]
examples = examples_for([GRADO], {"bx_cin_grado": candidates}, {"bx_cin_grado": right})
return Batch(examples, "revision", documents=1, records=1, unreachable={})
@pytest.fixture(autouse=True)
def _fresh_cache(monkeypatch):
"""No ranker cached from another test, and the default selection."""
monkeypatch.setattr(extraction_ranker, "_cache", {})
monkeypatch.delenv(extraction_ranker.SELECTION_ENV, raising=False)
def test_each_batch_is_a_new_dev_version_with_its_routines(mlflow_tracking):
"""Fails if learning stops registering a DEV version, its run loses one
of the five routine records or its saved model, which ML-01a and ML-01b
require to promote it."""
version = learn("cacu", _batch())
described = registry.get("cacu", extraction_ranker.SCENARIO, version)
assert described.tags["environment"] == "DEV"
checks = {c.code: c.passed for c in registry.checks("cacu", extraction_ranker.SCENARIO, version)}
assert checks["ML-01a"] and checks["ML-01b"]
def test_routine_records_hold_counts_never_document_text(mlflow_tracking):
"""What a ranker stores can be shared: weights and counts. Fails if a
routine record or the ranker's state carries a raw reading or the line
it came from."""
version = learn("cacu", _batch())
run_id = registry.get("cacu", extraction_ranker.SCENARIO, version).run_id
stored = json.dumps(mlflow.artifacts.load_dict(f"runs:/{run_id}/{extraction_ranker.RANKER_PATH}"))
for kind in ("MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"):
stored += mlflow.artifacts.load_text(f"runs:/{run_id}/{ROUTINES_PATH}/{kind}.json")
assert "NIC I" not in stored and "Diagnóstico" not in stored and "reporte.pdf" not in stored
def test_learning_continues_from_the_latest_version(mlflow_tracking):
"""Fails if a new batch starts from scratch instead of the latest
version, which would forget every earlier correction."""
learn("cacu", _batch())
second = learn("cacu", _batch())
ranker = current("cacu")
assert ranker.version == f"{extraction_ranker.SCENARIO}:{second}"
assert ranker.examples == 2 * len(_batch().examples)
def test_extraction_takes_production_first_and_can_be_turned_off(mlflow_tracking, monkeypatch):
"""With a version in production that one is used even when newer DEV
versions exist; `produccion` refuses DEV-only registries and `ninguno`
turns the ranker off. Fails if the selection order changes."""
assert current("cacu") is None
first = learn("cacu", _batch())
learn("cacu", _batch())
registry.client.set_registered_model_alias("cacu-extraccion", "produccion", first)
assert current("cacu").version == f"{extraction_ranker.SCENARIO}:{first}"
monkeypatch.setenv(extraction_ranker.SELECTION_ENV, "ninguno")
assert current("cacu") is None
monkeypatch.setenv(extraction_ranker.SELECTION_ENV, "produccion")
assert current("tea") is None
def test_an_empty_batch_registers_nothing(mlflow_tracking):
"""Fails if a review without usable examples creates a version."""
assert learn("cacu", Batch([], "revision", 0, 0, {})) is None
assert registry.versions("cacu", extraction_ranker.SCENARIO) == []