Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 34 additions & 2 deletions packages/flow/openadapt_flow/form_tx/presets/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
"""Domain presets for ``form_tx`` pack induction, kept as data.

A preset is a canonical domain schema (the fields a kind of form asks for,
A domain preset is a canonical domain schema (the fields a kind of form asks for,
with label synonyms) used by ``induce_form_pack`` and the ``--domain`` flag.
It is vocabulary for one kind of form, so it lives here as JSON
(``openadapt.form-domain-preset/v1``), not in the engine's code. The
``build_*_domain_schema`` functions in ``pack_compiler`` load these files and
return the same objects they used to build.

A word list (``openadapt.form-word-list/v1``, ``presets/words/*.json``) holds
the words one rule looks for, such as the entity kinds that name the person a
form is about. The module constants that used to hold them load these files.
"""

from __future__ import annotations
Expand All @@ -18,10 +22,18 @@
if TYPE_CHECKING:
from openadapt_flow.form_tx.pack_compiler import CanonicalDomainSchema

__all__ = ["PRESET_SCHEMA", "load_domain_schema", "preset_names"]
__all__ = [
"PRESET_SCHEMA",
"WORD_LIST_SCHEMA",
"load_domain_schema",
"load_words",
"preset_names",
]

PRESET_SCHEMA = "openadapt.form-domain-preset/v1"
WORD_LIST_SCHEMA = "openadapt.form-word-list/v1"
_DIR = Path(__file__).resolve().parent
_WORDS = _DIR / "words"


def preset_names() -> tuple[str, ...]:
Expand Down Expand Up @@ -49,3 +61,23 @@ def load_domain_schema(name: str) -> "CanonicalDomainSchema":
from openadapt_flow.form_tx.pack_compiler import CanonicalDomainSchema

return CanonicalDomainSchema.model_validate(_raw(name))


@lru_cache(maxsize=None)
def load_words(name: str) -> tuple[str, ...]:
"""The words of word list ``name`` (``presets/words/<name>.json``), in order."""

names = {p.stem for p in _WORDS.glob("*.json")}
if name not in names:
raise ValueError(f"unknown form_tx word list {name!r}")
data = json.loads((_WORDS / f"{name}.json").read_text(encoding="utf-8"))
words = data.get("words") if isinstance(data, dict) else None
if (
not isinstance(data, dict)
or data.get("schema") != WORD_LIST_SCHEMA
or data.get("name") != name
or not isinstance(words, list)
or not all(isinstance(w, str) for w in words)
):
raise ValueError(f"word list {name!r} is not {WORD_LIST_SCHEMA}")
return tuple(words)
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"schema": "openadapt.form-word-list/v1",
"name": "primary_entity_kinds",
"about": "Entity kinds a dossier uses for the person the form is about. An entity table also expects these entities when they carry the table's key fields.",
"words": [
"primary_applicant",
"primary_insured",
"applicant",
"insured",
"primary",
"self"
]
}
24 changes: 10 additions & 14 deletions packages/flow/openadapt_flow/form_tx/reconciler.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
values_equivalent,
)
from openadapt_flow.form_tx.judge import SummaryJudge
from openadapt_flow.form_tx.presets import load_words
from openadapt_flow.form_tx.receipt import issue_form_tx_receipt
from openadapt_flow.form_tx.surface import (
AmbiguousAnchorError,
Expand Down Expand Up @@ -70,16 +71,9 @@
"ReconcilerSession",
]

