From c9960dc1d6ac1b1e46cb31726ab7668be2f4a567 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:11:30 -0500 Subject: [PATCH 1/2] chore: carry the effect-location package from #2500 for this stack Copied unchanged from claude/effect-location-record at 52a0a7b14 so this branch can use it. Drops out of the diff when #2500 merges. --- packages/flow/docs/EFFECT_LOCATION.md | 96 ++++ .../effect_location/__init__.py | 53 ++ .../openadapt_flow/effect_location/_compat.py | 67 +++ .../openadapt_flow/effect_location/codecs.py | 266 +++++++++ .../effect_location/evaluator.py | 505 +++++++++++++++++ .../openadapt_flow/effect_location/record.py | 448 +++++++++++++++ packages/flow/tests/test_effect_location.py | 513 ++++++++++++++++++ 7 files changed, 1948 insertions(+) create mode 100644 packages/flow/docs/EFFECT_LOCATION.md create mode 100644 packages/flow/openadapt_flow/effect_location/__init__.py create mode 100644 packages/flow/openadapt_flow/effect_location/_compat.py create mode 100644 packages/flow/openadapt_flow/effect_location/codecs.py create mode 100644 packages/flow/openadapt_flow/effect_location/evaluator.py create mode 100644 packages/flow/openadapt_flow/effect_location/record.py create mode 100644 packages/flow/tests/test_effect_location.py diff --git a/packages/flow/docs/EFFECT_LOCATION.md b/packages/flow/docs/EFFECT_LOCATION.md new file mode 100644 index 0000000000..d8e4a8cbdb --- /dev/null +++ b/packages/flow/docs/EFFECT_LOCATION.md @@ -0,0 +1,96 @@ +# Effect locations + +A careful person who has just entered a form checks their work. They read the +review page before they press submit, and afterwards they look again where the +value should now appear: the summary, the saved record, a list row, a second +session or an export. An effect location records one of those places as data, +so the engine can do the same check for any application without knowing which +application it is. + +The record is `openadapt.effect-location/v1` +(`openadapt_flow/effect_location/record.py`). A pack stores one per place, +compiled from the demonstration. The evaluator +(`openadapt_flow/effect_location/evaluator.py`) judges it from a reading that +an adapter (a browser, an accessibility tree, a terminal screen, an export +reader) takes when it goes back. + +## The record + +| Field | What it holds | +| --- | --- | +| `keys` | The intended values the location shows. Usually one. A summary row such as "Name (DOB)" shows two. | +| `path` | The demonstration steps that reach the location. | +| `start` | Where the re-observation starts: `same_screen`, `fresh_navigation`, `new_session` or `other_channel`. | +| `locator` | How to find it: `label`, `row_key` (a row whose `column` cell equals `value`) or `region`. The adapter reads it; the evaluator does not. | +| `expected` | The value each key should show, in the codec's canonical form. The run's plan fills it in. | +| `codec` | How displayed text maps to the value (below). | +| `expected_count` | How many times the value shows. Required; usually 1. | +| `baseline` | Optional. What the location showed before the action. | + +## Codecs + +Every codec reads the whole displayed text. A prefix, a longer text or a value +with extra words never matches, so "Jane" is not "Jane Doe" and "250" is not +"$1,250.00". + +| Kind | Reads | Canonical value | +| --- | --- | --- | +| `text`, `fold` | Text, whitespace collapsed (`fold` also ignores case) | string | +| `number`, `unit` | A decimal number, for `unit` followed by one of `units` | decimal | +| `money` | An amount with optional `affixes` (currency signs), `group_marks` and `decimal_mark` | integer minor units | +| `date` | ISO, or numeric in `date_order` (`YMD`, `MDY`, `DMY`), or with `month_names` | ISO date | +| `bool` | One of `true_tokens` or `false_tokens` | bool | +| `enum` | An entry of `table` (shown text to value) | string | +| `split_date` | Three displayed parts, `year`, `month` and `day` | ISO date | +| `template` | One text matched in full by `pattern`; each of `parts` reads one named group as one key with its own codec | one value per key | + +The engine has no default words. A bool codec with no tokens, a date codec +with no month names or a money codec with no currency sign accepts only the +bare form. The pack supplies the rest from the demonstration. + +## How a value is judged + +The obligations are the run's intended values, fixed before any reading is +judged. Each one ends in one of the verdict kernel's three statuses. + +- `not_checked`: no location shows the value, or the location was not read, + was not found, or was found a different number of times than expected. Also + when the read failed or came from another run, the start condition was not + met, a kind is unknown, the text can't be read, or the read was partial and + showed no conflict. Also when the expected value equals the baseline, so + the read can't tell the change from what was already there. +- `refuted`: the location shows a different value. A partial read can refute. +- `held`: every location for the value was read in full and showed exactly + the expected value the expected number of times. + +The run passes only when every planned value held and no reading is left +over. When several locations show one value, a refutation at any of them +refutes it, and it holds only when all of them hold, at the weakest level. + +## Check level and receipt word + +The check level comes from the start condition the adapter achieved: + +| Start | Check level | +| --- | --- | +| `same_screen` | 1, `same_screen` | +| `fresh_navigation` | 2, `reopened` | +| `new_session` | 3, `separate_session`, basis `separate_session` | +| `other_channel` | 4, `system_of_record`, with the basis the adapter names (`system_api`, `activity_log`, `db_frame` or `owned_connection`) | + +The receipt word comes from `openadapt_types.check_level.outcome_word`, so +this package never decides what `VERIFIED` means. A same-screen read or a +fresh navigation is `SHOWN`. A new session is `VERIFIED`. Another channel is +`VERIFIED` only with a basis, otherwise `RECORDED`. Until `outcome_word` is on +main, the word is `None`. + +The adapter states the start condition it achieved and binds the reading to +the run. The evaluator can't see whether a navigation really fetched from the +server; the adapter must prove it before it says `fresh_navigation`. + +## Fail-open testing + +`evaluate_all` is a registered verdict site (`effect_location.evaluate_all`). +Its spec, `tests/failopen/sites/effect_location.py`, runs the generic +mutations against a plan with a label, a summary row, a split date and an +amount. diff --git a/packages/flow/openadapt_flow/effect_location/__init__.py b/packages/flow/openadapt_flow/effect_location/__init__.py new file mode 100644 index 0000000000..5c74abc223 --- /dev/null +++ b/packages/flow/openadapt_flow/effect_location/__init__.py @@ -0,0 +1,53 @@ +"""Effect locations: where a careful person would look again to see a value. + +Echo before commit, re-observe after. For each intended value, a pack stores +an effect location compiled from the demonstration: how to get there (the path +and a start condition), what to look for (the locator), what it should show +(the expected value, read through a codec), how many times (usually once) and, +optionally, what it showed before. A review page is one effect location; a +summary row, a lookup-table row, a reopened record, a separate session and an +export are others. + +:func:`evaluate` judges one location from one reading. :func:`evaluate_all` +judges every intended value of a run. A location that can't be reached, found +or read is ``not_checked``, never a silent pass. The engine holds no +vocabulary for any application or field: every word, pattern and token table +comes from the pack. See ``docs/EFFECT_LOCATION.md``. +""" + +from __future__ import annotations + +from openadapt_flow.effect_location.codecs import CodecError, decode +from openadapt_flow.effect_location.evaluator import ( + KeyResult, + Report, + evaluate, + evaluate_all, +) +from openadapt_flow.effect_location.record import ( + CODEC_KINDS, + LOCATOR_KINDS, + SCHEMA, + Codec, + EffectLocation, + Locator, + Reading, + Start, +) + +__all__ = [ + "CODEC_KINDS", + "LOCATOR_KINDS", + "SCHEMA", + "Codec", + "CodecError", + "EffectLocation", + "KeyResult", + "Locator", + "Reading", + "Report", + "Start", + "decode", + "evaluate", + "evaluate_all", +] diff --git a/packages/flow/openadapt_flow/effect_location/_compat.py b/packages/flow/openadapt_flow/effect_location/_compat.py new file mode 100644 index 0000000000..4b17b26387 --- /dev/null +++ b/packages/flow/openadapt_flow/effect_location/_compat.py @@ -0,0 +1,67 @@ +"""The two interfaces this package codes against before they reach main. + +- ``openadapt_flow.verdict_sites.verdict_site`` (#2476) registers a verdict + site with the fail-open harness. Until it is on main, the decorator here + records the id on the function and changes nothing else. +- ``openadapt_types.check_level.outcome_word`` and ``level_for_basis`` + (#2495) choose the receipt word and say which level a basis reaches. Until + they are on main, no word is chosen (``None``) and no basis is accepted + for another channel. Nothing here defines what ``VERIFIED`` means. + +Delete this module once both are on main and import them directly. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any, Optional, TypeVar + +from openadapt_types import check_level as _check_level + +F = TypeVar("F", bound=Callable[..., Any]) + +try: # pragma: no cover - which branch runs depends on what is merged + from openadapt_flow.verdict_sites import verdict_site as verdict_site +except ImportError: # pragma: no cover + + def verdict_site(id: str, *, classes: str) -> Callable[[F], F]: # type: ignore[no-redef] + """Record ``id`` on the function, as #2476's decorator does.""" + + def mark(fn: F) -> F: + setattr(fn, "__verdict_site__", id) + return fn + + return mark + + +_level_for_basis: Optional[Callable[..., Any]] = getattr( + _check_level, "level_for_basis", None +) +_outcome_word: Optional[Callable[..., Any]] = getattr( + _check_level, "outcome_word", None +) + + +def has_ladder_words() -> bool: + """True when ``check_level.outcome_word`` is available.""" + + return _outcome_word is not None + + +def reaches(basis: Optional[str], level: Any) -> bool: + """True when ``basis`` is a known basis that reaches exactly ``level``.""" + + if basis is None or _level_for_basis is None: + return False + try: + return bool(_level_for_basis(basis) == level) + except ValueError: + return False + + +def word(level: Any, basis: Optional[str], *, confirmed: bool) -> Optional[str]: + """The receipt word for ``level`` and ``basis``, or None before #2495.""" + + if _outcome_word is None: + return None + return str(_outcome_word(level, basis, confirmed=confirmed)) diff --git a/packages/flow/openadapt_flow/effect_location/codecs.py b/packages/flow/openadapt_flow/effect_location/codecs.py new file mode 100644 index 0000000000..9fd98b61d3 --- /dev/null +++ b/packages/flow/openadapt_flow/effect_location/codecs.py @@ -0,0 +1,266 @@ +"""Read displayed text as a value, by a pack's :class:`Codec`. + +Every codec matches the whole displayed text. A prefix, a superstring or a +value with extra words is an error, never a match: a type-ahead's "Jane" +is not "Jane Doe", and "250" is not "$1,250.00". Anything the codec can't +read raises :class:`CodecError`, which the evaluator turns into +``not_checked``. + +The module names no language and no application. Month names, yes/no words, +currency signs, units and lookup tables come from the pack. +""" + +from __future__ import annotations + +import datetime as _dt +import re +from collections.abc import Mapping +from decimal import Decimal, InvalidOperation +from typing import Any + +from openadapt_flow.effect_location.record import SCALAR_KINDS, Codec + +__all__ = ["CodecError", "canonical", "decode", "decode_scalar"] + + +class CodecError(ValueError): + """The text (or the expected value) can't be read by this codec.""" + + +_WS = re.compile(r"\s+") +_ISO = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$") +_PLAIN_NUMBER = re.compile(r"^-?\d+(?:\.\d+)?$") +_DATE_SPLIT = re.compile(r"[\s/.\-,]+") + + +def _collapse(text: str) -> str: + return _WS.sub(" ", text).strip() + + +def _need_str(text: Any) -> str: + if not isinstance(text, str): + raise CodecError(f"displayed value is a {type(text).__name__}, not text") + return text + + +def _iso(year: int, month: int, day: int) -> str: + try: + return _dt.date(year, month, day).isoformat() + except ValueError: + raise CodecError("not a calendar date") from None + + +def _number(codec: Codec, text: str, *, affixes: tuple[str, ...]) -> Decimal: + body = _collapse(text) + # A sign may sit outside or inside a currency sign: "-$250" or "$-250". + sign = "" + if body.startswith("-"): + sign, body = "-", body.removeprefix("-").strip() + for affix in sorted(affixes, key=len, reverse=True): + if affix and body.startswith(affix): + body = body.removeprefix(affix).strip() + break + if affix and body.endswith(affix): + body = body.removesuffix(affix).strip() + break + if not sign and body.startswith("-"): + sign, body = "-", body.removeprefix("-") + dec = re.escape(codec.decimal_mark) if codec.decimal_mark else None + frac = rf"(?:{dec}\d+)?" if dec else "" + plain = rf"\d+{frac}" + groups = [re.escape(g) for g in codec.group_marks if g] + if groups: + grouped = rf"\d{{1,3}}(?:(?:{'|'.join(groups)})\d{{3}})+{frac}" + pattern = rf"^(?:{plain}|{grouped})$" + else: + pattern = rf"^{plain}$" + if not re.match(pattern, body): + raise CodecError("not a number in this format") + for g in codec.group_marks: + if g: + body = body.replace(g, "") + if codec.decimal_mark and codec.decimal_mark != ".": + body = body.replace(codec.decimal_mark, ".") + try: + return Decimal(sign + body) + except InvalidOperation: + raise CodecError("not a number") from None + + +def _month(codec: Codec, token: str) -> int: + if token.isdigit(): + return int(token) + folded = token.casefold() + hits = [ + n + for n, names in enumerate(codec.month_names, start=1) + if folded in {name.casefold() for name in names} + ] + if len(hits) != 1: + raise CodecError("not a month this codec knows") + return hits[0] + + +def _date(codec: Codec, text: str) -> str: + body = _collapse(text) + m = _ISO.match(body) + if m: + return _iso(int(m[1]), int(m[2]), int(m[3])) + order = codec.date_order + if sorted(order) != ["D", "M", "Y"]: + raise CodecError("not an ISO date, and the codec gives no date order") + tokens = [t for t in _DATE_SPLIT.split(body) if t] + if len(tokens) != 3: + raise CodecError("not a date in this format") + parts = dict(zip(order, tokens)) + return _split(codec, parts["Y"], parts["M"], parts["D"]) + + +def _split(codec: Codec, year: Any, month: Any, day: Any) -> str: + y, mo, d = (_collapse(_need_str(v)) for v in (year, month, day)) + if not (len(y) == 4 and y.isdigit()) or not d.isdigit() or len(d) > 2: + raise CodecError("not a date in this format") + if mo.isdigit() and len(mo) > 2: + raise CodecError("not a date in this format") + return _iso(int(y), _month(codec, mo), int(d)) + + +def decode_scalar(codec: Codec, text: Any) -> Any: + """The value one displayed text shows, by a scalar codec.""" + + text = _need_str(text) + kind = codec.kind + if kind not in SCALAR_KINDS: + raise CodecError(f"codec {kind!r} does not read a single text") + if kind == "text": + return _collapse(text) + if kind == "fold": + return _collapse(text).casefold() + if kind == "number": + return _number(codec, text, affixes=codec.affixes) + if kind == "money": + amount = _number(codec, text, affixes=codec.affixes) + minor = amount * (10**codec.decimals) + if minor != minor.to_integral_value(): + raise CodecError("more decimal places than the currency has") + return int(minor) + if kind == "unit": + body = _collapse(text) + for unit in sorted(codec.units, key=len, reverse=True): + if unit and body.endswith(unit): + return _number(codec, body.removesuffix(unit), affixes=()) + raise CodecError("not followed by a unit this codec knows") + if kind == "date": + return _date(codec, text) + if kind == "bool": + folded = _collapse(text).casefold() + yes = {t.casefold() for t in codec.true_tokens} + no = {t.casefold() for t in codec.false_tokens} + if yes & no: + raise CodecError("a token is both true and false") + if folded in yes: + return True + if folded in no: + return False + raise CodecError("not a yes or no this codec knows") + # enum + folded = _collapse(text).casefold() + hits = { + value for shown, value in codec.table if _collapse(shown).casefold() == folded + } + if len(hits) != 1: + raise CodecError("not an entry this codec's table holds") + return hits.pop() + + +def canonical(codec: Codec, expected: Any) -> Any: + """The expected value in the form :func:`decode_scalar` returns. + + Strict about types: ``True`` is not 1, ``"1250"`` is not 1250 minor units, + and a float is refused (a pack stores amounts as integers or decimal + strings). + """ + + kind = codec.kind + if kind in ("text", "fold", "enum"): + if not isinstance(expected, str): + raise CodecError("the expected value is not text") + if kind == "enum": + return expected + return _collapse(expected) if kind == "text" else _collapse(expected).casefold() + if kind in ("number", "unit"): + if isinstance(expected, bool): + raise CodecError("the expected value is a bool, not a number") + if isinstance(expected, int): + return Decimal(expected) + if isinstance(expected, Decimal) and expected.is_finite(): + return expected + if isinstance(expected, str) and _PLAIN_NUMBER.match(expected): + return Decimal(expected) + raise CodecError("the expected value is not a number") + if kind == "money": + if isinstance(expected, int) and not isinstance(expected, bool): + return expected + raise CodecError("the expected amount is not an integer in minor units") + if kind in ("date", "split_date"): + m = _ISO.match(expected) if isinstance(expected, str) else None + if not m: + raise CodecError("the expected date is not an ISO date") + return _iso(int(m[1]), int(m[2]), int(m[3])) + if kind == "bool": + if not isinstance(expected, bool): + raise CodecError("the expected value is not a bool") + return expected + raise CodecError(f"codec {kind!r} has no single expected value") + + +def decode( + codec: Codec, match: Mapping[str, Any], keys: tuple[str, ...] +) -> dict[str, Any]: + """Each key's value in one match, or the :class:`CodecError` that stopped it. + + A scalar codec reads the match's ``text`` part as its one key. A + ``split_date`` codec reads ``year``, ``month`` and ``day`` as its one key. + A ``template`` codec reads ``text`` with ``pattern`` (the whole text) and + each part's group as that part's key; when the pattern doesn't match, + every key is an error. A match with parts the codec doesn't read is an + error too, so a stray part can't be ignored. + """ + + kind = codec.kind + if kind == "split_date": + names = {"year", "month", "day"} + if len(keys) != 1 or set(match) != names: + return dict.fromkeys(keys, CodecError("not the parts of a split date")) + try: + value: Any = _split(codec, match["year"], match["month"], match["day"]) + except CodecError as exc: + value = exc + return {keys[0]: value} + if set(match) != {"text"}: + return dict.fromkeys(keys, CodecError("the match is not one displayed text")) + if kind == "template": + if set(keys) != set(codec.keys()) or len(codec.keys()) != len(keys): + return dict.fromkeys(keys, CodecError("template keys do not match")) + if not all(p.codec.kind in SCALAR_KINDS for p in codec.parts): + return dict.fromkeys(keys, CodecError("a template part is not scalar")) + try: + text = _collapse(_need_str(match["text"])) + m = re.fullmatch(codec.pattern, text) if codec.pattern else None + except (CodecError, re.error): + m = None + if m is None: + return dict.fromkeys(keys, CodecError("the text does not fit the template")) + out: dict[str, Any] = {} + for part in codec.parts: + try: + out[part.key] = decode_scalar(part.codec, m.group(part.group)) + except (CodecError, IndexError) as exc: + out[part.key] = CodecError(str(exc)) + return out + if len(keys) != 1: + return dict.fromkeys(keys, CodecError("a scalar codec shows one key")) + try: + return {keys[0]: decode_scalar(codec, match["text"])} + except CodecError as exc: + return {keys[0]: exc} diff --git a/packages/flow/openadapt_flow/effect_location/evaluator.py b/packages/flow/openadapt_flow/effect_location/evaluator.py new file mode 100644 index 0000000000..e139edf622 --- /dev/null +++ b/packages/flow/openadapt_flow/effect_location/evaluator.py @@ -0,0 +1,505 @@ +"""Judge effect locations from readings: every intended value, or ``not_checked``. + +The obligations are the run's intended values (the plan), fixed before any +reading is judged. Each one ends ``held``, ``refuted`` or ``not_checked``, the +three statuses of the verdict kernel (``openadapt_flow.verdict``): + +- ``not_checked`` when no location shows the value, the location was not + read, the read failed or came from another run, the start condition was not + met, the locator or codec kind is unknown, the value was found a different + number of times than expected, the text could not be read, the read was + partial and showed no conflict, or the value equals the baseline (the read + can't tell the change from what was there before). +- ``refuted`` when a complete or partial read shows a different value. +- ``held`` only when every location for the value was read in full and showed + exactly the expected value the expected number of times. + +The run passes only when every planned value held and no reading was left +over. The check level comes from the start condition the adapter achieved +(``openadapt_types.check_level``); the receipt word is +``check_level.outcome_word`` when that is available, so this module never +decides what ``VERIFIED`` means. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass +from typing import Any, Literal, Optional, Union, get_args + +from openadapt_types.check_level import CheckLevel + +from openadapt_flow.effect_location import _compat +from openadapt_flow.effect_location._compat import verdict_site +from openadapt_flow.effect_location.codecs import CodecError, canonical, decode +from openadapt_flow.effect_location.record import ( + LOCATOR_KINDS, + SCALAR_KINDS, + EffectLocation, + Reading, + Start, +) + +__all__ = [ + "CODES", + "HELD", + "NOT_CHECKED", + "REFUTED", + "KeyResult", + "KeyStatus", + "Report", + "evaluate", + "evaluate_all", +] + +#: The verdict kernel's three statuses (``openadapt_flow.verdict.Status``). +KeyStatus = Literal["held", "refuted", "not_checked"] +HELD, REFUTED, NOT_CHECKED = get_args(KeyStatus) + +#: Every ``KeyResult.code``. Only ``shown`` holds; only ``mismatch`` refutes. +CODES = frozenset( + { + "shown", + "mismatch", + "bad_record", + "other_run", + "read_failed", + "bad_reading", + "start_not_met", + "not_found", + "count_mismatch", + "no_expected", + "bad_expected", + "bad_baseline", + "unreadable", + "partial", + "same_as_baseline", + "no_location", + "not_read", + "duplicate_location", + "stale_record", + "plan_conflict", + } +) + +#: The check level a start condition reaches. +LEVEL_OF_START: dict[Start, CheckLevel] = { + Start.SAME_SCREEN: CheckLevel.SAME_SCREEN, + Start.FRESH_NAVIGATION: CheckLevel.REOPENED, + Start.NEW_SESSION: CheckLevel.SEPARATE_SESSION, + Start.OTHER_CHANNEL: CheckLevel.SYSTEM_OF_RECORD, +} + + +@dataclass(frozen=True) +class KeyResult: + """One intended value's verdict. + + ``shown`` holds the displayed texts the reading matched for this value, + for the caller's message to a person. It may hold typed values, so it + never goes into a receipt. + """ + + key: str + status: str + reason: str + level: CheckLevel = CheckLevel.UNCHECKED + basis: Optional[str] = None + word: Optional[str] = None + locations: tuple[str, ...] = () + shown: tuple[str, ...] = () + #: Why, for code: one of :data:`CODES`. Callers branch on this, never + #: on ``reason``, which is for people. + code: str = "" + + +@dataclass(frozen=True) +class Report: + """Every planned value's verdict and the run's.""" + + results: tuple[KeyResult, ...] + status: str + reason: str + level: CheckLevel + basis: Optional[str] + word: Optional[str] + #: Readings that no planned location asked for. + unexpected: tuple[str, ...] + + @property + def passes(self) -> bool: + return self.status == HELD + + def by_key(self) -> dict[str, KeyResult]: + return {r.key: r for r in self.results} + + +def _start(value: Any) -> Optional[Start]: + try: + return Start(value) + except ValueError: + return None + + +def _same(a: Any, b: Any) -> bool: + """Equal and of the same type: ``True`` is not 1, ``"1"`` is not 1.""" + + return type(a) is type(b) and a == b + + +def _codec_for(loc: EffectLocation, key: str) -> Any: + if loc.codec.kind == "template": + for part in loc.codec.parts: + if part.key == key: + return part.codec + return None + return loc.codec + + +def _shape_problem(loc: EffectLocation) -> Optional[str]: + """Why the record itself can't be judged, or None.""" + + if loc.locator.kind not in LOCATOR_KINDS: + return "the locator kind is not one this engine reads" + kind = loc.codec.kind + if kind == "template": + if not loc.codec.pattern or set(loc.keys) != set(loc.codec.keys()): + return "the template does not name each key once" + if len(loc.codec.keys()) != len(set(loc.codec.keys())): + return "the template names a key twice" + elif kind == "split_date" or kind in SCALAR_KINDS: + if len(loc.keys) != 1: + return "this codec shows one key" + else: + return "the codec kind is not one this engine reads" + if len(set(loc.keys)) != len(loc.keys) or not loc.keys: + return "the location names no key, or a key twice" + count = loc.expected_count + if not isinstance(count, int) or isinstance(count, bool) or count < 1: + return "the expected count is not a positive whole number" + if _start(loc.start) is None: + return "the start condition is not one this engine knows" + return None + + +def _basis(start: Start, claimed: Optional[str]) -> Optional[str]: + if start is Start.NEW_SESSION: + return "separate_session" + if start is Start.OTHER_CHANNEL and _compat.reaches( + claimed, CheckLevel.SYSTEM_OF_RECORD + ): + return claimed + return None + + +def _judge(loc: EffectLocation, reading: Reading, run_id: str) -> dict[str, KeyResult]: + """Each of ``loc``'s keys judged from one reading.""" + + def nc(code: str, reason: str, shown: tuple[str, ...] = ()) -> dict[str, KeyResult]: + return { + k: KeyResult( + k, NOT_CHECKED, reason, locations=(loc.id,), shown=shown, code=code + ) + for k in loc.keys + } + + problem = _shape_problem(loc) + if problem: + return nc("bad_record", problem) + if not run_id or reading.run_id != run_id: + return nc("other_run", "the reading belongs to another run") + if reading.error is not None: + return nc("read_failed", "the read failed") + if not isinstance(reading.complete, bool): + return nc("bad_reading", "the reading does not say whether it was complete") + wanted = _start(loc.start) + got = _start(reading.start) + if got is None or wanted is None or LEVEL_OF_START[got] < LEVEL_OF_START[wanted]: + return nc( + "start_not_met", "the reading did not start where the location requires" + ) + found = len(reading.matches) + if found == 0: + return nc("not_found", "the location was not found") + shown_all = tuple(str(m.get("text", "")) for m in reading.matches) + if found != loc.expected_count: + return nc( + "count_mismatch", + f"found {found} times, expected {loc.expected_count}", + shown_all, + ) + decoded = [decode(loc.codec, m, loc.keys) for m in reading.matches] + out: dict[str, KeyResult] = {} + level = LEVEL_OF_START[got] + basis = _basis(got, reading.basis) + for key in loc.keys: + codec = _codec_for(loc, key) + + def result(status: str, code: str, reason: str) -> KeyResult: + return KeyResult( + key, + status, + reason, + code=code, + level=level if status == HELD else CheckLevel.UNCHECKED, + basis=basis if status == HELD else None, + locations=(loc.id,), + shown=shown_all, + ) + + if key not in loc.expected: + out[key] = result( + NOT_CHECKED, "no_expected", "the location has no expected value" + ) + continue + try: + want = canonical(codec, loc.expected[key]) + except CodecError: + out[key] = result( + NOT_CHECKED, + "bad_expected", + "the expected value is not in the codec's form", + ) + continue + values = [d.get(key) for d in decoded] + wrong = [ + v for v in values if not isinstance(v, CodecError) and not _same(v, want) + ] + if wrong: + # A partial read can refute: it showed a different value. + out[key] = result( + REFUTED, "mismatch", "the location shows a different value" + ) + continue + if any( + isinstance(v, CodecError) or key not in d for v, d in zip(values, decoded) + ): + out[key] = result( + NOT_CHECKED, "unreadable", "the displayed text could not be read" + ) + continue + if reading.complete is not True: + out[key] = result(NOT_CHECKED, "partial", "the read was partial") + continue + if loc.baseline is not None and key in loc.baseline: + try: + before = canonical(codec, loc.baseline[key]) + except CodecError: + out[key] = result( + NOT_CHECKED, + "bad_baseline", + "the baseline is not in the codec's form", + ) + continue + if _same(before, want): + out[key] = result( + NOT_CHECKED, + "same_as_baseline", + "the value was already shown before, so the read cannot show the change", + ) + continue + out[key] = result(HELD, "shown", "the location shows the expected value") + return out + + +def _combine(key: str, results: Sequence[KeyResult]) -> KeyResult: + """One value's verdict from every location and reading that judged it. + + Any refutation refutes. Otherwise it holds only when every result held, + at the weakest level among them (``check_level``: the weakest wins). + """ + + locs = tuple(dict.fromkeys(loc for r in results for loc in r.locations)) + shown = tuple(s for r in results for s in r.shown) + if not results: + return KeyResult( + key, NOT_CHECKED, "no effect location shows this value", code="no_location" + ) + refuted = [r for r in results if r.status == REFUTED] + if refuted: + return KeyResult( + key, + REFUTED, + refuted[0].reason, + locations=locs, + shown=shown, + code=refuted[0].code, + ) + open_ = [r for r in results if r.status != HELD] + if open_: + return KeyResult( + key, + NOT_CHECKED, + open_[0].reason, + locations=locs, + shown=shown, + code=open_[0].code, + ) + weakest = min(results, key=lambda r: r.level) + bases = {r.basis for r in results if r.level == weakest.level} + basis = bases.pop() if len(bases) == 1 else None + return KeyResult( + key, + HELD, + weakest.reason, + level=weakest.level, + basis=basis, + word=_compat.word(weakest.level, basis, confirmed=True), + code=weakest.code, + locations=locs, + shown=shown, + ) + + +Plan = Union[Mapping[str, Any], Iterable[Sequence[Any]]] + + +def _plan_items(plan: Plan) -> list[tuple[str, Any]]: + items = plan.items() if isinstance(plan, Mapping) else plan + out = [] + for item in items: + pair: Sequence[Any] = item + key, value = pair + out.append((key, value)) + return out + + +@verdict_site("effect_location.evaluate_all", classes="C1 C2 C5") +def evaluate_all( + plan: Plan, + locations: Iterable[EffectLocation], + readings: Iterable[Reading], + *, + run_id: str, +) -> Report: + """Judge every intended value in ``plan`` (key to expected value, or a + list of pairs) from the pack's ``locations`` and the adapter's + ``readings`` for run ``run_id``. + + A key planned twice with different values, two locations with one id, a + location expecting another value than the plan, and a reading no planned + location asked for all keep the run from passing. + """ + + planned: dict[str, Any] = {} + conflicted: set[str] = set() + for key, value in _plan_items(plan): + if key in planned and not _same(planned[key], value): + conflicted.add(key) + planned.setdefault(key, value) + locs = list(locations) + ids: dict[str, int] = {} + for loc in locs: + ids[loc.id] = ids.get(loc.id, 0) + 1 + by_reading: dict[str, list[Reading]] = {} + for one in readings: + by_reading.setdefault(one.location_id, []).append(one) + + judged: dict[str, list[KeyResult]] = {k: [] for k in planned} + used: set[str] = set() + for loc in locs: + relevant = [k for k in loc.keys if k in planned] + if not relevant: + continue + used.add(loc.id) + if ids[loc.id] > 1: + for k in relevant: + judged[k].append( + KeyResult( + k, + NOT_CHECKED, + "two locations share this id", + locations=(loc.id,), + code="duplicate_location", + ) + ) + continue + got = by_reading.get(loc.id, []) + if not got: + for k in relevant: + judged[k].append( + KeyResult( + k, + NOT_CHECKED, + "the location was not read", + locations=(loc.id,), + code="not_read", + ) + ) + continue + # The plan is what must show; a record that expects something else + # was made for another value and can't confirm this one. + planned_loc = loc.with_expected({k: planned[k] for k in relevant}) + for reading in got: + per_key = _judge(planned_loc, reading, run_id) + for k in relevant: + r = per_key[k] + stale = k in loc.expected and not _same(loc.expected[k], planned[k]) + if stale and r.status != REFUTED: + r = KeyResult( + k, + NOT_CHECKED, + "the location expects a different value than the plan", + locations=(loc.id,), + shown=r.shown, + code="stale_record", + ) + judged[k].append(r) + + results = [] + for key in planned: + if key in conflicted: + results.append( + KeyResult( + key, + NOT_CHECKED, + "the plan has two values for this key", + code="plan_conflict", + ) + ) + else: + results.append(_combine(key, judged[key])) + unexpected = tuple(sorted(lid for lid in by_reading if lid not in used)) + + if not results: + status, reason = NOT_CHECKED, "nothing was planned" + elif any(r.status == REFUTED for r in results): + status, reason = REFUTED, "a location shows a different value" + elif all(r.status == HELD for r in results) and not unexpected: + status, reason = HELD, "every planned value was shown where expected" + elif unexpected and all(r.status == HELD for r in results): + status, reason = NOT_CHECKED, "a reading matches no planned location" + else: + status, reason = NOT_CHECKED, "a planned value was not checked" + + level, basis, word = CheckLevel.UNCHECKED, None, None + if status == HELD: + level = min(r.level for r in results) + bases = {r.basis for r in results if r.level == level} + basis = bases.pop() if len(bases) == 1 else None + word = _compat.word(level, basis, confirmed=True) + else: + word = _compat.word(CheckLevel.UNCHECKED, None, confirmed=False) + return Report( + results=tuple(results), + status=status, + reason=reason, + level=level, + basis=basis, + word=word, + unexpected=unexpected, + ) + + +def evaluate( + location: EffectLocation, reading: Optional[Reading], *, run_id: str +) -> Report: + """Judge one location, planned with its own expected values, from one + reading (None when it was not read).""" + + return evaluate_all( + location.expected, + [location], + [] if reading is None else [reading], + run_id=run_id, + ) diff --git a/packages/flow/openadapt_flow/effect_location/record.py b/packages/flow/openadapt_flow/effect_location/record.py new file mode 100644 index 0000000000..601eec48b4 --- /dev/null +++ b/packages/flow/openadapt_flow/effect_location/record.py @@ -0,0 +1,448 @@ +"""The effect-location record (``openadapt.effect-location/v1``) and a reading. + +An :class:`EffectLocation` is data a pack stores for one or more intended +values. It is compiled from a demonstration, never written into the engine: + +- ``path`` and ``start``: the demonstration steps that reach the place where + the value shows, and the condition the re-observation must start from + (:class:`Start`). +- ``locator``: how to find it there (a label, a row key or a region). +- ``expected``: the value each key should show, in the codec's canonical form. +- ``codec``: how displayed text maps to the value (:class:`Codec`). A + ``template`` codec reads one displayed text as several keys, such as one + summary row "Name (DOB)"; a ``split_date`` codec reads several displayed + parts as one key. +- ``expected_count``: how many times the value should show (usually 1). +- ``baseline``: optionally, what the location showed before the action. + +A :class:`Reading` is what an adapter (a browser, an accessibility tree, a +terminal screen, an export) saw when it went back to the location. The +adapter states the start condition it achieved and must bind the reading to +the run; the evaluator judges only what the reading says. + +Kinds are kept as strings so a pack written for a newer engine loads. An +unknown kind is judged ``not_checked``, never guessed. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Optional + +__all__ = [ + "CODEC_KINDS", + "LOCATOR_KINDS", + "SCHEMA", + "Codec", + "EffectLocation", + "Locator", + "Reading", + "Start", +] + +SCHEMA = "openadapt.effect-location/v1" + + +class Start(str, Enum): + """Where the re-observation starts from, weakest first.""" + + #: The screen the action was taken on, read again in place. + SAME_SCREEN = "same_screen" + #: A new navigation to the location in the acting session. + FRESH_NAVIGATION = "fresh_navigation" + #: A separately signed-in, read-only session. + NEW_SESSION = "new_session" + #: Another channel than the acting user interface: an export, an API, + #: a message the system sent. + OTHER_CHANNEL = "other_channel" + + +#: The order of :class:`Start`, weakest first. +START_ORDER: tuple[Start, ...] = tuple(Start) + +LOCATOR_KINDS = frozenset({"label", "row_key", "region"}) +CODEC_KINDS = frozenset( + { + "text", + "fold", + "number", + "money", + "unit", + "date", + "bool", + "enum", + "split_date", + "template", + } +) +#: Codecs that read one displayed text as one key. +SCALAR_KINDS = CODEC_KINDS - {"split_date", "template"} + + +def _strs(value: Any, name: str) -> tuple[str, ...]: + if isinstance(value, str) or not isinstance(value, Sequence): + raise ValueError(f"{name} must be a list of strings") + out = tuple(value) + if not all(isinstance(v, str) for v in out): + raise ValueError(f"{name} must be a list of strings") + return out + + +def _only(data: Mapping[str, Any], allowed: set[str], what: str) -> None: + if not isinstance(data, Mapping): + raise ValueError(f"{what} must be an object") + extra = set(data) - allowed + if extra: + raise ValueError(f"{what} has unknown fields {sorted(extra)}") + + +@dataclass(frozen=True) +class Locator: + """How to find the location on the screen or channel it is read from. + + ``kind`` is ``label`` (a label or heading next to the value), ``row_key`` + (a table or list row whose ``column`` cell equals ``value``) or ``region`` + (a named area). ``value`` and ``section`` are patterns or texts from the + demonstration; the adapter interprets them, the evaluator does not. + """ + + kind: str + value: str + section: str = "" + column: str = "" + + def to_dict(self) -> dict[str, Any]: + return { + "kind": self.kind, + "value": self.value, + "section": self.section, + "column": self.column, + } + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> "Locator": + _only(data, {"kind", "value", "section", "column"}, "locator") + out = cls( + kind=data["kind"], + value=data["value"], + section=data.get("section", ""), + column=data.get("column", ""), + ) + for name in ("kind", "value", "section", "column"): + if not isinstance(getattr(out, name), str): + raise ValueError(f"locator {name} must be a string") + return out + + +@dataclass(frozen=True) +class Part: + """One named group of a ``template`` codec: the key it shows and its codec.""" + + group: str + key: str + codec: "Codec" + + +@dataclass(frozen=True) +class Codec: + """How displayed text maps to a value. Every word and symbol is data. + + ``kind`` and its parameters: + + - ``text``: whitespace collapsed, compared exactly. ``fold``: also + case-folded. + - ``number``: a decimal number. ``money``: an amount, compared in minor + units (``decimals`` places). ``unit``: a number followed by one of + ``units``. ``affixes`` are the symbols allowed before or after the + number (a currency sign); ``group_marks`` and ``decimal_mark`` are the + separators. + - ``date``: an ISO date, or a numeric date in ``date_order`` (``YMD``, + ``MDY`` or ``DMY``), or with a month spelled as in ``month_names``. + - ``bool``: one of ``true_tokens`` or ``false_tokens`` (case-folded). + - ``enum``: the displayed text, case-folded, looked up in ``table``. + - ``split_date``: the parts ``year``, ``month`` and ``day`` read + separately (a month by number or by ``month_names``). + - ``template``: ``pattern`` must match the whole displayed text; each of + ``parts`` reads one named group as one key. + + With no tokens, names, affixes or table given, only the bare form is + accepted: a pack that needs more says so. + """ + + kind: str + date_order: str = "" + month_names: tuple[tuple[str, ...], ...] = () + true_tokens: tuple[str, ...] = () + false_tokens: tuple[str, ...] = () + table: tuple[tuple[str, str], ...] = () + units: tuple[str, ...] = () + affixes: tuple[str, ...] = () + group_marks: tuple[str, ...] = (",",) + decimal_mark: str = "." + decimals: int = 2 + pattern: str = "" + parts: tuple[Part, ...] = () + + def keys(self) -> tuple[str, ...]: + """The keys a ``template`` codec shows (empty for other kinds).""" + + return tuple(p.key for p in self.parts) + + def to_dict(self) -> dict[str, Any]: + out: dict[str, Any] = {"kind": self.kind} + defaults = Codec(kind=self.kind) + for name in ( + "date_order", + "true_tokens", + "false_tokens", + "units", + "affixes", + "group_marks", + "decimal_mark", + "decimals", + "pattern", + ): + value = getattr(self, name) + if value != getattr(defaults, name): + out[name] = list(value) if isinstance(value, tuple) else value + if self.month_names: + out["month_names"] = [list(m) for m in self.month_names] + if self.table: + out["table"] = {shown: value for shown, value in self.table} + if self.parts: + out["parts"] = [ + {"group": p.group, "key": p.key, "codec": p.codec.to_dict()} + for p in self.parts + ] + return out + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> "Codec": + names = { + "kind", + "date_order", + "month_names", + "true_tokens", + "false_tokens", + "table", + "units", + "affixes", + "group_marks", + "decimal_mark", + "decimals", + "pattern", + "parts", + } + _only(data, names, "codec") + kind = data["kind"] + if not isinstance(kind, str): + raise ValueError("codec kind must be a string") + kw: dict[str, Any] = {"kind": kind} + for name in ("true_tokens", "false_tokens", "units", "affixes", "group_marks"): + if name in data: + kw[name] = _strs(data[name], name) + for name in ("date_order", "decimal_mark", "pattern"): + if name in data: + if not isinstance(data[name], str): + raise ValueError(f"codec {name} must be a string") + kw[name] = data[name] + if "decimals" in data: + d = data["decimals"] + if not isinstance(d, int) or isinstance(d, bool) or not 0 <= d <= 6: + raise ValueError("codec decimals must be an integer from 0 to 6") + kw["decimals"] = d + if "month_names" in data: + months = data["month_names"] + if isinstance(months, str) or not isinstance(months, Sequence): + raise ValueError("month_names must be twelve lists of names") + kw["month_names"] = tuple(_strs(m, "month_names") for m in months) + if len(kw["month_names"]) != 12: + raise ValueError("month_names must be twelve lists of names") + if "table" in data: + table = data["table"] + if not isinstance(table, Mapping) or not all( + isinstance(k, str) and isinstance(v, str) for k, v in table.items() + ): + raise ValueError("codec table must map strings to strings") + kw["table"] = tuple(table.items()) + if "parts" in data: + parts = data["parts"] + if isinstance(parts, str) or not isinstance(parts, Sequence): + raise ValueError("codec parts must be a list") + built = [] + for p in parts: + _only(p, {"group", "key", "codec"}, "codec part") + if not isinstance(p["group"], str) or not isinstance(p["key"], str): + raise ValueError("codec part group and key must be strings") + built.append(Part(p["group"], p["key"], cls.from_dict(p["codec"]))) + kw["parts"] = tuple(built) + return cls(**kw) + + +@dataclass(frozen=True) +class EffectLocation: + """Where one or more intended values show after the action. See the module.""" + + id: str + keys: tuple[str, ...] + path: tuple[str, ...] + start: str + locator: Locator + codec: Codec + expected: Mapping[str, Any] = field(default_factory=dict) + expected_count: int = 1 + baseline: Optional[Mapping[str, Any]] = None + #: Where the record came from (a demonstration id), for people. + source: str = "" + + def with_expected(self, values: Mapping[str, Any]) -> "EffectLocation": + """A copy expecting ``values`` for its keys (other keys are ignored).""" + + return EffectLocation( + id=self.id, + keys=self.keys, + path=self.path, + start=self.start, + locator=self.locator, + codec=self.codec, + expected={k: values[k] for k in self.keys if k in values}, + expected_count=self.expected_count, + baseline=self.baseline, + source=self.source, + ) + + def to_dict(self) -> dict[str, Any]: + out: dict[str, Any] = { + "schema": SCHEMA, + "id": self.id, + "keys": list(self.keys), + "path": list(self.path), + "start": self.start, + "locator": self.locator.to_dict(), + "codec": self.codec.to_dict(), + "expected": dict(self.expected), + "expected_count": self.expected_count, + } + if self.baseline is not None: + out["baseline"] = dict(self.baseline) + if self.source: + out["source"] = self.source + return out + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> "EffectLocation": + names = { + "schema", + "id", + "keys", + "path", + "start", + "locator", + "codec", + "expected", + "expected_count", + "baseline", + "source", + } + _only(data, names, "effect location") + if data.get("schema") != SCHEMA: + raise ValueError(f"effect location schema must be {SCHEMA!r}") + # Required, not defaulted: a record that doesn't say how many times + # the value shows can't tell one match from the only match. + if "expected_count" not in data: + raise ValueError("effect location needs expected_count") + count = data["expected_count"] + if not isinstance(count, int) or isinstance(count, bool): + raise ValueError("expected_count must be an integer") + expected = data.get("expected", {}) + baseline = data.get("baseline") + if not isinstance(expected, Mapping) or ( + baseline is not None and not isinstance(baseline, Mapping) + ): + raise ValueError("expected and baseline must be objects") + for name in ("id", "start", "source"): + if not isinstance(data.get(name, ""), str): + raise ValueError(f"effect location {name} must be a string") + return cls( + id=data["id"], + keys=_strs(data["keys"], "keys"), + path=_strs(data.get("path", ()), "path"), + start=data["start"], + locator=Locator.from_dict(data["locator"]), + codec=Codec.from_dict(data["codec"]), + expected=dict(expected), + expected_count=count, + baseline=None if baseline is None else dict(baseline), + source=data.get("source", ""), + ) + + +@dataclass(frozen=True) +class Reading: + """What an adapter saw at one location, bound to one run. + + ``matches`` holds one entry per place the locator matched: a mapping of + part name to displayed text (``text`` for a single text; ``year``, + ``month`` and ``day`` for a split date). ``complete`` is false when the + adapter could not read the whole located area (a truncated table, a + capped page), so a match can't be shown to be the only one. ``error`` is + set when the read failed. ``start`` is the start condition the adapter + achieved and can show; ``basis`` names who produced the evidence for an + ``other_channel`` read (``system_api``, ``activity_log``, ``db_frame`` or + ``owned_connection``). + """ + + location_id: str + run_id: str + start: str + matches: tuple[Mapping[str, Any], ...] + complete: bool + error: Optional[str] + basis: Optional[str] = None + + def to_dict(self) -> dict[str, Any]: + return { + "location_id": self.location_id, + "run_id": self.run_id, + "start": self.start, + "matches": [dict(m) for m in self.matches], + "complete": self.complete, + "error": self.error, + "basis": self.basis, + } + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> "Reading": + """Every field is required, ``error`` and ``basis`` as null when unset: + a reading that leaves out whether it was complete or failed is not + evidence.""" + + names = { + "location_id", + "run_id", + "start", + "matches", + "complete", + "error", + "basis", + } + _only(data, names, "reading") + missing = names - set(data) + if missing: + raise ValueError(f"reading is missing {sorted(missing)}") + matches = data["matches"] + if isinstance(matches, (str, Mapping)) or not isinstance(matches, Sequence): + raise ValueError("reading matches must be a list") + if not all(isinstance(m, Mapping) for m in matches): + raise ValueError("each reading match must be an object") + return cls( + location_id=data["location_id"], + run_id=data["run_id"], + start=data["start"], + matches=tuple(dict(m) for m in matches), + complete=data["complete"], + error=data["error"], + basis=data["basis"], + ) diff --git a/packages/flow/tests/test_effect_location.py b/packages/flow/tests/test_effect_location.py new file mode 100644 index 0000000000..5a60d0a23b --- /dev/null +++ b/packages/flow/tests/test_effect_location.py @@ -0,0 +1,513 @@ +"""The effect-location record and its evaluator (synthetic readings only).""" + +from __future__ import annotations + +import json +from decimal import Decimal +from typing import Any + +import pytest +from openadapt_types.check_level import CheckLevel + +from openadapt_flow.effect_location import ( + Codec, + EffectLocation, + Locator, + Reading, + _compat, + decode, + evaluate, + evaluate_all, +) +from openadapt_flow.effect_location.record import Part + +RUN = "run-1" +DMY_MONTHS = tuple( + (name,) + for name in ( + "m01", "m02", "m03", "m04", "m05", "m06", + "m07", "m08", "m09", "m10", "m11", "m12", + ) +) # fmt: skip + + +def loc( + keys: tuple[str, ...] = ("name",), + codec: Codec | None = None, + expected: dict[str, Any] | None = None, + start: str = "same_screen", + **kw: Any, +) -> EffectLocation: + return EffectLocation( + id=kw.pop("id", "L1"), + keys=keys, + path=("step-1", "step-2"), + start=start, + locator=kw.pop("locator", Locator("label", "^Name$")), + codec=codec or Codec("text"), + expected={"name": "Ada Byron"} if expected is None else expected, + **kw, + ) + + +def reading(*texts: Any, **kw: Any) -> Reading: + matches = kw.pop("matches", None) + return Reading( + location_id=kw.pop("location_id", "L1"), + run_id=kw.pop("run_id", RUN), + start=kw.pop("start", "same_screen"), + matches=tuple(matches) + if matches is not None + else tuple({"text": t} for t in texts), + complete=kw.pop("complete", True), + error=kw.pop("error", None), + basis=kw.pop("basis", None), + ) + + +def status(location: EffectLocation, r: Reading | None) -> str: + return evaluate(location, r, run_id=RUN).status + + +# -- one scalar location --------------------------------------------------------- + + +def test_shown_value_holds_at_the_start_level() -> None: + report = evaluate(loc(), reading("Ada Byron"), run_id=RUN) + assert report.status == "held" + assert report.level is CheckLevel.SAME_SCREEN + assert report.results[0].locations == ("L1",) + + +@pytest.mark.parametrize( + "shown", ["Ada", "Ada Byron 0", "Ada Byron (old)", "", "ada byron"] +) +def test_close_text_refutes(shown: str) -> None: + assert status(loc(), reading(shown)) == "refuted" + + +def test_fold_ignores_case_only() -> None: + folded = loc(codec=Codec("fold")) + assert status(folded, reading("ADA byron")) == "held" + assert status(folded, reading("ADA byro")) == "refuted" + + +@pytest.mark.parametrize( + ("r", "why"), + [ + (None, "the location was not read"), + (reading(), "the location was not found"), + (reading("Ada Byron", "Ada Byron"), "found 2 times, expected 1"), + (reading("Ada Byron", error="timeout"), "the read failed"), + (reading("Ada Byron", run_id="other"), "the reading belongs to another run"), + (reading("Ada Byron", complete=False), "the read was partial"), + (reading(matches=[{"text": None}]), "the displayed text could not be read"), + ( + reading(matches=[{"text": "Ada Byron", "x": "1"}]), + "the displayed text could not be read", + ), + ], +) +def test_what_cannot_be_read_is_not_checked(r: Reading | None, why: str) -> None: + report = evaluate(loc(), r, run_id=RUN) + assert report.status == "not_checked" + assert report.results[0].reason == why + assert report.level is CheckLevel.UNCHECKED + + +def test_a_partial_read_still_refutes() -> None: + assert status(loc(), reading("Grace", complete=False)) == "refuted" + + +def test_expected_count_two() -> None: + twice = loc(expected_count=2) + assert status(twice, reading("Ada Byron", "Ada Byron")) == "held" + assert status(twice, reading("Ada Byron")) == "not_checked" + assert status(twice, reading("Ada Byron", "Grace")) == "refuted" + + +@pytest.mark.parametrize( + "bad", + [ + {"locator": Locator("pixel", "x")}, + {"codec": Codec("guess")}, + {"start": "telepathy"}, + {"expected_count": 0}, + {"keys": ("name", "name")}, + ], +) +def test_unknown_or_malformed_records_are_not_checked(bad: dict[str, Any]) -> None: + assert status(loc(**bad), reading("Ada Byron")) == "not_checked" + + +def test_the_start_condition_must_be_met() -> None: + wanted = loc(start="new_session") + assert status(wanted, reading("Ada Byron")) == "not_checked" + assert ( + status(wanted, reading("Ada Byron", start="fresh_navigation")) == "not_checked" + ) + assert status(wanted, reading("Ada Byron", start="new_session")) == "held" + stronger = evaluate(loc(), reading("Ada Byron", start="new_session"), run_id=RUN) + assert stronger.level is CheckLevel.SEPARATE_SESSION + + +def test_start_conditions_map_to_levels() -> None: + levels = { + s: evaluate(loc(start=s), reading("Ada Byron", start=s), run_id=RUN).level + for s in ("same_screen", "fresh_navigation", "new_session", "other_channel") + } + assert levels == { + "same_screen": CheckLevel.SAME_SCREEN, + "fresh_navigation": CheckLevel.REOPENED, + "new_session": CheckLevel.SEPARATE_SESSION, + "other_channel": CheckLevel.SYSTEM_OF_RECORD, + } + + +# -- baseline -------------------------------------------------------------------- + + +def test_a_value_that_was_already_there_proves_nothing() -> None: + same = loc(baseline={"name": "Ada Byron"}) + report = evaluate(same, reading("Ada Byron"), run_id=RUN) + assert report.status == "not_checked" + assert "already shown before" in report.results[0].reason + + +def test_a_location_still_showing_the_baseline_refutes() -> None: + changed = loc(baseline={"name": "Grace"}) + assert status(changed, reading("Grace")) == "refuted" + assert status(changed, reading("Ada Byron")) == "held" + + +# -- codecs ---------------------------------------------------------------------- + + +def test_money_compares_whole_amounts_in_minor_units() -> None: + money = Codec("money", affixes=("$",)) + m = loc(keys=("cost",), codec=money, expected={"cost": 125000}) + assert status(m, reading("$1,250.00")) == "held" + assert status(m, reading("1,250")) == "held" + assert status(m, reading("$250.00")) == "refuted" + assert status(m, reading("$1,250.005")) == "not_checked" + assert status(m, reading("$12,50.00")) == "not_checked" + no_affix = loc(keys=("cost",), codec=Codec("money"), expected={"cost": 125000}) + assert status(no_affix, reading("$1,250.00")) == "not_checked" + refund = loc(keys=("cost",), codec=money, expected={"cost": -25000}) + assert status(refund, reading("-$250.00")) == "held" + assert status(refund, reading("$-250.00")) == "held" + assert status(refund, reading("--$250.00")) == "not_checked" + as_text = loc(keys=("cost",), codec=money, expected={"cost": "125000"}) + assert status(as_text, reading("$1,250.00")) == "not_checked" + + +def test_units_and_numbers() -> None: + unit = loc(keys=("w",), codec=Codec("unit", units=("kg",)), expected={"w": "12.5"}) + assert status(unit, reading("12.50 kg")) == "held" + assert status(unit, reading("12.5kg")) == "held" + assert status(unit, reading("12.5 lb")) == "not_checked" + assert status(unit, reading("13 kg")) == "refuted" + dec = loc(keys=("n",), codec=Codec("number"), expected={"n": Decimal("2.50")}) + assert status(dec, reading("2.5")) == "held" + nan = loc(keys=("n",), codec=Codec("number"), expected={"n": Decimal("NaN")}) + assert status(nan, reading("2.5")) == "not_checked" + num = loc(keys=("n",), codec=Codec("number"), expected={"n": True}) + assert status(num, reading("1")) == "not_checked" + + +def test_dates_need_an_order_unless_iso() -> None: + iso = loc(keys=("d",), codec=Codec("date"), expected={"d": "2024-03-07"}) + assert status(iso, reading("2024-03-07")) == "held" + assert status(iso, reading("03/07/2024")) == "not_checked" + mdy = loc( + keys=("d",), codec=Codec("date", date_order="MDY"), expected={"d": "2024-03-07"} + ) + assert status(mdy, reading("03/07/2024")) == "held" + assert status(mdy, reading("07/03/2024")) == "refuted" + assert status(mdy, reading("02/30/2024")) == "not_checked" + spelled = loc( + keys=("d",), + codec=Codec("date", date_order="DMY", month_names=DMY_MONTHS), + expected={"d": "2024-03-07"}, + ) + assert status(spelled, reading("7 M03 2024")) == "held" + assert status(spelled, reading("7 m13 2024")) == "not_checked" + + +def test_split_date_reads_three_parts_as_one_value() -> None: + split = loc( + keys=("dob",), codec=Codec("split_date"), expected={"dob": "1990-01-31"} + ) + good = {"year": "1990", "month": "1", "day": "31"} + assert status(split, reading(matches=[good])) == "held" + assert status(split, reading(matches=[{**good, "day": "30"}])) == "refuted" + assert status(split, reading(matches=[{**good, "day": "32"}])) == "not_checked" + assert ( + status(split, reading(matches=[{"year": "1990", "month": "1"}])) + == "not_checked" + ) + + +def test_bool_and_enum_need_their_tables() -> None: + b = loc(keys=("ok",), codec=Codec("bool"), expected={"ok": True}) + assert status(b, reading("yes")) == "not_checked" + tokens = Codec("bool", true_tokens=("ja",), false_tokens=("nein",)) + b2 = loc(keys=("ok",), codec=tokens, expected={"ok": True}) + assert status(b2, reading("JA")) == "held" + assert status(b2, reading("nein")) == "refuted" + e = loc( + keys=("s",), + codec=Codec("enum", table=(("Ontario", "ON"),)), + expected={"s": "ON"}, + ) + assert status(e, reading("ontario")) == "held" + assert status(e, reading("Onta")) == "not_checked" + + +# -- composite: one summary row covering two values ----------------------------- + +ROW = Codec( + "template", + pattern=r"(?P.+) \((?P[^)]*)\)", + parts=( + Part("n", "traveller_name", Codec("text")), + Part("d", "traveller_dob", Codec("date", date_order="MDY")), + ), +) +ROW_EXPECTED = {"traveller_name": "Ada Byron", "traveller_dob": "1990-01-31"} + + +def row_loc(**kw: Any) -> EffectLocation: + return loc( + keys=("traveller_name", "traveller_dob"), codec=ROW, expected=ROW_EXPECTED, **kw + ) + + +def test_a_summary_row_checks_both_values() -> None: + report = evaluate(row_loc(), reading("Ada Byron (01/31/1990)"), run_id=RUN) + assert report.status == "held" + assert {r.key: r.status for r in report.results} == { + "traveller_name": "held", + "traveller_dob": "held", + } + + +def test_one_wrong_part_refutes_only_that_value() -> None: + report = evaluate(row_loc(), reading("Ada Byron (01/30/1990)"), run_id=RUN) + assert report.by_key()["traveller_name"].status == "held" + assert report.by_key()["traveller_dob"].status == "refuted" + assert report.status == "refuted" + + +def test_a_row_that_does_not_fit_leaves_both_not_checked() -> None: + report = evaluate(row_loc(), reading("Ada Byron, 01/31/1990"), run_id=RUN) + assert {r.status for r in report.results} == {"not_checked"} + + +def test_a_template_must_name_each_key() -> None: + bad = loc(keys=("traveller_name",), codec=ROW, expected=ROW_EXPECTED) + assert status(bad, reading("Ada Byron (01/31/1990)")) == "not_checked" + + +def test_decode_reports_errors_per_key() -> None: + out = decode( + ROW, {"text": "Ada Byron (13/31/1990)"}, ("traveller_name", "traveller_dob") + ) + assert out["traveller_name"] == "Ada Byron" + assert isinstance(out["traveller_dob"], ValueError) + + +# -- a run's plan ---------------------------------------------------------------- + + +def test_every_planned_value_needs_a_location() -> None: + report = evaluate_all( + {"name": "Ada Byron", "email": "a@example.test"}, + [loc()], + [reading("Ada Byron")], + run_id=RUN, + ) + assert report.status == "not_checked" + assert report.by_key()["email"].reason == "no effect location shows this value" + + +def test_an_empty_plan_never_passes() -> None: + assert ( + evaluate_all({}, [loc()], [reading("Ada Byron")], run_id=RUN).status + == "not_checked" + ) + assert evaluate_all({}, [], [], run_id=RUN).status == "not_checked" + + +def test_the_plan_decides_the_expected_value() -> None: + template = loc(expected={}) + assert evaluate_all( + {"name": "Ada Byron"}, [template], [reading("Ada Byron")], run_id=RUN + ).passes + stale = loc(expected={"name": "Grace"}) + report = evaluate_all( + {"name": "Ada Byron"}, [stale], [reading("Ada Byron")], run_id=RUN + ) + assert report.status == "not_checked" + assert "different value than the plan" in report.results[0].reason + + +def test_left_over_readings_and_duplicates_do_not_pass() -> None: + extra = evaluate_all( + {"name": "Ada Byron"}, + [loc()], + [reading("Ada Byron"), reading("x", location_id="L9")], + run_id=RUN, + ) + assert extra.status == "not_checked" and extra.unexpected == ("L9",) + twice = evaluate_all( + {"name": "Ada Byron"}, [loc(), loc()], [reading("Ada Byron")], run_id=RUN + ) + assert twice.status == "not_checked" + plan_twice = evaluate_all( + [("name", "Ada Byron"), ("name", "Grace")], + [loc()], + [reading("Ada Byron")], + run_id=RUN, + ) + assert plan_twice.status == "not_checked" + + +def test_two_readings_of_one_location_must_agree() -> None: + both = evaluate_all( + {"name": "Ada Byron"}, + [loc()], + [reading("Ada Byron"), reading("Grace")], + run_id=RUN, + ) + assert both.status == "refuted" + same = evaluate_all( + {"name": "Ada Byron"}, + [loc()], + [reading("Ada Byron"), reading("Ada Byron")], + run_id=RUN, + ) + assert same.status == "held" + + +def test_the_weakest_location_sets_the_level() -> None: + review = loc(id="review") + fresh = loc(id="session", start="new_session") + report = evaluate_all( + {"name": "Ada Byron"}, + [review, fresh], + [ + reading("Ada Byron", location_id="review"), + reading("Ada Byron", location_id="session", start="new_session"), + ], + run_id=RUN, + ) + assert report.status == "held" + assert report.level is CheckLevel.SAME_SCREEN + + +def test_a_missing_run_id_never_passes() -> None: + assert ( + evaluate(loc(), reading("Ada Byron", run_id=""), run_id="").status + == "not_checked" + ) + + +# -- receipt words (the ladder from #2495) --------------------------------------- + +needs_words = pytest.mark.skipif( + not _compat.has_ladder_words(), + reason="check_level.outcome_word is not on this branch yet", +) + + +@needs_words +@pytest.mark.parametrize( + ("start", "basis", "word"), + [ + ("same_screen", None, "SHOWN"), + ("fresh_navigation", None, "SHOWN"), + ("new_session", None, "VERIFIED"), + ("other_channel", None, "RECORDED"), + ("other_channel", "db_frame", "VERIFIED"), + ("other_channel", "separate_session", "RECORDED"), + ("same_screen", "db_frame", "SHOWN"), + ], +) +def test_words_come_from_the_ladder(start: str, basis: str | None, word: str) -> None: + report = evaluate( + loc(start=start), reading("Ada Byron", start=start, basis=basis), run_id=RUN + ) + assert report.status == "held" + assert report.word == word + + +@needs_words +def test_a_check_that_did_not_hold_is_recorded() -> None: + assert evaluate(loc(), reading("Grace"), run_id=RUN).word == "RECORDED" + + +def test_without_the_ladder_no_word_is_invented() -> None: + if _compat.has_ladder_words(): + pytest.skip("the ladder is on this branch") + assert evaluate(loc(), reading("Ada Byron"), run_id=RUN).word is None + + +# -- the record as data ---------------------------------------------------------- + + +def test_round_trip_through_json() -> None: + record = row_loc(baseline={"traveller_name": "x"}, source="demo-1") + data = json.loads(json.dumps(record.to_dict())) + assert EffectLocation.from_dict(data) == record + r = reading("Ada Byron (01/31/1990)") + assert Reading.from_dict(json.loads(json.dumps(r.to_dict()))) == r + + +def test_parsing_is_strict() -> None: + data = loc().to_dict() + with pytest.raises(ValueError): + EffectLocation.from_dict({**data, "surprise": 1}) + with pytest.raises(ValueError): + EffectLocation.from_dict({**data, "schema": "other/v1"}) + with pytest.raises(ValueError): + EffectLocation.from_dict({**data, "codec": {"kind": "text", "units": "kg"}}) + r = reading("Ada Byron").to_dict() + for name in r: + gone = dict(r) + del gone[name] + with pytest.raises(ValueError): + Reading.from_dict(gone) + + +def test_unknown_kinds_load_and_judge_not_checked() -> None: + data = {**loc().to_dict(), "codec": {"kind": "future_kind"}} + future = EffectLocation.from_dict(data) + assert status(future, reading("Ada Byron")) == "not_checked" + + +def test_every_result_carries_a_listed_code() -> None: + from openadapt_flow.effect_location.evaluator import CODES + + cases = [ + (loc(), reading("Ada Byron"), "shown"), + (loc(), reading("Grace"), "mismatch"), + (loc(), reading(), "not_found"), + (loc(), reading("Ada Byron", "Ada Byron"), "count_mismatch"), + (loc(), reading(matches=[{"text": 3}]), "unreadable"), + (loc(), reading("Ada Byron", error="x"), "read_failed"), + (loc(), reading("Ada Byron", complete=False), "partial"), + (loc(), None, "not_read"), + (loc(codec=Codec("guess")), reading("Ada Byron"), "bad_record"), + (loc(baseline={"name": "Ada Byron"}), reading("Ada Byron"), "same_as_baseline"), + ] + for location, r, code in cases: + got = evaluate(location, r, run_id=RUN).results[0].code + assert got == code and got in CODES, (code, got) + stale = evaluate_all( + {"name": "Ada Byron"}, + [loc(expected={"name": "G"})], + [reading("Ada Byron")], + run_id=RUN, + ) + assert stale.results[0].code == "stale_record" From 59e757a9003e9c980b4ca47c31661e72bf853c0d Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:22:01 -0500 Subject: [PATCH 2/2] refactor(form-tx): judge the review page's text through an effect location Before submit, form_tx reads the review screen and stops when a value differs from the intake. For a value shown as page text under the whitespace_collapse or casefold codec, that comparison is now an openadapt.effect-location/v1 record (start same_screen) judged by the shared evaluator. Every other codec, checkbox and radio bindings (which fall back to yes or no), and values held in form controls keep form_tx's own comparison. No decision changes: a differential test runs the old comparison (vendored from 1ddd69712) and the port over a corpus of intake values and shown texts for every ported binding. A value found but not held still stops the run; only "not shown" and "shown more than once" are skips, as before. --- .../flow/openadapt_flow/form_tx/reconciler.py | 19 ++- .../openadapt_flow/form_tx/review_location.py | 122 ++++++++++++++ .../tests/test_form_tx_review_location.py | 152 ++++++++++++++++++ 3 files changed, 288 insertions(+), 5 deletions(-) create mode 100644 packages/flow/openadapt_flow/form_tx/review_location.py create mode 100644 packages/flow/tests/test_form_tx_review_location.py diff --git a/packages/flow/openadapt_flow/form_tx/reconciler.py b/packages/flow/openadapt_flow/form_tx/reconciler.py index 5c00b5366a..0e19114b86 100644 --- a/packages/flow/openadapt_flow/form_tx/reconciler.py +++ b/packages/flow/openadapt_flow/form_tx/reconciler.py @@ -1630,6 +1630,7 @@ def _review_mismatch_halt( _observed_control_matches, _text_pair_matches, ) + from openadapt_flow.form_tx.review_location import review_text_matches for rb in check.review_readbacks: fact = session.effective_facts.get(rb.dossier_key) @@ -1654,11 +1655,19 @@ def _review_mismatch_halt( session._review_skipped[rb.dossier_key] = "not shown on the review" continue session._review_skipped.pop(rb.dossier_key, None) - ok = ( - _observed_control_matches(fact.value, ctrl, rb) - if ctrl is not None - else pair is not None and _text_pair_matches(fact.value, pair, rb) - ) + if ctrl is not None: + ok = _observed_control_matches(fact.value, ctrl, rb) + elif pair is not None: + ported = review_text_matches( + rb, fact.value, pair, run_id=session.run_id + ) + ok = ( + _text_pair_matches(fact.value, pair, rb) + if ported is None + else ported + ) + else: + ok = False if ok: continue shown = ( diff --git a/packages/flow/openadapt_flow/form_tx/review_location.py b/packages/flow/openadapt_flow/form_tx/review_location.py new file mode 100644 index 0000000000..356bfb5509 --- /dev/null +++ b/packages/flow/openadapt_flow/form_tx/review_location.py @@ -0,0 +1,122 @@ +"""The review page as an effect location: echo before commit. + +Before submit, form_tx reads the review screen and stops when it shows a +value other than the intake's. This module states that check as an +``openadapt.effect-location/v1`` record (start ``same_screen``) and judges it +with the shared evaluator, :mod:`openadapt_flow.effect_location`, for the +value a review page shows as page text. + +Only the codecs whose reading the shared codecs reproduce exactly are ported: +``whitespace_collapse`` and ``casefold``. For any other codec, a checkbox or +radio binding (whose text falls back to yes or no), and a value held in a form +control (which may match by its option label), :func:`review_text_matches` +returns None and the caller keeps form_tx's own comparison. +``tests/test_form_tx_review_location.py`` compares the two over a corpus. + +Gate direction: a value that is found but does not hold stops the run, as it +did before. Only "not shown" and "shown more than once" are skips, and those +are decided before this module is called. +""" + +from __future__ import annotations + +from typing import Any, Optional + +from openadapt_flow.effect_location import ( + Codec, + EffectLocation, + Locator, + Reading, + evaluate, +) +from openadapt_flow.form_tx.codecs import ( + CodecValueError, + collapse_whitespace, + normalize_with_codec, +) +from openadapt_flow.form_tx.types import ( + ControlKind, + FieldBindingSpec, + FormCodecKind, + ObservedTextPair, +) + +__all__ = ["PORTED_CODECS", "review_location", "review_text_matches"] + +#: form_tx codec kind to the shared codec kind that reads text the same way. +PORTED_CODECS: dict[FormCodecKind, str] = { + FormCodecKind.WHITESPACE_COLLAPSE: "text", + FormCodecKind.CASEFOLD: "fold", +} + +#: Bindings whose page text is also read as yes or no: kept on form_tx's path. +_YES_NO_BINDINGS = frozenset({ControlKind.CHECKBOX, ControlKind.RADIO_GROUP}) + + +def review_location( + binding: FieldBindingSpec, intake_value: Any +) -> Optional[EffectLocation]: + """The review-page effect location for ``binding``, or None when this + binding stays on form_tx's comparison (see the module).""" + + kind = PORTED_CODECS.get(binding.codec.kind) + if kind is None or binding.control_kind in _YES_NO_BINDINGS: + return None + try: + expected = normalize_with_codec(intake_value, binding.codec) + except CodecValueError: + return None + if not isinstance(expected, str): + return None + return EffectLocation( + id=f"review:{binding.dossier_key}", + keys=(binding.dossier_key,), + path=(), + start="same_screen", + locator=Locator( + kind="label", + value="|".join(binding.anchor.label_patterns), + section="|".join(binding.anchor.section_patterns), + ), + codec=Codec(kind), + expected={binding.dossier_key: expected}, + expected_count=1, + source="form_tx.summary_check.review_readbacks", + ) + + +def _placeholder_or_empty(value: str, placeholders: tuple[str, ...]) -> bool: + norm = collapse_whitespace(value).casefold() + return not norm or norm in {collapse_whitespace(p).casefold() for p in placeholders} + + +def review_text_matches( + binding: FieldBindingSpec, + intake_value: Any, + pair: ObservedTextPair, + *, + run_id: str, +) -> Optional[bool]: + """Whether the review page's text ``pair`` shows the intake value. + + True when the effect location holds. False when it does not: refuted, + or found but not readable as the value, and that stops the run. None when + the binding is not ported, so the caller compares it the old way. + """ + + location = review_location(binding, intake_value) + if location is None: + return None + # A placeholder ("-- Select --") is never the value, even when the intake + # happens to read the same. The placeholder list is the binding's data. + if _placeholder_or_empty(pair.value, binding.placeholder_values): + return False + reading = Reading( + location_id=location.id, + run_id=run_id, + start="same_screen", + matches=({"text": pair.value},), + complete=True, + error=None, + ) + return evaluate(location, reading, run_id=run_id).passes diff --git a/packages/flow/tests/test_form_tx_review_location.py b/packages/flow/tests/test_form_tx_review_location.py new file mode 100644 index 0000000000..633aa2b23a --- /dev/null +++ b/packages/flow/tests/test_form_tx_review_location.py @@ -0,0 +1,152 @@ +"""The review page's text check, ported onto the effect-location record. + +The port must not change a single decision. ``_old_text_pair_matches`` is +form_tx's comparison as it was before the port (vendored below from +``openadapt_flow/form_tx/judge.py`` at 1ddd69712, lines 129 to 184). Every +intake value and every shown text in the corpus, under every ported binding, +gets the same answer from the old comparison and from the effect location. +Bindings that are not ported return None and keep the old comparison. +""" + +from __future__ import annotations + +import itertools +from typing import Any + +import pytest + +from openadapt_flow.form_tx.codecs import collapse_whitespace, values_equivalent +from openadapt_flow.form_tx.review_location import ( + PORTED_CODECS, + review_location, + review_text_matches, +) +from openadapt_flow.form_tx.types import ( + ControlKind, + FieldAnchorSpec, + FieldBindingSpec, + FieldCodecSpec, + FormCodecKind, + ObservedTextPair, +) + + +# vendored: 1ddd69712:packages/flow/openadapt_flow/form_tx/judge.py 129-134 +def _old_is_placeholder_or_empty(value: str, placeholders: Any) -> bool: + norm = collapse_whitespace(value).casefold() + if not norm: + return True + placeholder_set = {collapse_whitespace(p).casefold() for p in placeholders} + return norm in placeholder_set + + +# vendored: 1ddd69712:packages/flow/openadapt_flow/form_tx/judge.py 167-184 +def _old_text_pair_matches(expected_val: Any, pair: Any, binding: Any) -> bool: + if _old_is_placeholder_or_empty(pair.value, binding.placeholder_values): + return False + if values_equivalent(expected_val, pair.value, binding.codec): + return True + if binding.control_kind in (ControlKind.CHECKBOX, ControlKind.RADIO_GROUP): + return values_equivalent( + expected_val, + pair.value, + FieldCodecSpec(kind=FormCodecKind.BOOLEAN_YES_NO), + ) + return False + + +TEXTS = [ + "Ada Byron", + "Ada Byron", + " ada\tbyron\n", + "ADA BYRON", + "Ada", + "Ada Byron 0", + "Ada Byron (old)", + "", + " ", + "-- Select --", + "select one", + "Straße", + "STRASSE", + "strasse", + "Ünïcode Ño", + "ünïcode ño", + "5", + "05", + "Yes", + "yes", + "No", + "true", + "Ada Byron", +] +INTAKE: list[Any] = [*TEXTS, 5, 0, True, False, None, 1.5] +CONTROL_KINDS = [ + ControlKind.TEXT, + ControlKind.SELECT, + ControlKind.DATE, + ControlKind.READONLY_OUTPUT, +] + + +def _binding(kind: FormCodecKind, control: ControlKind) -> FieldBindingSpec: + return FieldBindingSpec( + binding_id="b", + dossier_key="k", + anchor=FieldAnchorSpec(label_patterns=("^Name$",)), + control_kind=control, + codec=FieldCodecSpec(kind=kind), + ) + + +@pytest.mark.parametrize("kind", sorted(PORTED_CODECS, key=lambda k: k.value)) +@pytest.mark.parametrize("control", CONTROL_KINDS, ids=lambda c: c.value) +def test_ported_decisions_are_unchanged( + kind: FormCodecKind, control: ControlKind +) -> None: + binding = _binding(kind, control) + ported = 0 + for intake, shown in itertools.product(INTAKE, TEXTS): + pair = ObservedTextPair(label="Name", value=shown) + old = _old_text_pair_matches(intake, pair, binding) + new = review_text_matches(binding, intake, pair, run_id="r") + if new is None: + # Not ported: an intake value the codec can't read. The old + # comparison then says no match too, and it is what runs. + assert old is False, (intake, shown) + continue + ported += 1 + assert new is old, (kind, control, intake, shown, old, new) + assert ported > len(TEXTS) * 10 + + +@pytest.mark.parametrize( + "kind", [k for k in FormCodecKind if k not in PORTED_CODECS], ids=lambda k: k.value +) +def test_other_codecs_stay_on_the_old_comparison(kind: FormCodecKind) -> None: + pair = ObservedTextPair(label="Name", value="Ada Byron") + assert ( + review_text_matches( + _binding(kind, ControlKind.TEXT), "Ada Byron", pair, run_id="r" + ) + is None + ) + + +@pytest.mark.parametrize("control", [ControlKind.CHECKBOX, ControlKind.RADIO_GROUP]) +def test_yes_no_bindings_stay_on_the_old_comparison(control: ControlKind) -> None: + binding = _binding(FormCodecKind.WHITESPACE_COLLAPSE, control) + pair = ObservedTextPair(label="Name", value="Yes") + assert review_text_matches(binding, "true", pair, run_id="r") is None + + +def test_the_record_says_where_and_how() -> None: + binding = _binding(FormCodecKind.CASEFOLD, ControlKind.TEXT) + location = review_location(binding, " Ada Byron ") + assert location is not None + assert location.start == "same_screen" + assert location.keys == ("k",) + assert location.expected == {"k": "ada byron"} + assert location.codec.kind == "fold" + assert location.locator.value == "^Name$" + assert location.expected_count == 1