_PRIMARY_ENTITY_KINDS = frozenset(
{
"primary_applicant",
"primary_insured",
"applicant",
"insured",
"primary",
"self",
}
)
#: Entity kinds that name the person the form is about (data:
#: ``presets/words/primary_entity_kinds.json``).
_PRIMARY_ENTITY_KINDS = frozenset(load_words("primary_entity_kinds"))
_DEFAULT_PLACEHOLDERS: tuple[str, ...] = (
"",
"-- Select --",
Expand Down Expand Up @@ -645,15 +639,17 @@ def _check_entity_table_conflicts(
pack = session.pack
dossier = session.dossier

primary_kinds = (
frozenset(pack.primary_entity_kinds)
if pack.primary_entity_kinds is not None
else _PRIMARY_ENTITY_KINDS
)
for spec in pack.entity_tables:
expected_entities: list[DossierEntity] = list(
dossier.entities_of_kind(spec.entity_kind)
)
for ent in dossier.entities:
if (
ent.entity_kind in _PRIMARY_ENTITY_KINDS
and ent not in expected_entities
):
if ent.entity_kind in primary_kinds and ent not in expected_entities:
if all(kf in ent.fields for kf in spec.key_fields):
expected_entities.append(ent)

Expand Down
16 changes: 15 additions & 1 deletion packages/flow/openadapt_flow/form_tx/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,9 +398,23 @@ class FormPack(BaseModel):
summary_check: Optional[SummaryCheckSpec] = None
commit_url_patterns: tuple[str, ...] = ()
max_commit_mutations: int = Field(default=1, ge=0, le=10)
# Overrides of the engine's default word lists (``form_tx/presets/words``).
# None keeps the default. An entity table also expects a dossier entity of
# one of these kinds when it carries the table's key fields.
primary_entity_kinds: Optional[tuple[str, ...]] = None

def digest(self) -> str:
return canonical_sha256(self)
# An override left unset is not hashed, so a pack written before the
# field existed keeps its digest.
data = self.model_dump(mode="json")
for name in _UNHASHED_WHEN_UNSET:
if data.get(name) is None:
data.pop(name, None)
return canonical_sha256(data)


#: FormPack fields left out of the digest while they are None.
_UNHASHED_WHEN_UNSET = ("primary_entity_kinds",)


class ObservedOption(BaseModel):
Expand Down
99 changes: 99 additions & 0 deletions packages/flow/tests/test_form_tx_presets.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,102 @@ def test_an_unknown_preset_is_refused() -> None:
load_domain_schema("no_such_preset")
with pytest.raises(ValueError):
load_domain_schema("../pack_compiler")


# -- word lists ------------------------------------------------------------------


def _old_constant(sha: str, source: str, name: str) -> object:
"""A module constant's value at ``sha``: a literal, or frozenset(literal)."""

import ast

got = subprocess.run(
["git", "-C", str(ROOT), "show", f"{sha}:{source}"],
capture_output=True,
text=True,
)
if got.returncode != 0:
pytest.skip("no git history for the commit before the move")
for node in ast.parse(got.stdout).body:
targets = (
[node.target]
if isinstance(node, ast.AnnAssign)
else getattr(node, "targets", [])
)
if any(getattr(t, "id", None) == name for t in targets):
value = node.value
if (
isinstance(value, ast.Call)
and getattr(value.func, "id", "") == "frozenset"
):
return frozenset(ast.literal_eval(value.args[0]))
return ast.literal_eval(value) # type: ignore[arg-type]
raise AssertionError(f"{name} not found in {source} at {sha}")


def _primary_entity_kinds() -> object:
from openadapt_flow.form_tx import reconciler

return reconciler._PRIMARY_ENTITY_KINDS


#: word list: (current value, the commit before the move, file, constant)
MOVED_WORDS = {
"primary_entity_kinds": (
_primary_entity_kinds,
"2f506d6c463aef8098fc8fcc2fd5bc46e55c1829",
"packages/flow/openadapt_flow/form_tx/reconciler.py",
"_PRIMARY_ENTITY_KINDS",
),
}


@pytest.mark.parametrize("words", sorted(MOVED_WORDS))
def test_the_constant_equals_the_old_one(words: str) -> None:
current, sha, source, name = MOVED_WORDS[words]
old = _old_constant(sha, source, name)
now = current()
assert type(now) is type(old)
assert now == old


@pytest.mark.parametrize("words", sorted(MOVED_WORDS))
def test_each_word_list_ships_as_json(words: str) -> None:
from openadapt_flow.form_tx.presets import load_words

assert load_words(words)
assert words not in preset_names()


def test_an_unknown_word_list_is_refused() -> None:
from openadapt_flow.form_tx.presets import load_words

with pytest.raises(ValueError):
load_words("no_such_list")


@pytest.mark.parametrize(
"content",
[
"[]",
'"words"',
'{"schema": "other/v1", "name": "bad", "words": []}',
'{"schema": "openadapt.form-word-list/v1", "name": "other", "words": []}',
'{"schema": "openadapt.form-word-list/v1", "name": "bad", "words": [1]}',
'{"schema": "openadapt.form-word-list/v1", "name": "bad", "words": "a"}',
],
)
def test_a_malformed_word_list_is_refused(
content: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from openadapt_flow.form_tx import presets

(tmp_path / "bad.json").write_text(content, encoding="utf-8")
monkeypatch.setattr(presets, "_WORDS", tmp_path)
presets.load_words.cache_clear()
try:
with pytest.raises(ValueError):
presets.load_words("bad")
finally:
presets.load_words.cache_clear()
48 changes: 48 additions & 0 deletions packages/flow/tests/test_form_tx_reconciler_and_receipts.py
Original file line number Diff line number Diff line change
Expand Up @@ -1412,6 +1412,54 @@ def test_ppr_conditional_cascade_human_resume_popup_summary_and_receipt() -> Non
assert pii_token not in serialized_receipt


def test_a_pack_can_override_the_primary_entity_kinds() -> None:
"""The engine's default list (presets/words/primary_entity_kinds.json)
lets the dossier's primary applicant ground its own table row. A pack
that names no primary kinds makes that row an unlisted entity."""
grounded_row = {"first_name": "Elena", "last_name": "Vance"}
dossier = _build_dossier(has_pool="No")

default_pack = _build_pack()
assert default_pack.primary_entity_kinds is None
surface = FakeStatefulFormSurface(entity_rows=[grounded_row])
reconciler = FormReconciler(surface)
done = reconciler.run_until_halt_or_done(
reconciler.create_session(default_pack, dossier)
)
assert done.outcome == FormTxOutcome.VERIFIED_DONE

same = default_pack.model_copy(
update={"primary_entity_kinds": ("primary_applicant",)}
)
surface = FakeStatefulFormSurface(entity_rows=[grounded_row])
reconciler = FormReconciler(surface)
assert (
reconciler.run_until_halt_or_done(
reconciler.create_session(same, dossier)
).outcome
== FormTxOutcome.VERIFIED_DONE
)

none = default_pack.model_copy(update={"primary_entity_kinds": ()})
surface = FakeStatefulFormSurface(entity_rows=[grounded_row])
reconciler = FormReconciler(surface)
halted = reconciler.run_until_halt_or_done(reconciler.create_session(none, dossier))
assert halted.outcome == FormTxOutcome.HALTED_NEEDS_HUMAN
assert halted.halts[0].kind == FormHaltKind.PREFILL_ENTITY_CONFLICT


def test_an_unset_override_keeps_the_pack_digest() -> None:
from openadapt_flow.form_tx.types import canonical_sha256

pack = _build_pack()
old_style = pack.model_dump(mode="json")
old_style.pop("primary_entity_kinds")
assert pack.digest() == canonical_sha256(old_style)
assert (
pack.model_copy(update={"primary_entity_kinds": ()}).digest() != pack.digest()
)


def test_entity_table_prefill_conflict_dismiss_accept_and_broken_dismiss() -> None:
grounded_row = {"first_name": "Elena", "last_name": "Vance"}
unlisted_spouse = {"first_name": "Marcus", "last_name": "Vance"}
Expand Down
Loading