From c72222a0c00b91423063c45e63981f46d3f1f6ea Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 21:56:04 -0500 Subject: [PATCH 1/5] feat(flow): effect-location record and evaluator An effect location is pack data for one place a careful person would look again to see an intended value: the demonstration path and start condition, a locator, the expected value, a codec (including a template codec for one summary row that shows two values, and a split-date codec), the expected count and an optional baseline. evaluate_all judges every planned value as held, refuted or not_checked. A location that can't be reached, found or read is not_checked. The check level follows the start condition, and the receipt word comes from check_level.outcome_word when it is available. It is registered as a verdict site for the fail-open harness (#2476) through a small compat module, so it works on main today and picks up the real decorator and ladder when they merge. --- CAPABILITIES.md | 1 + llms-full.txt | 1 + packages/flow/CHANGELOG.md | 19 + 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 | 261 +++++++++ .../effect_location/evaluator.py | 427 +++++++++++++++ .../openadapt_flow/effect_location/record.py | 448 ++++++++++++++++ .../openadapt_flow/runtime/identity_vlm.py | 216 -------- .../flow/openadapt_flow/runtime/remote_vlm.py | 320 +---------- .../tests/failopen/sites/effect_location.py | 206 ++++++++ packages/flow/tests/test_effect_location.py | 477 +++++++++++++++++ .../flow/tests/test_local_vlm_gold_crop.py | 500 ------------------ packages/flow/tests/test_remote_vlm.py | 25 +- packages/flow/tests/test_wire_remote_vlm.py | 8 +- 16 files changed, 2069 insertions(+), 1056 deletions(-) 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/failopen/sites/effect_location.py create mode 100644 packages/flow/tests/test_effect_location.py delete mode 100644 packages/flow/tests/test_local_vlm_gold_crop.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index f679bf283b..22a704845d 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -161,6 +161,7 @@ improvising or retrying when something is off. | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](packages/flow/docs/VERIFICATION.md) | | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | +| Check a value where a careful person would look again: an effect location (`openadapt.effect-location/v1`) is pack data for one place an intended value shows (path and start condition, locator, expected value, codec, expected count, optional baseline). One summary row can cover two values ("Name (DOB)"), and a date can be split over three fields. Every planned value is `held`, `refuted` or `not_checked`; a place that can't be reached, found or read is `not_checked`. The check level follows the start condition (a new session is level 3), and the engine holds no application words | On main, not yet used by a runner | Unit tests and the fail-open harness (synthetic readings only) | `openadapt_flow/effect_location/`, [EFFECT_LOCATION.md](packages/flow/docs/EFFECT_LOCATION.md) | | Judge any executor's write, including an agent's or a script's, from the system of record | Released | Synthetic | `openadapt-flow verify-run`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md) | | Judge an "ensure the record exists" write (found, created once with every value, or needs review) through a FHIR server's read path only: searches, AuditEvent and `_history`, never the database; the coverage claim names that read path. An agent's own correction of the record it created counts as one write when the audit trail and history show only that agent, no other reader, and the same record in every version | Released ([#1640](https://github.com/OpenAdaptAI/OpenAdapt/pull/1640), corrections [#1655](https://github.com/OpenAdaptAI/OpenAdapt/pull/1655)) | Real app (Medplum 5.2.8; three blind fault suites: 17/18, 17/20, 19/20; no fault passed in the last two. Corrections, on 15 blind cases and the 37 public ones: false stops 8 to 2 and 9 to 4 for Claude, no harm passed that the old rule caught) | `openadapt_flow/ensure_record.py`, [ENSURE_RECORD.md](packages/flow/docs/ENSURE_RECORD.md) | | Generate an ensure-record contract from three demonstrations, the server's CapabilityStatement and its SearchParameter definitions: field paths and `[system=…]` filters, comparison kinds, value maps, identity, search parameters, the closed record and the change feed. It refuses when unsure, asks a person to confirm an identity for a type with no reviewed template, and self-checks every demonstration plus a perturbation per field | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8: all 16 hand-written Patient lines regenerated; one blind write type, Immunization: 78 s of person time, 2 lines edited after the person declined the proposed identity; blind suite 23/24, no fault passed) | `openadapt_flow/generate/ensure_contract.py`, [RESULTS.md](packages/flow/benchmark/contract_autogen/results/RESULTS.md) | diff --git a/llms-full.txt b/llms-full.txt index 333173dddf..3d4afe135a 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -601,6 +601,7 @@ improvising or retrying when something is off. | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFICATION.md) | | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | +| Check a value where a careful person would look again: an effect location (`openadapt.effect-location/v1`) is pack data for one place an intended value shows (path and start condition, locator, expected value, codec, expected count, optional baseline). One summary row can cover two values ("Name (DOB)"), and a date can be split over three fields. Every planned value is `held`, `refuted` or `not_checked`; a place that can't be reached, found or read is `not_checked`. The check level follows the start condition (a new session is level 3), and the engine holds no application words | On main, not yet used by a runner | Unit tests and the fail-open harness (synthetic readings only) | `openadapt_flow/effect_location/`, [EFFECT_LOCATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EFFECT_LOCATION.md) | | Judge any executor's write, including an agent's or a script's, from the system of record | Released | Synthetic | `openadapt-flow verify-run`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md) | | Judge an "ensure the record exists" write (found, created once with every value, or needs review) through a FHIR server's read path only: searches, AuditEvent and `_history`, never the database; the coverage claim names that read path. An agent's own correction of the record it created counts as one write when the audit trail and history show only that agent, no other reader, and the same record in every version | Released ([#1640](https://github.com/OpenAdaptAI/OpenAdapt/pull/1640), corrections [#1655](https://github.com/OpenAdaptAI/OpenAdapt/pull/1655)) | Real app (Medplum 5.2.8; three blind fault suites: 17/18, 17/20, 19/20; no fault passed in the last two. Corrections, on 15 blind cases and the 37 public ones: false stops 8 to 2 and 9 to 4 for Claude, no harm passed that the old rule caught) | `openadapt_flow/ensure_record.py`, [ENSURE_RECORD.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/ENSURE_RECORD.md) | | Generate an ensure-record contract from three demonstrations, the server's CapabilityStatement and its SearchParameter definitions: field paths and `[system=…]` filters, comparison kinds, value maps, identity, search parameters, the closed record and the change feed. It refuses when unsure, asks a person to confirm an identity for a type with no reviewed template, and self-checks every demonstration plus a perturbation per field | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8: all 16 hand-written Patient lines regenerated; one blind write type, Immunization: 78 s of person time, 2 lines edited after the person declined the proposed identity; blind suite 23/24, no fault passed) | `openadapt_flow/generate/ensure_contract.py`, [RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/contract_autogen/results/RESULTS.md) | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index d5a15df702..d442dd6fa6 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -15,6 +15,25 @@ +## Unreleased + +### Features + +- Effect locations (`openadapt.effect-location/v1`, + `openadapt_flow/effect_location/`): the place a careful person would look + again to see an intended value, stored as pack data. Each record holds the + demonstration path and start condition (`same_screen`, `fresh_navigation`, + `new_session`, `other_channel`), a locator (label, row key or region), the + expected value, a codec (including a `template` codec that reads one + summary row as two values and a `split_date` codec), the expected count + and an optional baseline. `evaluate_all` judges every planned value as + `held`, `refuted` or `not_checked`. A location that can't be reached, + found or read is `not_checked`, never a pass. The check level comes from + the start condition; the receipt word comes from + `check_level.outcome_word` when it is available. The engine holds no + application vocabulary: month names, yes and no words, currency signs and + tables come from the pack. See docs/EFFECT_LOCATION.md. + ## v3.4.0 (2026-11-21) ### Features 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..403f29471d --- /dev/null +++ b/packages/flow/openadapt_flow/effect_location/codecs.py @@ -0,0 +1,261 @@ +"""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) + 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 + sign = "" + if body.startswith("-"): + sign, body = "-", body[1:] + 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, 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..b031a795f0 --- /dev/null +++ b/packages/flow/openadapt_flow/effect_location/evaluator.py @@ -0,0 +1,427 @@ +"""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__ = [ + "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) + +#: 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, ...] = () + + +@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(reason: str, shown: tuple[str, ...] = ()) -> dict[str, KeyResult]: + return { + k: KeyResult(k, NOT_CHECKED, reason, locations=(loc.id,), shown=shown) + for k in loc.keys + } + + problem = _shape_problem(loc) + if problem: + return nc(problem) + if not run_id or reading.run_id != run_id: + return nc("the reading belongs to another run") + if reading.error is not None: + return nc("the read failed") + if not isinstance(reading.complete, bool): + return nc("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("the reading did not start where the location requires") + found = len(reading.matches) + if found == 0: + return nc("the location was not found") + shown_all = tuple(str(m.get("text", "")) for m in reading.matches) + if found != loc.expected_count: + return nc(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, reason: str) -> KeyResult: + return KeyResult( + key, + status, + reason, + 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, "the location has no expected value") + continue + try: + want = canonical(codec, loc.expected[key]) + except CodecError: + out[key] = result( + NOT_CHECKED, "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, "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, "the displayed text could not be read") + continue + if reading.complete is not True: + out[key] = result(NOT_CHECKED, "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, "the baseline is not in the codec's form" + ) + continue + if _same(before, want): + out[key] = result( + NOT_CHECKED, + "the value was already shown before, so the read cannot show the change", + ) + continue + out[key] = result(HELD, "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") + refuted = [r for r in results if r.status == REFUTED] + if refuted: + return KeyResult(key, REFUTED, refuted[0].reason, locations=locs, shown=shown) + open_ = [r for r in results if r.status != HELD] + if open_: + return KeyResult(key, NOT_CHECKED, open_[0].reason, locations=locs, shown=shown) + 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), + 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,), + ) + ) + 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,) + ) + ) + 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, + ) + 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") + ) + 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/openadapt_flow/runtime/identity_vlm.py b/packages/flow/openadapt_flow/runtime/identity_vlm.py index dd6a0e79d8..ebad05e1fc 100644 --- a/packages/flow/openadapt_flow/runtime/identity_vlm.py +++ b/packages/flow/openadapt_flow/runtime/identity_vlm.py @@ -21,228 +21,12 @@ from __future__ import annotations import tempfile -from dataclasses import dataclass -from enum import Enum from pathlib import Path from typing import Any, Optional -from openadapt_flow.ir import Region -from openadapt_flow.runtime.grounder import component_may_egress -from openadapt_flow.runtime.remote_vlm import ( - _MAX_MODEL_IMAGE_DIM, - IdentityVerdict, - extract_roi_crop, - gold_crop_for_model, -) - DEFAULT_MODEL = "mlx-community/Qwen3-VL-4B-Instruct-4bit" -class VetoVerdict(str, Enum): - """Unified veto-only verdict for local and remote VLM guards. - - * ``PASS`` -- confident affirmative match/state; fail-to-veto ONLY. - NEVER overrides a failed deterministic check. - * ``VETO`` -- explicit mismatch or violated state; halts execution. - * ``ABSTAIN`` -- uncertain, unreachable, timeout, exception, or malformed - output; halts execution. - """ - - PASS = "pass" - VETO = "veto" - ABSTAIN = "abstain" - - -@dataclass(frozen=True) -class VetoDecision: - """Outcome of a single veto-only VLM guard check.""" - - verdict: VetoVerdict - reason: str = "" - used_gold_crop: bool = False - - @property - def should_halt(self) -> bool: - """True for ``VETO`` and ``ABSTAIN``; False only for ``PASS``.""" - return self.verdict is not VetoVerdict.PASS - - def apply_to_deterministic(self, deterministic_passed: bool) -> bool: - """Combine with a deterministic check under strict veto-only semantics. - - ``VETO`` / ``ABSTAIN`` always halt (return ``False``). ``PASS`` lets a - passing deterministic check stand, and NEVER overrides a failing - deterministic check. - """ - return bool(deterministic_passed) and not self.should_halt - - -class VetoOnlyVLMGuard: - """Unified veto-only guard over local (MLX) or remote VLM backends. - - Enforces two invariants across identity and state checks: - - 1. **Strict veto-only semantics**: ``VETO`` and ``ABSTAIN`` (including any - transport error, model exception, or unrecognized answer) halt; ``PASS`` - only declines to veto and never overrides deterministic checks. - 2. **GOLD ROI cropping**: when full-frame screenshots exceed ``max_dim`` - (1024px) and a target/alert ``roi`` is provided, the guard extracts - native-resolution ROI crops (or GOLD global+local composites) within the - ``max_dim`` budget instead of uniformly downscaling away small text. - """ - - def __init__( - self, - *, - identity_vlm: Optional[Any] = None, - state_verifier: Optional[Any] = None, - max_dim: int = _MAX_MODEL_IMAGE_DIM, - ) -> None: - self._identity_vlm = identity_vlm - self._state_verifier = state_verifier - self._max_dim = max_dim - - @property - def MAY_EGRESS(self) -> bool: - """Propagate screenshot-egress classification from wrapped backends.""" - return component_may_egress(self._identity_vlm) or component_may_egress( - self._state_verifier - ) - - def check_identity( - self, - recorded_png: bytes, - live_png: bytes, - *, - roi: Optional[Region] = None, - ) -> VetoDecision: - """Run a veto-only identity comparison, applying symmetric ROI cropping if ``roi`` is set.""" - if self._identity_vlm is None: - return VetoDecision(VetoVerdict.ABSTAIN, reason="no_identity_backend") - - used_gold = False - rec_sent = recorded_png - live_sent = live_png - if roi is not None: - rec_crop = extract_roi_crop(recorded_png, roi, max_dim=self._max_dim) - live_crop = extract_roi_crop(live_png, roi, max_dim=self._max_dim) - if rec_crop is None or live_crop is None: - return VetoDecision( - VetoVerdict.ABSTAIN, - reason="identity_roi_unavailable", - used_gold_crop=False, - ) - rec_sent = rec_crop - live_sent = live_crop - used_gold = True - - try: - compare_fn = getattr(self._identity_vlm, "compare", None) - if callable(compare_fn): - raw = compare_fn(rec_sent, live_sent) - if raw is IdentityVerdict.VERIFY: - return VetoDecision(VetoVerdict.PASS, used_gold_crop=used_gold) - if raw is IdentityVerdict.MISMATCH: - return VetoDecision( - VetoVerdict.VETO, - reason="identity_mismatch", - used_gold_crop=used_gold, - ) - return VetoDecision( - VetoVerdict.ABSTAIN, - reason="identity_abstain", - used_gold_crop=used_gold, - ) - - same_fn = getattr(self._identity_vlm, "same_or_different", None) - if callable(same_fn): - ans = same_fn(rec_sent, live_sent) - if ans == "same": - return VetoDecision(VetoVerdict.PASS, used_gold_crop=used_gold) - if ans == "different": - return VetoDecision( - VetoVerdict.VETO, - reason="identity_different", - used_gold_crop=used_gold, - ) - return VetoDecision( - VetoVerdict.ABSTAIN, - reason="identity_unrecognized", - used_gold_crop=used_gold, - ) - except Exception as exc: - return VetoDecision( - VetoVerdict.ABSTAIN, - reason=f"identity_error:{type(exc).__name__}", - used_gold_crop=used_gold, - ) - - return VetoDecision( - VetoVerdict.ABSTAIN, - reason="unsupported_identity_backend", - used_gold_crop=used_gold, - ) - - def check_state( - self, - screenshot: bytes, - expected_state: str, - *, - roi: Optional[Region] = None, - ) -> VetoDecision: - """Run a veto-only state check, applying GOLD cropping when ``roi`` is set.""" - if self._state_verifier is None: - return VetoDecision(VetoVerdict.ABSTAIN, reason="no_state_backend") - - used_gold = False - sent = screenshot - if roi is not None: - gold = gold_crop_for_model(screenshot, roi=roi, max_dim=self._max_dim) - if gold.used_gold: - sent = gold.composite_png - used_gold = True - - try: - verify_fn = getattr(self._state_verifier, "verify", None) - if not callable(verify_fn): - return VetoDecision( - VetoVerdict.ABSTAIN, - reason="unsupported_state_backend", - used_gold_crop=used_gold, - ) - raw = verify_fn(sent, expected_state) - except Exception as exc: - return VetoDecision( - VetoVerdict.ABSTAIN, - reason=f"state_error:{type(exc).__name__}", - used_gold_crop=used_gold, - ) - - if raw == "yes": - return VetoDecision(VetoVerdict.PASS, used_gold_crop=used_gold) - if raw == "no": - return VetoDecision( - VetoVerdict.VETO, - reason="state_not_held", - used_gold_crop=used_gold, - ) - return VetoDecision( - VetoVerdict.ABSTAIN, - reason="state_uncertain", - used_gold_crop=used_gold, - ) - - def same_or_different( - self, - recorded_png: bytes, - live_png: bytes, - *, - roi: Optional[Region] = None, - ) -> str: - """Satisfy the ``IdentityVLM`` protocol: ``"same"`` iff ``PASS``, else ``"different"``.""" - decision = self.check_identity(recorded_png, live_png, roi=roi) - return "same" if decision.verdict is VetoVerdict.PASS else "different" - - class MLXIdentityVLM: """Local MLX VLM used as a veto-only same/different identity comparator. diff --git a/packages/flow/openadapt_flow/runtime/remote_vlm.py b/packages/flow/openadapt_flow/runtime/remote_vlm.py index ee36316c30..6d88c415fb 100644 --- a/packages/flow/openadapt_flow/runtime/remote_vlm.py +++ b/packages/flow/openadapt_flow/runtime/remote_vlm.py @@ -18,7 +18,6 @@ from __future__ import annotations import base64 -import math import os from dataclasses import dataclass from enum import Enum @@ -65,10 +64,6 @@ def _b64(png: bytes) -> str: # but never useful). Full-frame screenshots are downscaled below this before # they cross the wire; identity crops are already small and are left untouched. _MAX_MODEL_IMAGE_DIM = 1024 -_GOLD_DIVIDER_PX = 4 -_GOLD_DIVIDER_RGB = (48, 48, 48) -_GOLD_DEFAULT_PAD_RATIO = 0.15 -_GOLD_MIN_PAD_PX = 16 def _downscale_for_model( @@ -101,234 +96,6 @@ def _downscale_for_model( return png, 1.0 -def _png_dimensions(png: bytes) -> Optional[tuple[int, int]]: - """Return ``(width, height)`` for decodable image bytes, or ``None``.""" - try: - from io import BytesIO - - from PIL import Image - - with Image.open(BytesIO(png)) as img: - w, h = img.size - return (int(w), int(h)) if w > 0 and h > 0 else None - except Exception: - return None - - -def extract_roi_crop( - png: bytes, - roi: Region, - max_dim: int = _MAX_MODEL_IMAGE_DIM, - *, - pad_ratio: float = _GOLD_DEFAULT_PAD_RATIO, - min_pad_px: int = _GOLD_MIN_PAD_PX, -) -> Optional[bytes]: - """Extract a padded ROI crop bounded by ``max_dim``, or ``None`` if invalid. - - Unlike :func:`gold_crop_for_model`, this always crops to ``roi`` regardless - of whether the source frame exceeds ``max_dim`` so callers comparing two - frames (e.g. identity checks) never pair a cropped ROI with an uncropped - full screenshot. - """ - if max_dim <= 0: - return None - try: - from io import BytesIO - - from PIL import Image - - img = Image.open(BytesIO(png)).convert("RGB") - w, h = img.size - rx, ry, rw, rh = roi - if rw <= 0 or rh <= 0: - return None - x0 = int(rx) - y0 = int(ry) - x1 = int(rx + rw) - y1 = int(ry + rh) - # Require the entire requested subject region to be visible inside the - # image; a partly clipped ROI would omit part of the identifier on one - # side while forwarding a nonempty crop. - if x0 < 0 or y0 < 0 or x1 > w or y1 > h: - return None - - pad_x = max(min_pad_px, round((x1 - x0) * pad_ratio)) - pad_y = max(min_pad_px, round((y1 - y0) * pad_ratio)) - cx0 = max(0, x0 - pad_x) - cy0 = max(0, y0 - pad_y) - cx1 = min(w, x1 + pad_x) - cy1 = min(h, y1 + pad_y) - - crop = img.crop((cx0, cy0, cx1, cy1)) - cw, ch = crop.size - if max(cw, ch) > max_dim: - local_scale = max_dim / max(cw, ch) - crop = crop.resize( - (max(1, round(cw * local_scale)), max(1, round(ch * local_scale))), - Image.Resampling.LANCZOS, - ) - buf = BytesIO() - crop.save(buf, format="PNG") - return buf.getvalue() - except Exception: - return None - - -@dataclass(frozen=True) -class GoldCropResult: - """Deterministic Global-to-Local (GOLD) view of a screenshot within ``max_dim``. - - * ``global_png`` -- downscaled full frame (``max(w, h) <= max_dim``) - * ``global_scale`` -- scale factor of ``global_png`` (``<= 1.0``) - * ``local_png`` -- high-resolution ROI crop extracted from the original - unscaled frame (``max(w, h) <= max_dim``) - * ``local_scale`` -- scale factor of ``local_png`` relative to original - pixels (``1.0`` whenever the padded ROI fits inside ``max_dim``) - * ``local_origin`` -- ``(crop_x, crop_y)`` top-left of the padded ROI in - original full-frame pixel coordinates - * ``composite_png`` -- single-image GOLD composite (global overview stacked - above the high-resolution local ROI crop, bounded by ``max_dim`` on both - axes) for single-image VLM endpoints - * ``used_gold`` -- ``True`` iff the original frame exceeded ``max_dim`` - and a valid ROI preserved higher pixel resolution than uniform downscaling - """ - - global_png: bytes - global_scale: float - local_png: bytes - local_scale: float - local_origin: tuple[int, int] - composite_png: bytes - used_gold: bool - - -def gold_crop_for_model( - png: bytes, - roi: Optional[Region] = None, - max_dim: int = _MAX_MODEL_IMAGE_DIM, - *, - pad_ratio: float = _GOLD_DEFAULT_PAD_RATIO, - min_pad_px: int = _GOLD_MIN_PAD_PX, -) -> GoldCropResult: - """Build a deterministic Global-to-Local (GOLD) view within ``max_dim``. - - When ``roi`` is ``None``, empty/out-of-bounds, or the screenshot already - fits inside ``max_dim``, this falls back cleanly to - :func:`_downscale_for_model` with ``used_gold=False`` (zero behavior - change for existing callers). - - When ``max(w, h) > max_dim`` and a valid ``roi = (x, y, w, h)`` is given, - the target/alert region is cropped directly from the original unscaled - screenshot with deterministic padding so small text and banners retain - native 1:1 resolution (or the highest scale that fits ``max_dim``), paired - with a global overview frame inside a single ``<= max_dim`` composite. - """ - global_png, global_scale = _downscale_for_model(png, max_dim=max_dim) - fallback = GoldCropResult( - global_png=global_png, - global_scale=global_scale, - local_png=global_png, - local_scale=global_scale, - local_origin=(0, 0), - composite_png=global_png, - used_gold=False, - ) - if roi is None or max_dim <= _GOLD_DIVIDER_PX + 2: - return fallback - - try: - from io import BytesIO - - from PIL import Image - - img = Image.open(BytesIO(png)).convert("RGB") - w, h = img.size - if max(w, h) <= max_dim: - return fallback - - rx, ry, rw, rh = roi - if rw <= 0 or rh <= 0: - return fallback - x0 = max(0, min(w, int(rx))) - y0 = max(0, min(h, int(ry))) - x1 = max(0, min(w, int(rx + rw))) - y1 = max(0, min(h, int(ry + rh))) - if x1 <= x0 or y1 <= y0: - return fallback - - pad_x = max(min_pad_px, round((x1 - x0) * pad_ratio)) - pad_y = max(min_pad_px, round((y1 - y0) * pad_ratio)) - cx0 = max(0, x0 - pad_x) - cy0 = max(0, y0 - pad_y) - cx1 = min(w, x1 + pad_x) - cy1 = min(h, y1 + pad_y) - - crop = img.crop((cx0, cy0, cx1, cy1)) - cw, ch = crop.size - if max(cw, ch) > max_dim: - local_scale = max_dim / max(cw, ch) - local_img = crop.resize( - (max(1, round(cw * local_scale)), max(1, round(ch * local_scale))), - Image.Resampling.LANCZOS, - ) - else: - local_scale = 1.0 - local_img = crop - - local_buf = BytesIO() - local_img.save(local_buf, format="PNG") - local_png = local_buf.getvalue() - - # Build the single-image GOLD composite inside (max_dim x max_dim). - # Preserve native local crop resolution up to 2/3 of the vertical budget - # and fit the global overview in the remaining height. - avail_h = max_dim - _GOLD_DIVIDER_PX - local_max_h = min(local_img.height, max(1, (avail_h * 2) // 3)) - if local_img.height > local_max_h or local_img.width > max_dim: - comp_local_scale = min( - max_dim / local_img.width, local_max_h / local_img.height - ) - local_panel = local_img.resize( - ( - max(1, round(local_img.width * comp_local_scale)), - max(1, round(local_img.height * comp_local_scale)), - ), - Image.Resampling.LANCZOS, - ) - else: - local_panel = local_img - - global_max_h = max(1, avail_h - local_panel.height) - comp_global_scale = min(max_dim / w, global_max_h / h) - global_panel = img.resize( - ( - max(1, round(w * comp_global_scale)), - max(1, round(h * comp_global_scale)), - ), - Image.Resampling.LANCZOS, - ) - - comp_w = max(global_panel.width, local_panel.width) - comp_h = global_panel.height + _GOLD_DIVIDER_PX + local_panel.height - canvas = Image.new("RGB", (comp_w, comp_h), _GOLD_DIVIDER_RGB) - canvas.paste(global_panel, (0, 0)) - canvas.paste(local_panel, (0, global_panel.height + _GOLD_DIVIDER_PX)) - comp_buf = BytesIO() - canvas.save(comp_buf, format="PNG") - - return GoldCropResult( - global_png=global_png, - global_scale=global_scale, - local_png=local_png, - local_scale=local_scale, - local_origin=(cx0, cy0), - composite_png=comp_buf.getvalue(), - used_gold=local_scale > global_scale, - ) - except Exception: - return fallback - - class RemoteVLMClient: """Thin HTTP client for the VLM service. Never raises on transport failure. @@ -468,41 +235,8 @@ def locate( screen_png: bytes, intent: str, ocr_text: Optional[str] = None, - roi: Optional[Region] = None, ) -> Optional[GrounderMatch]: - if roi is not None: - gold = gold_crop_for_model(screen_png, roi=roi) - if gold.used_gold: - match = self._ground_and_map( - gold.local_png, - intent, - ocr_text, - scale=gold.local_scale, - origin=gold.local_origin, - ) - if match is not None: - return match - # Local ROI had no proposal: fall back deterministically to the - # global downscaled frame so a drifted target can still be found. - return self._ground_and_map( - gold.global_png, - intent, - ocr_text, - scale=gold.global_scale, - origin=(0, 0), - ) sent, scale = _downscale_for_model(screen_png) - return self._ground_and_map(sent, intent, ocr_text, scale=scale, origin=(0, 0)) - - def _ground_and_map( - self, - sent: bytes, - intent: str, - ocr_text: Optional[str], - *, - scale: float, - origin: tuple[int, int], - ) -> Optional[GrounderMatch]: data = self._client.ground(sent, intent, ocr_text) if data is None: return None # SAFE: service down => no proposal @@ -510,30 +244,11 @@ def _ground_and_map( if not point or not isinstance(point, (list, tuple)) or len(point) != 2: return None x, y = point - if ( - isinstance(x, bool) - or isinstance(y, bool) - or not isinstance(x, (int, float)) - or not isinstance(y, (int, float)) - or not math.isfinite(x) - or not math.isfinite(y) - ): - return None - # Validate coordinates against the actual image submitted to the model - # before translating back to full-frame pixel space; if dimensions - # cannot be established or the point falls outside the observed image, - # treat it as a miss (local retries globally; global returns None). - dims = _png_dimensions(sent) - if dims is None: + if not isinstance(x, (int, float)) or not isinstance(y, (int, float)): return None - sent_w, sent_h = dims - if x < 0 or y < 0 or x >= sent_w or y >= sent_h: - return None - # The model saw a downscaled or ROI-cropped frame; map the proposal back - # to the original screenshot's pixel space before anything acts on it. - ox, oy = origin - px = ox + int(round(x / scale)) - py = oy + int(round(y / scale)) + # The model saw a downscaled frame; map the proposal back to the + # original screenshot's pixel space before anything acts on it. + px, py = int(round(x / scale)), int(round(y / scale)) region: Region = ( max(0, px - _REGION_HALF_W), max(0, py - _REGION_HALF_H), @@ -562,20 +277,10 @@ class RemoteStateVerifier: def __init__(self, client: RemoteVLMClient) -> None: self._client = client - def verify( - self, - screenshot: bytes, - expected_state: str, - roi: Optional[Region] = None, - ) -> str: - # Downscale below the model's image ceiling; when an ROI is supplied on - # a >1024px frame, send a GOLD composite (global overview + native-res - # local crop) within the same 1024px budget. - if roi is not None: - gold = gold_crop_for_model(screenshot, roi=roi) - sent = gold.composite_png if gold.used_gold else gold.global_png - else: - sent, _scale = _downscale_for_model(screenshot) + def verify(self, screenshot: bytes, expected_state: str) -> str: + # Downscale below the model's image ceiling; there are no coordinates + # to map back for a yes/no/uncertain verdict. + sent, _scale = _downscale_for_model(screenshot) data = self._client.verify_state(sent, expected_state) if data is None: return "uncertain" # SAFE: service down => unproven => halt @@ -584,14 +289,9 @@ def verify( return holds return "uncertain" - def holds( - self, - screenshot: bytes, - expected_state: str, - roi: Optional[Region] = None, - ) -> bool: + def holds(self, screenshot: bytes, expected_state: str) -> bool: """Convenience: True ONLY on a confident 'yes' (uncertain/no => False).""" - return self.verify(screenshot, expected_state, roi=roi) == "yes" + return self.verify(screenshot, expected_state) == "yes" @dataclass diff --git a/packages/flow/tests/failopen/sites/effect_location.py b/packages/flow/tests/failopen/sites/effect_location.py new file mode 100644 index 0000000000..e4c79d67a3 --- /dev/null +++ b/packages/flow/tests/failopen/sites/effect_location.py @@ -0,0 +1,206 @@ +"""effect_location.evaluate_all: every planned value shown where expected (C1, C2, C5). + +The plan (the run's intended values) is the obligation set; the readings are +the results. A dropped reading, an empty plan, a failed read, a reading from +another run, a partial read, a missing field and a close-but-wrong displayed +text must all keep the run from passing. The seeds cover a plain label, a +composite summary row (one text, two values), a split date and an amount. +""" + +from __future__ import annotations + +import copy +from typing import Any + +from openadapt_flow.verdict import Status +from tests.failopen.harness import Seed, SiteSpec, index, key, register + +from openadapt_flow.effect_location import EffectLocation, Reading, evaluate_all + +RUN = "run-1" + + +def _loc( + lid: str, keys: list[str], codec: dict[str, Any], start: str = "same_screen" +) -> dict[str, Any]: + return { + "schema": "openadapt.effect-location/v1", + "id": lid, + "keys": keys, + "path": ["s1"], + "start": start, + "locator": {"kind": "label", "value": lid}, + "codec": codec, + "expected": {}, + "expected_count": 1, + } + + +def _read( + lid: str, *matches: dict[str, Any], start: str = "same_screen" +) -> dict[str, Any]: + return { + "location_id": lid, + "run_id": RUN, + "start": start, + "matches": list(matches), + "complete": True, + "error": None, + "basis": None, + } + + +ROW = { + "kind": "template", + "pattern": r"(?P.+) \((?P[^)]*)\)", + "parts": [ + {"group": "n", "key": "t_name", "codec": {"kind": "text"}}, + {"group": "d", "key": "t_dob", "codec": {"kind": "date", "date_order": "MDY"}}, + ], +} + + +def _good(start: str = "same_screen") -> dict[str, Any]: + return { + "run_id": RUN, + "plan": [ + ["name", "Ada Byron"], + ["t_name", "Ada Byron"], + ["t_dob", "1990-01-31"], + ["dep", "2024-03-07"], + ["cost", 125000], + ], + "locations": [ + _loc("name", ["name"], {"kind": "text"}, start), + _loc("row", ["t_name", "t_dob"], ROW, start), + _loc("dep", ["dep"], {"kind": "split_date"}, start), + _loc("cost", ["cost"], {"kind": "money", "affixes": ["$"]}, start), + ], + "readings": [ + _read("name", {"text": "Ada Byron"}, start=start), + _read("row", {"text": "Ada Byron (01/31/1990)"}, start=start), + _read("dep", {"year": "2024", "month": "3", "day": "7"}, start=start), + _read("cost", {"text": "$1,250.00"}, start=start), + ], + } + + +def _run(ev: dict[str, Any]) -> Any: + return evaluate_all( + [tuple(p) for p in ev["plan"]], + [EffectLocation.from_dict(d) for d in ev["locations"]], + [Reading.from_dict(d) for d in ev["readings"]], + run_id=ev["run_id"], + ) + + +def _bad(reading: dict[str, Any]) -> dict[str, Any]: + out = copy.deepcopy(reading) + for m in out["matches"]: + for part in m: + m[part] = "9" + str(m[part]) if part == "day" else "x" + str(m[part]) + return out + + +def _inflate(_ev: Any, n: int) -> dict[str, Any]: + plan = [[f"k{i}", f"v{i}"] for i in range(n)] + locs = [_loc(f"k{i}", [f"k{i}"], {"kind": "text"}) for i in range(n)] + reads = [_read(f"k{i}", {"text": f"v{i}"}) for i in range(n - 1)] + reads.append(_read(f"k{n - 1}", {"text": "wrong"})) + return {"run_id": RUN, "plan": plan, "locations": locs, "readings": reads} + + +def _raise(ev: dict[str, Any], exc: BaseException) -> dict[str, Any]: + out = copy.deepcopy(ev) + # The adapter saw the value, then the read raised: the matches it kept + # are not evidence. + out["readings"][0]["error"] = f"{type(exc).__name__}: {exc}" + return out + + +def _partial(ev: dict[str, Any]) -> list[tuple[str, Any]]: + out = [] + for i in range(len(ev["readings"])): + p = copy.deepcopy(ev) + p["readings"][i]["complete"] = False + out.append((f"reading {i} complete", p)) + return out + + +def _seed(change: Any) -> dict[str, Any]: + ev = _good() + change(ev) + return ev + + +register( + SiteSpec( + id="effect_location.evaluate_all", + classes="C1 C2 C5", + target="openadapt_flow.effect_location.evaluator:evaluate_all", + run=_run, + is_pass=lambda out: out.passes, + level=lambda out: Status(out.status), + seeds=lambda: [ + Seed(_good(), True, "label, summary row, split date, amount"), + Seed(_good("new_session"), True, "the same from a new session"), + Seed( + _seed( + lambda ev: ev["readings"][3]["matches"][0].update(text="$250.00") + ), + False, + "a different amount", + ), + Seed( + _seed( + lambda ev: ev["readings"][1]["matches"][0].update( + text="Ada Byron (01/30/1990)" + ) + ), + False, + "the row shows another date", + ), + Seed( + _seed(lambda ev: ev["readings"][0].update(matches=[])), + False, + "not found", + ), + Seed( + _seed( + lambda ev: ev["readings"][0]["matches"].append( + {"text": "Ada Byron"} + ) + ), + False, + "found twice, expected once", + ), + Seed( + _seed(lambda ev: ev["locations"][0].update(start="new_session")), + False, + "start condition not met", + ), + ], + items=key("readings"), + plan=key("plan"), + bad_item=_bad, + inflate=_inflate, + fields=index(key("readings"), 0), + values=( + key("text", "readings", 0, "matches", 0), + key("text", "readings", 1, "matches", 0), + key("day", "readings", 2, "matches", 0), + key("text", "readings", 3, "matches", 0), + key("complete", "readings", 0), + key("start", "readings", 0), + key("expected_count", "locations", 0), + key("kind", "locations", 0, "codec"), + ), + probe_raise=_raise, + subject=key("run_id", "readings", 0), + partial=_partial, + notes={ + "partial": "a reading whose area was not read in full can't show the " + "value is the only one there, so it never holds (M15)", + }, + ) +) diff --git a/packages/flow/tests/test_effect_location.py b/packages/flow/tests/test_effect_location.py new file mode 100644 index 0000000000..63b38b6d8e --- /dev/null +++ b/packages/flow/tests/test_effect_location.py @@ -0,0 +1,477 @@ +"""The effect-location record and its evaluator (synthetic readings only).""" + +from __future__ import annotations + +import json +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" + 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" + 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" diff --git a/packages/flow/tests/test_local_vlm_gold_crop.py b/packages/flow/tests/test_local_vlm_gold_crop.py deleted file mode 100644 index 8e33c0661a..0000000000 --- a/packages/flow/tests/test_local_vlm_gold_crop.py +++ /dev/null @@ -1,500 +0,0 @@ -"""Tests for Global-to-Local (GOLD) ROI cropping and VetoOnlyVLMGuard. - -Proves: -1. Zero behavior regression when ``roi`` is omitted or frames fit ``<= 1024px``. -2. Improved pixel-fidelity preservation on ``> 1024px`` synthetic frames within - the ``<= 1024px`` model ceiling, plus deterministic coordinate round-trips. -3. Strict veto-only semantics: ``VETO`` and ``ABSTAIN`` always halt; ``PASS`` - never overrides a failed deterministic check. -""" - -from __future__ import annotations - -import io -from typing import Optional - -import pytest -from PIL import Image, ImageDraw - -from openadapt_flow.runtime.grounder import component_may_egress -from openadapt_flow.runtime.identity import IdentityVLM -from openadapt_flow.runtime.identity_vlm import ( - VetoDecision, - VetoOnlyVLMGuard, - VetoVerdict, -) -from openadapt_flow.runtime.remote_vlm import ( - _MAX_MODEL_IMAGE_DIM, - IdentityVerdict, - RemoteGrounder, - RemoteIdentityVLM, - RemoteStateVerifier, - RemoteVLMClient, - _downscale_for_model, - gold_crop_for_model, -) -from openadapt_flow.runtime.replayer import EgressNotPermitted, Replayer - - -def _dims(png: bytes) -> tuple[int, int]: - return Image.open(io.BytesIO(png)).size - - -def _make_synthetic_banner_frame( - w: int = 2560, - h: int = 1440, - roi: tuple[int, int, int, int] = (900, 80, 320, 64), -) -> bytes: - """Create a >1024px frame with crisp alternating 2px vertical bars in ``roi``. - - Uniformly downscaling 2560 -> 1024 (0.4x) blurs 2px stripes into grey, - whereas a native-resolution GOLD ROI crop preserves full black/white contrast. - """ - img = Image.new("RGB", (w, h), (235, 235, 235)) - draw = ImageDraw.Draw(img) - rx, ry, rw, rh = roi - # Distinct red border around the alert banner region - draw.rectangle( - [rx, ry, rx + rw - 1, ry + rh - 1], fill=(255, 255, 255), outline=(220, 30, 30) - ) - # High-frequency 2px vertical bars inside the banner (proxy for small crisp text) - for x in range(rx + 8, rx + rw - 8, 4): - draw.rectangle([x, ry + 12, x + 1, ry + rh - 12], fill=(0, 0, 0)) - buf = io.BytesIO() - img.save(buf, format="PNG") - return buf.getvalue() - - -class _StubClient: - def __init__(self, *, ground_responses=None, state=None): - self._ground_responses = list(ground_responses or []) - self._state = state - self.ground_calls: list[tuple[tuple[int, int], str]] = [] - self.state_calls: list[tuple[tuple[int, int], str]] = [] - self.last_state_png: Optional[bytes] = None - - def ground(self, png, intent, ocr_text=None): - self.ground_calls.append((_dims(png), intent)) - if self._ground_responses: - return self._ground_responses.pop(0) - return None - - def verify_state(self, png, expected): - self.state_calls.append((_dims(png), expected)) - self.last_state_png = png - return self._state - - -# -------------------------------------------------------------------------- -# 1. Zero behavior regression -# -------------------------------------------------------------------------- - - -def test_gold_crop_no_roi_matches_downscale_exactly(): - frame = _make_synthetic_banner_frame(2560, 1440) - expected_png, expected_scale = _downscale_for_model(frame) - res = gold_crop_for_model(frame, roi=None) - assert res.used_gold is False - assert res.global_png == expected_png - assert res.local_png == expected_png - assert res.composite_png == expected_png - assert res.global_scale == expected_scale - assert res.local_scale == expected_scale - assert res.local_origin == (0, 0) - - -def test_gold_crop_small_frame_is_untouched(): - frame = _make_synthetic_banner_frame(800, 600, roi=(100, 50, 200, 60)) - res = gold_crop_for_model(frame, roi=(100, 50, 200, 60)) - assert res.used_gold is False - assert res.global_png == frame - assert res.composite_png == frame - assert res.global_scale == 1.0 - assert res.local_scale == 1.0 - - -@pytest.mark.parametrize( - "bad_roi", - [ - (0, 0, 0, 50), - (0, 0, 50, -10), - (5000, 5000, 100, 100), - ], -) -def test_gold_crop_invalid_roi_falls_back_cleanly(bad_roi): - frame = _make_synthetic_banner_frame(2048, 1200) - res = gold_crop_for_model(frame, roi=bad_roi) - assert res.used_gold is False - assert max(_dims(res.composite_png)) == _MAX_MODEL_IMAGE_DIM - - -def test_gold_crop_malformed_bytes_fail_safe(): - res = gold_crop_for_model(b"not-a-png", roi=(10, 10, 100, 50)) - assert res.used_gold is False - assert res.composite_png == b"not-a-png" - assert res.global_scale == 1.0 - - -# -------------------------------------------------------------------------- -# 2. Improved crop preservation on >1024px frames within the 1024px budget -# -------------------------------------------------------------------------- - - -def test_gold_crop_preserves_native_resolution_and_high_frequency_detail(): - roi = (900, 80, 320, 64) - frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) - res = gold_crop_for_model(frame, roi=roi) - - assert res.used_gold is True - assert res.global_scale == pytest.approx(1024 / 2560) - assert res.local_scale == 1.0 - assert res.local_scale > res.global_scale - - # Every output stays strictly inside the 1024px model ceiling on both axes. - assert max(_dims(res.global_png)) <= _MAX_MODEL_IMAGE_DIM - assert max(_dims(res.local_png)) <= _MAX_MODEL_IMAGE_DIM - assert max(_dims(res.composite_png)) <= _MAX_MODEL_IMAGE_DIM - - # Verify high-frequency stripe contrast is preserved in local_png (black=0, white=255) - # whereas uniform global downscaling smears the stripes. - local_im = Image.open(io.BytesIO(res.local_png)).convert("L") - local_extrema = local_im.getextrema() - assert local_extrema == (0, 255) - - global_im = Image.open(io.BytesIO(res.global_png)).convert("L") - rx, ry, rw, rh = roi - gs = res.global_scale - global_banner = global_im.crop( - ( - int(rx * gs) + 4, - int(ry * gs) + 4, - int((rx + rw) * gs) - 4, - int((ry + rh) * gs) - 4, - ) - ) - g_lo, g_hi = global_banner.getextrema() - assert (g_hi - g_lo) < 255 # downscaled banner lost full black-white contrast - - -def test_gold_crop_oversized_roi_stays_within_budget_and_beats_global(): - frame = _make_synthetic_banner_frame(3200, 2400, roi=(400, 300, 1400, 900)) - res = gold_crop_for_model(frame, roi=(400, 300, 1400, 900)) - assert res.used_gold is True - assert max(_dims(res.local_png)) == _MAX_MODEL_IMAGE_DIM - assert max(_dims(res.composite_png)) <= _MAX_MODEL_IMAGE_DIM - assert res.local_scale > res.global_scale - - -def test_remote_grounder_gold_crop_maps_local_point_to_original_frame(): - roi = (900, 80, 320, 64) - frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) - expected = gold_crop_for_model(frame, roi=roi) - ox, oy = expected.local_origin - - stub = _StubClient(ground_responses=[{"point": [100, 40], "confidence": 0.92}]) - grounder = RemoteGrounder(stub) - match = grounder.locate(frame, "Dismiss alert", roi=roi) - - assert len(stub.ground_calls) == 1 - assert stub.ground_calls[0][0] == _dims(expected.local_png) - assert match is not None - assert match.point == (ox + 100, oy + 40) - assert match.confidence == pytest.approx(0.92) - - -def test_remote_grounder_gold_crop_falls_back_to_global_when_local_misses(): - roi = (900, 80, 320, 64) - frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) - - # Local ROI returns null; global pass finds target at (500, 200) in 1024x576 frame. - stub = _StubClient( - ground_responses=[ - {"point": None}, - {"point": [500, 200], "confidence": 0.85}, - ] - ) - grounder = RemoteGrounder(stub) - match = grounder.locate(frame, "Submit button", roi=roi) - - assert len(stub.ground_calls) == 2 - assert stub.ground_calls[1][0] == (1024, 576) - assert match is not None - assert match.point == (round(500 / (1024 / 2560)), round(200 / (1024 / 2560))) - - -def test_remote_state_verifier_uses_gold_composite_within_budget(): - roi = (900, 80, 320, 64) - frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) - stub = _StubClient(state={"holds": "yes"}) - verifier = RemoteStateVerifier(stub) - - assert verifier.verify(frame, "error banner visible", roi=roi) == "yes" - assert len(stub.state_calls) == 1 - sent_w, sent_h = stub.state_calls[0][0] - assert max(sent_w, sent_h) <= _MAX_MODEL_IMAGE_DIM - # Composite is taller than plain 1024x576 global downscale because it appends the ROI crop. - assert sent_h > 576 - - -# -------------------------------------------------------------------------- -# 3. Unified Veto-Only Local VLM Guard semantics -# -------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - ("det_passed", "verdict", "expected"), - [ - (True, VetoVerdict.PASS, True), - (True, VetoVerdict.VETO, False), - (True, VetoVerdict.ABSTAIN, False), - # PASS must NEVER override a failed deterministic check. - (False, VetoVerdict.PASS, False), - (False, VetoVerdict.VETO, False), - (False, VetoVerdict.ABSTAIN, False), - ], -) -def test_veto_decision_strict_veto_only_truth_table(det_passed, verdict, expected): - decision = VetoDecision(verdict=verdict) - assert decision.should_halt is (verdict is not VetoVerdict.PASS) - assert decision.apply_to_deterministic(det_passed) is expected - - -class _FakeRemoteIdentity: - def __init__(self, verdict: IdentityVerdict): - self.verdict = verdict - self.seen_dims: list[tuple[tuple[int, int], tuple[int, int]]] = [] - - def compare(self, crop_a: bytes, crop_b: bytes) -> IdentityVerdict: - self.seen_dims.append((_dims(crop_a), _dims(crop_b))) - return self.verdict - - -class _FakeLocalIdentity: - def __init__(self, answer: str): - self.answer = answer - - def same_or_different(self, recorded_png: bytes, live_png: bytes) -> str: - return self.answer - - -class _ExplodingBackend: - def compare(self, crop_a: bytes, crop_b: bytes): - raise RuntimeError("backend crashed") - - def verify(self, screenshot: bytes, expected_state: str): - raise RuntimeError("backend crashed") - - -def test_guard_satisfies_identity_vlm_protocol(): - guard = VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("same")) - assert isinstance(guard, IdentityVLM) - - -def test_guard_identity_uses_gold_crop_and_maps_verdicts(): - roi = (900, 80, 320, 64) - frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) - - remote_ok = _FakeRemoteIdentity(IdentityVerdict.VERIFY) - guard_ok = VetoOnlyVLMGuard(identity_vlm=remote_ok) - dec_ok = guard_ok.check_identity(frame, frame, roi=roi) - assert dec_ok.verdict is VetoVerdict.PASS - assert dec_ok.should_halt is False - assert dec_ok.used_gold_crop is True - assert max(remote_ok.seen_dims[0][0]) <= _MAX_MODEL_IMAGE_DIM - assert remote_ok.seen_dims[0][0][0] < 1024 # cropped ROI, not full 1024px frame - assert guard_ok.same_or_different(frame, frame, roi=roi) == "same" - - guard_mismatch = VetoOnlyVLMGuard( - identity_vlm=_FakeRemoteIdentity(IdentityVerdict.MISMATCH) - ) - dec_veto = guard_mismatch.check_identity(frame, frame, roi=roi) - assert dec_veto.verdict is VetoVerdict.VETO - assert dec_veto.should_halt is True - assert guard_mismatch.same_or_different(frame, frame, roi=roi) == "different" - - guard_abstain = VetoOnlyVLMGuard( - identity_vlm=_FakeRemoteIdentity(IdentityVerdict.ABSTAIN) - ) - dec_abs = guard_abstain.check_identity(frame, frame, roi=roi) - assert dec_abs.verdict is VetoVerdict.ABSTAIN - assert dec_abs.should_halt is True - assert guard_abstain.same_or_different(frame, frame, roi=roi) == "different" - - -def test_guard_local_identity_and_exceptions_fail_safe_to_halt(): - frame = _make_synthetic_banner_frame(800, 600) - - assert ( - VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("same")) - .check_identity(frame, frame) - .verdict - is VetoVerdict.PASS - ) - assert ( - VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("different")) - .check_identity(frame, frame) - .verdict - is VetoVerdict.VETO - ) - assert ( - VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("maybe")) - .check_identity(frame, frame) - .verdict - is VetoVerdict.ABSTAIN - ) - - exploding = VetoOnlyVLMGuard( - identity_vlm=_ExplodingBackend(), state_verifier=_ExplodingBackend() - ) - id_dec = exploding.check_identity(frame, frame) - st_dec = exploding.check_state(frame, "saved") - assert id_dec.verdict is VetoVerdict.ABSTAIN and id_dec.should_halt is True - assert st_dec.verdict is VetoVerdict.ABSTAIN and st_dec.should_halt is True - - empty = VetoOnlyVLMGuard() - assert empty.check_identity(frame, frame).verdict is VetoVerdict.ABSTAIN - assert empty.check_state(frame, "saved").verdict is VetoVerdict.ABSTAIN - - -def test_guard_state_check_uses_gold_composite_and_veto_only_semantics(): - roi = (900, 80, 320, 64) - frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) - - for raw, expected_verdict in [ - ("yes", VetoVerdict.PASS), - ("no", VetoVerdict.VETO), - ("uncertain", VetoVerdict.ABSTAIN), - ]: - stub = _StubClient(state={"holds": raw}) - guard = VetoOnlyVLMGuard(state_verifier=RemoteStateVerifier(stub)) - dec = guard.check_state(frame, "alert visible", roi=roi) - assert dec.verdict is expected_verdict - assert dec.used_gold_crop is True - assert max(stub.state_calls[0][0]) <= _MAX_MODEL_IMAGE_DIM - - -# -------------------------------------------------------------------------- -# 4. Review regressions: egress propagation, bounds checks, symmetric ROI -# -------------------------------------------------------------------------- - - -def test_guard_propagates_egress_classification_to_replayer(): - remote_client = RemoteVLMClient("http://127.0.0.1:9") - remote_id_guard = VetoOnlyVLMGuard(identity_vlm=RemoteIdentityVLM(remote_client)) - remote_state_guard = VetoOnlyVLMGuard( - state_verifier=RemoteStateVerifier(remote_client) - ) - local_guard = VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("same")) - - assert component_may_egress(remote_id_guard) is True - assert component_may_egress(remote_state_guard) is True - assert component_may_egress(local_guard) is False - - # Replayer refuses a wrapped remote comparator without explicit opt-in. - with pytest.raises(EgressNotPermitted): - Replayer(backend=object(), vision=object(), identity_vlm=remote_id_guard) - - # With opt-in, Replayer wires it and sets the egress report flag. - replayer_remote = Replayer( - backend=object(), - vision=object(), - identity_vlm=remote_id_guard, - allow_model_grounding=True, - ) - assert replayer_remote._screenshots_may_leave_box is True - - # Purely local guard requires no opt-in and does not set the egress flag. - replayer_local = Replayer( - backend=object(), vision=object(), identity_vlm=local_guard - ) - assert replayer_local._screenshots_may_leave_box is False - - -@pytest.mark.parametrize( - "bad_point", - [ - [-1, 20], - [999, 20], - [20, 999], - [float("nan"), 20], - [float("inf"), 20], - [True, 20], - ], -) -def test_remote_grounder_rejects_out_of_bounds_local_and_falls_back_to_global( - bad_point, -): - roi = (900, 80, 320, 64) - frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) - - # Invalid local point must NOT be translated; must trigger global fallback. - stub = _StubClient( - ground_responses=[ - {"point": bad_point, "confidence": 0.99}, - {"point": [500, 200], "confidence": 0.85}, - ] - ) - match = RemoteGrounder(stub).locate(frame, "Submit", roi=roi) - assert len(stub.ground_calls) == 2 - assert match is not None - assert match.point == (round(500 / (1024 / 2560)), round(200 / (1024 / 2560))) - - # Invalid global point must return None (no proposal). - stub_global_bad = _StubClient( - ground_responses=[ - {"point": bad_point, "confidence": 0.99}, - {"point": [2000, 2000], "confidence": 0.99}, - ] - ) - assert RemoteGrounder(stub_global_bad).locate(frame, "Submit", roi=roi) is None - - -def test_guard_identity_crops_both_frames_symmetrically_or_abstains(): - roi = (200, 80, 320, 64) - large_frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) - small_frame = _make_synthetic_banner_frame(1024, 768, roi=roi) - - # Mixed sizes (one >1024px, one <=1024px): BOTH sides must get ROI crops, - # never a crop paired with an uncropped full screenshot. - backend = _FakeRemoteIdentity(IdentityVerdict.VERIFY) - guard = VetoOnlyVLMGuard(identity_vlm=backend) - dec = guard.check_identity(large_frame, small_frame, roi=roi) - assert dec.verdict is VetoVerdict.PASS - assert dec.used_gold_crop is True - assert len(backend.seen_dims) == 1 - rec_dims, live_dims = backend.seen_dims[0] - assert rec_dims == live_dims - assert rec_dims[0] < 1024 and rec_dims[1] < 768 - - # ROI partially clipped on the smaller frame (x=900..1220 exceeds 1024): - # must ABSTAIN without invoking the backend rather than comparing a partial - # crop against a full crop. - clipped_roi = (900, 80, 320, 64) - backend_clipped = _FakeRemoteIdentity(IdentityVerdict.VERIFY) - dec_clipped = VetoOnlyVLMGuard(identity_vlm=backend_clipped).check_identity( - large_frame, small_frame, roi=clipped_roi - ) - assert dec_clipped.verdict is VetoVerdict.ABSTAIN - assert dec_clipped.reason == "identity_roi_unavailable" - assert dec_clipped.should_halt is True - assert backend_clipped.seen_dims == [] - - # ROI outside the smaller frame: must ABSTAIN without invoking the backend. - oob_roi = (1500, 80, 320, 64) - backend_oob = _FakeRemoteIdentity(IdentityVerdict.VERIFY) - dec_oob = VetoOnlyVLMGuard(identity_vlm=backend_oob).check_identity( - large_frame, small_frame, roi=oob_roi - ) - assert dec_oob.verdict is VetoVerdict.ABSTAIN - assert dec_oob.reason == "identity_roi_unavailable" - assert dec_oob.should_halt is True - assert backend_oob.seen_dims == [] - - # Malformed bytes on one side: must ABSTAIN without invoking the backend. - backend_bad = _FakeRemoteIdentity(IdentityVerdict.VERIFY) - dec_bad = VetoOnlyVLMGuard(identity_vlm=backend_bad).check_identity( - large_frame, b"not-a-png", roi=roi - ) - assert dec_bad.verdict is VetoVerdict.ABSTAIN - assert dec_bad.should_halt is True - assert backend_bad.seen_dims == [] diff --git a/packages/flow/tests/test_remote_vlm.py b/packages/flow/tests/test_remote_vlm.py index db0198cb88..3bc16395d2 100644 --- a/packages/flow/tests/test_remote_vlm.py +++ b/packages/flow/tests/test_remote_vlm.py @@ -7,11 +7,8 @@ from __future__ import annotations -import io - import httpx import pytest -from PIL import Image from openadapt_flow.runtime.grounder import Grounder, GrounderMatch from openadapt_flow.runtime.remote_vlm import ( @@ -22,13 +19,7 @@ RemoteVLMClient, ) -PNG = b"\x89PNG\r\n\x1a\n" # unreadable stub header for transport-failure tests - - -def _valid_png(w: int = 200, h: int = 100) -> bytes: - buf = io.BytesIO() - Image.new("RGB", (w, h), (220, 220, 220)).save(buf, format="PNG") - return buf.getvalue() +PNG = b"\x89PNG\r\n\x1a\n" # bytes need not be a real PNG for the client layer # --- happy path (baseline: clients pass through good answers) --------------- @@ -63,23 +54,11 @@ def test_grounder_pass_through_point(monkeypatch): ), ) g = RemoteGrounder(RemoteVLMClient("http://x", token="t")) - m = g.locate(_valid_png(200, 100), "Save button") + m = g.locate(PNG, "Save button") assert isinstance(m, GrounderMatch) assert m.point == (120, 45) -def test_grounder_refuses_unreadable_image_bytes(monkeypatch): - monkeypatch.setattr( - httpx, - "post", - lambda url, **kw: httpx.Response( - 200, json={"point": [120, 45], "confidence": 0.9} - ), - ) - g = RemoteGrounder(RemoteVLMClient("http://x", token="t")) - assert g.locate(PNG, "Save button") is None - - def test_remote_grounder_satisfies_protocol(): g = RemoteGrounder(RemoteVLMClient("http://x")) assert isinstance(g, Grounder) diff --git a/packages/flow/tests/test_wire_remote_vlm.py b/packages/flow/tests/test_wire_remote_vlm.py index f58cfa03b1..beff66bab7 100644 --- a/packages/flow/tests/test_wire_remote_vlm.py +++ b/packages/flow/tests/test_wire_remote_vlm.py @@ -112,14 +112,8 @@ def test_grounder_outage_returns_no_proposal(): def test_grounder_proposes_a_point_when_reachable(): - import io - - from PIL import Image - - buf = io.BytesIO() - Image.new("RGB", (200, 100), (220, 220, 220)).save(buf, format="PNG") g = RemoteGrounder(_StubClient(ground={"point": [120, 44], "confidence": 0.9})) - m = g.locate(buf.getvalue(), "click Save", None) + m = g.locate(b"png", "click Save", None) assert m is not None and m.point == (120, 44) From 9d563a06fb298b2113ee14d58ea7a8c79cd9c279 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:00:33 -0500 Subject: [PATCH 2/5] fix(flow): restore files the branch reverted; read signs around currency signs The branch's first commit was cut against a newer main than its tree, so it reverted the GOLD crop and veto guard work from #2485. This puts those files back as they are on main. It also reads "-$250" and "$-250", and accepts a finite Decimal as an expected number. --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- .../openadapt_flow/effect_location/codecs.py | 11 +- .../openadapt_flow/runtime/identity_vlm.py | 216 ++++++++ .../flow/openadapt_flow/runtime/remote_vlm.py | 320 ++++++++++- packages/flow/tests/test_effect_location.py | 9 + .../flow/tests/test_local_vlm_gold_crop.py | 500 ++++++++++++++++++ packages/flow/tests/test_remote_vlm.py | 25 +- packages/flow/tests/test_wire_remote_vlm.py | 8 +- 9 files changed, 1075 insertions(+), 18 deletions(-) create mode 100644 packages/flow/tests/test_local_vlm_gold_crop.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 22a704845d..99b8c89fb7 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -161,7 +161,7 @@ improvising or retrying when something is off. | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](packages/flow/docs/VERIFICATION.md) | | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | -| Check a value where a careful person would look again: an effect location (`openadapt.effect-location/v1`) is pack data for one place an intended value shows (path and start condition, locator, expected value, codec, expected count, optional baseline). One summary row can cover two values ("Name (DOB)"), and a date can be split over three fields. Every planned value is `held`, `refuted` or `not_checked`; a place that can't be reached, found or read is `not_checked`. The check level follows the start condition (a new session is level 3), and the engine holds no application words | On main, not yet used by a runner | Unit tests and the fail-open harness (synthetic readings only) | `openadapt_flow/effect_location/`, [EFFECT_LOCATION.md](packages/flow/docs/EFFECT_LOCATION.md) | +| Check a value where a careful person would look again: an effect location (`openadapt.effect-location/v1`) is pack data for one place an intended value shows (path and start condition, locator, expected value, codec, expected count, optional baseline). One summary row can cover two values ("Name (DOB)"), and a date can be split over three fields. Every planned value is `held`, `refuted` or `not_checked`; a place that can't be reached, found or read is `not_checked`. The check level follows the start condition (a new session is level 3), and the engine holds no application words | PR [#2500](https://github.com/OpenAdaptAI/OpenAdapt/pull/2500), not yet used by a runner | Unit tests and the fail-open harness (synthetic readings only) | `openadapt_flow/effect_location/`, [EFFECT_LOCATION.md](packages/flow/docs/EFFECT_LOCATION.md) | | Judge any executor's write, including an agent's or a script's, from the system of record | Released | Synthetic | `openadapt-flow verify-run`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md) | | Judge an "ensure the record exists" write (found, created once with every value, or needs review) through a FHIR server's read path only: searches, AuditEvent and `_history`, never the database; the coverage claim names that read path. An agent's own correction of the record it created counts as one write when the audit trail and history show only that agent, no other reader, and the same record in every version | Released ([#1640](https://github.com/OpenAdaptAI/OpenAdapt/pull/1640), corrections [#1655](https://github.com/OpenAdaptAI/OpenAdapt/pull/1655)) | Real app (Medplum 5.2.8; three blind fault suites: 17/18, 17/20, 19/20; no fault passed in the last two. Corrections, on 15 blind cases and the 37 public ones: false stops 8 to 2 and 9 to 4 for Claude, no harm passed that the old rule caught) | `openadapt_flow/ensure_record.py`, [ENSURE_RECORD.md](packages/flow/docs/ENSURE_RECORD.md) | | Generate an ensure-record contract from three demonstrations, the server's CapabilityStatement and its SearchParameter definitions: field paths and `[system=…]` filters, comparison kinds, value maps, identity, search parameters, the closed record and the change feed. It refuses when unsure, asks a person to confirm an identity for a type with no reviewed template, and self-checks every demonstration plus a perturbation per field | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8: all 16 hand-written Patient lines regenerated; one blind write type, Immunization: 78 s of person time, 2 lines edited after the person declined the proposed identity; blind suite 23/24, no fault passed) | `openadapt_flow/generate/ensure_contract.py`, [RESULTS.md](packages/flow/benchmark/contract_autogen/results/RESULTS.md) | diff --git a/llms-full.txt b/llms-full.txt index 3d4afe135a..ffd66386d2 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -601,7 +601,7 @@ improvising or retrying when something is off. | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFICATION.md) | | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | -| Check a value where a careful person would look again: an effect location (`openadapt.effect-location/v1`) is pack data for one place an intended value shows (path and start condition, locator, expected value, codec, expected count, optional baseline). One summary row can cover two values ("Name (DOB)"), and a date can be split over three fields. Every planned value is `held`, `refuted` or `not_checked`; a place that can't be reached, found or read is `not_checked`. The check level follows the start condition (a new session is level 3), and the engine holds no application words | On main, not yet used by a runner | Unit tests and the fail-open harness (synthetic readings only) | `openadapt_flow/effect_location/`, [EFFECT_LOCATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EFFECT_LOCATION.md) | +| Check a value where a careful person would look again: an effect location (`openadapt.effect-location/v1`) is pack data for one place an intended value shows (path and start condition, locator, expected value, codec, expected count, optional baseline). One summary row can cover two values ("Name (DOB)"), and a date can be split over three fields. Every planned value is `held`, `refuted` or `not_checked`; a place that can't be reached, found or read is `not_checked`. The check level follows the start condition (a new session is level 3), and the engine holds no application words | PR [#2500](https://github.com/OpenAdaptAI/OpenAdapt/pull/2500), not yet used by a runner | Unit tests and the fail-open harness (synthetic readings only) | `openadapt_flow/effect_location/`, [EFFECT_LOCATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EFFECT_LOCATION.md) | | Judge any executor's write, including an agent's or a script's, from the system of record | Released | Synthetic | `openadapt-flow verify-run`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md) | | Judge an "ensure the record exists" write (found, created once with every value, or needs review) through a FHIR server's read path only: searches, AuditEvent and `_history`, never the database; the coverage claim names that read path. An agent's own correction of the record it created counts as one write when the audit trail and history show only that agent, no other reader, and the same record in every version | Released ([#1640](https://github.com/OpenAdaptAI/OpenAdapt/pull/1640), corrections [#1655](https://github.com/OpenAdaptAI/OpenAdapt/pull/1655)) | Real app (Medplum 5.2.8; three blind fault suites: 17/18, 17/20, 19/20; no fault passed in the last two. Corrections, on 15 blind cases and the 37 public ones: false stops 8 to 2 and 9 to 4 for Claude, no harm passed that the old rule caught) | `openadapt_flow/ensure_record.py`, [ENSURE_RECORD.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/ENSURE_RECORD.md) | | Generate an ensure-record contract from three demonstrations, the server's CapabilityStatement and its SearchParameter definitions: field paths and `[system=…]` filters, comparison kinds, value maps, identity, search parameters, the closed record and the change feed. It refuses when unsure, asks a person to confirm an identity for a type with no reviewed template, and self-checks every demonstration plus a perturbation per field | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8: all 16 hand-written Patient lines regenerated; one blind write type, Immunization: 78 s of person time, 2 lines edited after the person declined the proposed identity; blind suite 23/24, no fault passed) | `openadapt_flow/generate/ensure_contract.py`, [RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/contract_autogen/results/RESULTS.md) | diff --git a/packages/flow/openadapt_flow/effect_location/codecs.py b/packages/flow/openadapt_flow/effect_location/codecs.py index 403f29471d..9fd98b61d3 100644 --- a/packages/flow/openadapt_flow/effect_location/codecs.py +++ b/packages/flow/openadapt_flow/effect_location/codecs.py @@ -52,6 +52,10 @@ def _iso(year: int, month: int, day: int) -> str: 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() @@ -59,9 +63,8 @@ def _number(codec: Codec, text: str, *, affixes: tuple[str, ...]) -> Decimal: if affix and body.endswith(affix): body = body.removesuffix(affix).strip() break - sign = "" - if body.startswith("-"): - sign, body = "-", body[1:] + 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}" @@ -190,6 +193,8 @@ def canonical(codec: Codec, expected: Any) -> Any: 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") diff --git a/packages/flow/openadapt_flow/runtime/identity_vlm.py b/packages/flow/openadapt_flow/runtime/identity_vlm.py index ebad05e1fc..dd6a0e79d8 100644 --- a/packages/flow/openadapt_flow/runtime/identity_vlm.py +++ b/packages/flow/openadapt_flow/runtime/identity_vlm.py @@ -21,12 +21,228 @@ from __future__ import annotations import tempfile +from dataclasses import dataclass +from enum import Enum from pathlib import Path from typing import Any, Optional +from openadapt_flow.ir import Region +from openadapt_flow.runtime.grounder import component_may_egress +from openadapt_flow.runtime.remote_vlm import ( + _MAX_MODEL_IMAGE_DIM, + IdentityVerdict, + extract_roi_crop, + gold_crop_for_model, +) + DEFAULT_MODEL = "mlx-community/Qwen3-VL-4B-Instruct-4bit" +class VetoVerdict(str, Enum): + """Unified veto-only verdict for local and remote VLM guards. + + * ``PASS`` -- confident affirmative match/state; fail-to-veto ONLY. + NEVER overrides a failed deterministic check. + * ``VETO`` -- explicit mismatch or violated state; halts execution. + * ``ABSTAIN`` -- uncertain, unreachable, timeout, exception, or malformed + output; halts execution. + """ + + PASS = "pass" + VETO = "veto" + ABSTAIN = "abstain" + + +@dataclass(frozen=True) +class VetoDecision: + """Outcome of a single veto-only VLM guard check.""" + + verdict: VetoVerdict + reason: str = "" + used_gold_crop: bool = False + + @property + def should_halt(self) -> bool: + """True for ``VETO`` and ``ABSTAIN``; False only for ``PASS``.""" + return self.verdict is not VetoVerdict.PASS + + def apply_to_deterministic(self, deterministic_passed: bool) -> bool: + """Combine with a deterministic check under strict veto-only semantics. + + ``VETO`` / ``ABSTAIN`` always halt (return ``False``). ``PASS`` lets a + passing deterministic check stand, and NEVER overrides a failing + deterministic check. + """ + return bool(deterministic_passed) and not self.should_halt + + +class VetoOnlyVLMGuard: + """Unified veto-only guard over local (MLX) or remote VLM backends. + + Enforces two invariants across identity and state checks: + + 1. **Strict veto-only semantics**: ``VETO`` and ``ABSTAIN`` (including any + transport error, model exception, or unrecognized answer) halt; ``PASS`` + only declines to veto and never overrides deterministic checks. + 2. **GOLD ROI cropping**: when full-frame screenshots exceed ``max_dim`` + (1024px) and a target/alert ``roi`` is provided, the guard extracts + native-resolution ROI crops (or GOLD global+local composites) within the + ``max_dim`` budget instead of uniformly downscaling away small text. + """ + + def __init__( + self, + *, + identity_vlm: Optional[Any] = None, + state_verifier: Optional[Any] = None, + max_dim: int = _MAX_MODEL_IMAGE_DIM, + ) -> None: + self._identity_vlm = identity_vlm + self._state_verifier = state_verifier + self._max_dim = max_dim + + @property + def MAY_EGRESS(self) -> bool: + """Propagate screenshot-egress classification from wrapped backends.""" + return component_may_egress(self._identity_vlm) or component_may_egress( + self._state_verifier + ) + + def check_identity( + self, + recorded_png: bytes, + live_png: bytes, + *, + roi: Optional[Region] = None, + ) -> VetoDecision: + """Run a veto-only identity comparison, applying symmetric ROI cropping if ``roi`` is set.""" + if self._identity_vlm is None: + return VetoDecision(VetoVerdict.ABSTAIN, reason="no_identity_backend") + + used_gold = False + rec_sent = recorded_png + live_sent = live_png + if roi is not None: + rec_crop = extract_roi_crop(recorded_png, roi, max_dim=self._max_dim) + live_crop = extract_roi_crop(live_png, roi, max_dim=self._max_dim) + if rec_crop is None or live_crop is None: + return VetoDecision( + VetoVerdict.ABSTAIN, + reason="identity_roi_unavailable", + used_gold_crop=False, + ) + rec_sent = rec_crop + live_sent = live_crop + used_gold = True + + try: + compare_fn = getattr(self._identity_vlm, "compare", None) + if callable(compare_fn): + raw = compare_fn(rec_sent, live_sent) + if raw is IdentityVerdict.VERIFY: + return VetoDecision(VetoVerdict.PASS, used_gold_crop=used_gold) + if raw is IdentityVerdict.MISMATCH: + return VetoDecision( + VetoVerdict.VETO, + reason="identity_mismatch", + used_gold_crop=used_gold, + ) + return VetoDecision( + VetoVerdict.ABSTAIN, + reason="identity_abstain", + used_gold_crop=used_gold, + ) + + same_fn = getattr(self._identity_vlm, "same_or_different", None) + if callable(same_fn): + ans = same_fn(rec_sent, live_sent) + if ans == "same": + return VetoDecision(VetoVerdict.PASS, used_gold_crop=used_gold) + if ans == "different": + return VetoDecision( + VetoVerdict.VETO, + reason="identity_different", + used_gold_crop=used_gold, + ) + return VetoDecision( + VetoVerdict.ABSTAIN, + reason="identity_unrecognized", + used_gold_crop=used_gold, + ) + except Exception as exc: + return VetoDecision( + VetoVerdict.ABSTAIN, + reason=f"identity_error:{type(exc).__name__}", + used_gold_crop=used_gold, + ) + + return VetoDecision( + VetoVerdict.ABSTAIN, + reason="unsupported_identity_backend", + used_gold_crop=used_gold, + ) + + def check_state( + self, + screenshot: bytes, + expected_state: str, + *, + roi: Optional[Region] = None, + ) -> VetoDecision: + """Run a veto-only state check, applying GOLD cropping when ``roi`` is set.""" + if self._state_verifier is None: + return VetoDecision(VetoVerdict.ABSTAIN, reason="no_state_backend") + + used_gold = False + sent = screenshot + if roi is not None: + gold = gold_crop_for_model(screenshot, roi=roi, max_dim=self._max_dim) + if gold.used_gold: + sent = gold.composite_png + used_gold = True + + try: + verify_fn = getattr(self._state_verifier, "verify", None) + if not callable(verify_fn): + return VetoDecision( + VetoVerdict.ABSTAIN, + reason="unsupported_state_backend", + used_gold_crop=used_gold, + ) + raw = verify_fn(sent, expected_state) + except Exception as exc: + return VetoDecision( + VetoVerdict.ABSTAIN, + reason=f"state_error:{type(exc).__name__}", + used_gold_crop=used_gold, + ) + + if raw == "yes": + return VetoDecision(VetoVerdict.PASS, used_gold_crop=used_gold) + if raw == "no": + return VetoDecision( + VetoVerdict.VETO, + reason="state_not_held", + used_gold_crop=used_gold, + ) + return VetoDecision( + VetoVerdict.ABSTAIN, + reason="state_uncertain", + used_gold_crop=used_gold, + ) + + def same_or_different( + self, + recorded_png: bytes, + live_png: bytes, + *, + roi: Optional[Region] = None, + ) -> str: + """Satisfy the ``IdentityVLM`` protocol: ``"same"`` iff ``PASS``, else ``"different"``.""" + decision = self.check_identity(recorded_png, live_png, roi=roi) + return "same" if decision.verdict is VetoVerdict.PASS else "different" + + class MLXIdentityVLM: """Local MLX VLM used as a veto-only same/different identity comparator. diff --git a/packages/flow/openadapt_flow/runtime/remote_vlm.py b/packages/flow/openadapt_flow/runtime/remote_vlm.py index 6d88c415fb..ee36316c30 100644 --- a/packages/flow/openadapt_flow/runtime/remote_vlm.py +++ b/packages/flow/openadapt_flow/runtime/remote_vlm.py @@ -18,6 +18,7 @@ from __future__ import annotations import base64 +import math import os from dataclasses import dataclass from enum import Enum @@ -64,6 +65,10 @@ def _b64(png: bytes) -> str: # but never useful). Full-frame screenshots are downscaled below this before # they cross the wire; identity crops are already small and are left untouched. _MAX_MODEL_IMAGE_DIM = 1024 +_GOLD_DIVIDER_PX = 4 +_GOLD_DIVIDER_RGB = (48, 48, 48) +_GOLD_DEFAULT_PAD_RATIO = 0.15 +_GOLD_MIN_PAD_PX = 16 def _downscale_for_model( @@ -96,6 +101,234 @@ def _downscale_for_model( return png, 1.0 +def _png_dimensions(png: bytes) -> Optional[tuple[int, int]]: + """Return ``(width, height)`` for decodable image bytes, or ``None``.""" + try: + from io import BytesIO + + from PIL import Image + + with Image.open(BytesIO(png)) as img: + w, h = img.size + return (int(w), int(h)) if w > 0 and h > 0 else None + except Exception: + return None + + +def extract_roi_crop( + png: bytes, + roi: Region, + max_dim: int = _MAX_MODEL_IMAGE_DIM, + *, + pad_ratio: float = _GOLD_DEFAULT_PAD_RATIO, + min_pad_px: int = _GOLD_MIN_PAD_PX, +) -> Optional[bytes]: + """Extract a padded ROI crop bounded by ``max_dim``, or ``None`` if invalid. + + Unlike :func:`gold_crop_for_model`, this always crops to ``roi`` regardless + of whether the source frame exceeds ``max_dim`` so callers comparing two + frames (e.g. identity checks) never pair a cropped ROI with an uncropped + full screenshot. + """ + if max_dim <= 0: + return None + try: + from io import BytesIO + + from PIL import Image + + img = Image.open(BytesIO(png)).convert("RGB") + w, h = img.size + rx, ry, rw, rh = roi + if rw <= 0 or rh <= 0: + return None + x0 = int(rx) + y0 = int(ry) + x1 = int(rx + rw) + y1 = int(ry + rh) + # Require the entire requested subject region to be visible inside the + # image; a partly clipped ROI would omit part of the identifier on one + # side while forwarding a nonempty crop. + if x0 < 0 or y0 < 0 or x1 > w or y1 > h: + return None + + pad_x = max(min_pad_px, round((x1 - x0) * pad_ratio)) + pad_y = max(min_pad_px, round((y1 - y0) * pad_ratio)) + cx0 = max(0, x0 - pad_x) + cy0 = max(0, y0 - pad_y) + cx1 = min(w, x1 + pad_x) + cy1 = min(h, y1 + pad_y) + + crop = img.crop((cx0, cy0, cx1, cy1)) + cw, ch = crop.size + if max(cw, ch) > max_dim: + local_scale = max_dim / max(cw, ch) + crop = crop.resize( + (max(1, round(cw * local_scale)), max(1, round(ch * local_scale))), + Image.Resampling.LANCZOS, + ) + buf = BytesIO() + crop.save(buf, format="PNG") + return buf.getvalue() + except Exception: + return None + + +@dataclass(frozen=True) +class GoldCropResult: + """Deterministic Global-to-Local (GOLD) view of a screenshot within ``max_dim``. + + * ``global_png`` -- downscaled full frame (``max(w, h) <= max_dim``) + * ``global_scale`` -- scale factor of ``global_png`` (``<= 1.0``) + * ``local_png`` -- high-resolution ROI crop extracted from the original + unscaled frame (``max(w, h) <= max_dim``) + * ``local_scale`` -- scale factor of ``local_png`` relative to original + pixels (``1.0`` whenever the padded ROI fits inside ``max_dim``) + * ``local_origin`` -- ``(crop_x, crop_y)`` top-left of the padded ROI in + original full-frame pixel coordinates + * ``composite_png`` -- single-image GOLD composite (global overview stacked + above the high-resolution local ROI crop, bounded by ``max_dim`` on both + axes) for single-image VLM endpoints + * ``used_gold`` -- ``True`` iff the original frame exceeded ``max_dim`` + and a valid ROI preserved higher pixel resolution than uniform downscaling + """ + + global_png: bytes + global_scale: float + local_png: bytes + local_scale: float + local_origin: tuple[int, int] + composite_png: bytes + used_gold: bool + + +def gold_crop_for_model( + png: bytes, + roi: Optional[Region] = None, + max_dim: int = _MAX_MODEL_IMAGE_DIM, + *, + pad_ratio: float = _GOLD_DEFAULT_PAD_RATIO, + min_pad_px: int = _GOLD_MIN_PAD_PX, +) -> GoldCropResult: + """Build a deterministic Global-to-Local (GOLD) view within ``max_dim``. + + When ``roi`` is ``None``, empty/out-of-bounds, or the screenshot already + fits inside ``max_dim``, this falls back cleanly to + :func:`_downscale_for_model` with ``used_gold=False`` (zero behavior + change for existing callers). + + When ``max(w, h) > max_dim`` and a valid ``roi = (x, y, w, h)`` is given, + the target/alert region is cropped directly from the original unscaled + screenshot with deterministic padding so small text and banners retain + native 1:1 resolution (or the highest scale that fits ``max_dim``), paired + with a global overview frame inside a single ``<= max_dim`` composite. + """ + global_png, global_scale = _downscale_for_model(png, max_dim=max_dim) + fallback = GoldCropResult( + global_png=global_png, + global_scale=global_scale, + local_png=global_png, + local_scale=global_scale, + local_origin=(0, 0), + composite_png=global_png, + used_gold=False, + ) + if roi is None or max_dim <= _GOLD_DIVIDER_PX + 2: + return fallback + + try: + from io import BytesIO + + from PIL import Image + + img = Image.open(BytesIO(png)).convert("RGB") + w, h = img.size + if max(w, h) <= max_dim: + return fallback + + rx, ry, rw, rh = roi + if rw <= 0 or rh <= 0: + return fallback + x0 = max(0, min(w, int(rx))) + y0 = max(0, min(h, int(ry))) + x1 = max(0, min(w, int(rx + rw))) + y1 = max(0, min(h, int(ry + rh))) + if x1 <= x0 or y1 <= y0: + return fallback + + pad_x = max(min_pad_px, round((x1 - x0) * pad_ratio)) + pad_y = max(min_pad_px, round((y1 - y0) * pad_ratio)) + cx0 = max(0, x0 - pad_x) + cy0 = max(0, y0 - pad_y) + cx1 = min(w, x1 + pad_x) + cy1 = min(h, y1 + pad_y) + + crop = img.crop((cx0, cy0, cx1, cy1)) + cw, ch = crop.size + if max(cw, ch) > max_dim: + local_scale = max_dim / max(cw, ch) + local_img = crop.resize( + (max(1, round(cw * local_scale)), max(1, round(ch * local_scale))), + Image.Resampling.LANCZOS, + ) + else: + local_scale = 1.0 + local_img = crop + + local_buf = BytesIO() + local_img.save(local_buf, format="PNG") + local_png = local_buf.getvalue() + + # Build the single-image GOLD composite inside (max_dim x max_dim). + # Preserve native local crop resolution up to 2/3 of the vertical budget + # and fit the global overview in the remaining height. + avail_h = max_dim - _GOLD_DIVIDER_PX + local_max_h = min(local_img.height, max(1, (avail_h * 2) // 3)) + if local_img.height > local_max_h or local_img.width > max_dim: + comp_local_scale = min( + max_dim / local_img.width, local_max_h / local_img.height + ) + local_panel = local_img.resize( + ( + max(1, round(local_img.width * comp_local_scale)), + max(1, round(local_img.height * comp_local_scale)), + ), + Image.Resampling.LANCZOS, + ) + else: + local_panel = local_img + + global_max_h = max(1, avail_h - local_panel.height) + comp_global_scale = min(max_dim / w, global_max_h / h) + global_panel = img.resize( + ( + max(1, round(w * comp_global_scale)), + max(1, round(h * comp_global_scale)), + ), + Image.Resampling.LANCZOS, + ) + + comp_w = max(global_panel.width, local_panel.width) + comp_h = global_panel.height + _GOLD_DIVIDER_PX + local_panel.height + canvas = Image.new("RGB", (comp_w, comp_h), _GOLD_DIVIDER_RGB) + canvas.paste(global_panel, (0, 0)) + canvas.paste(local_panel, (0, global_panel.height + _GOLD_DIVIDER_PX)) + comp_buf = BytesIO() + canvas.save(comp_buf, format="PNG") + + return GoldCropResult( + global_png=global_png, + global_scale=global_scale, + local_png=local_png, + local_scale=local_scale, + local_origin=(cx0, cy0), + composite_png=comp_buf.getvalue(), + used_gold=local_scale > global_scale, + ) + except Exception: + return fallback + + class RemoteVLMClient: """Thin HTTP client for the VLM service. Never raises on transport failure. @@ -235,8 +468,41 @@ def locate( screen_png: bytes, intent: str, ocr_text: Optional[str] = None, + roi: Optional[Region] = None, ) -> Optional[GrounderMatch]: + if roi is not None: + gold = gold_crop_for_model(screen_png, roi=roi) + if gold.used_gold: + match = self._ground_and_map( + gold.local_png, + intent, + ocr_text, + scale=gold.local_scale, + origin=gold.local_origin, + ) + if match is not None: + return match + # Local ROI had no proposal: fall back deterministically to the + # global downscaled frame so a drifted target can still be found. + return self._ground_and_map( + gold.global_png, + intent, + ocr_text, + scale=gold.global_scale, + origin=(0, 0), + ) sent, scale = _downscale_for_model(screen_png) + return self._ground_and_map(sent, intent, ocr_text, scale=scale, origin=(0, 0)) + + def _ground_and_map( + self, + sent: bytes, + intent: str, + ocr_text: Optional[str], + *, + scale: float, + origin: tuple[int, int], + ) -> Optional[GrounderMatch]: data = self._client.ground(sent, intent, ocr_text) if data is None: return None # SAFE: service down => no proposal @@ -244,11 +510,30 @@ def locate( if not point or not isinstance(point, (list, tuple)) or len(point) != 2: return None x, y = point - if not isinstance(x, (int, float)) or not isinstance(y, (int, float)): + if ( + isinstance(x, bool) + or isinstance(y, bool) + or not isinstance(x, (int, float)) + or not isinstance(y, (int, float)) + or not math.isfinite(x) + or not math.isfinite(y) + ): + return None + # Validate coordinates against the actual image submitted to the model + # before translating back to full-frame pixel space; if dimensions + # cannot be established or the point falls outside the observed image, + # treat it as a miss (local retries globally; global returns None). + dims = _png_dimensions(sent) + if dims is None: return None - # The model saw a downscaled frame; map the proposal back to the - # original screenshot's pixel space before anything acts on it. - px, py = int(round(x / scale)), int(round(y / scale)) + sent_w, sent_h = dims + if x < 0 or y < 0 or x >= sent_w or y >= sent_h: + return None + # The model saw a downscaled or ROI-cropped frame; map the proposal back + # to the original screenshot's pixel space before anything acts on it. + ox, oy = origin + px = ox + int(round(x / scale)) + py = oy + int(round(y / scale)) region: Region = ( max(0, px - _REGION_HALF_W), max(0, py - _REGION_HALF_H), @@ -277,10 +562,20 @@ class RemoteStateVerifier: def __init__(self, client: RemoteVLMClient) -> None: self._client = client - def verify(self, screenshot: bytes, expected_state: str) -> str: - # Downscale below the model's image ceiling; there are no coordinates - # to map back for a yes/no/uncertain verdict. - sent, _scale = _downscale_for_model(screenshot) + def verify( + self, + screenshot: bytes, + expected_state: str, + roi: Optional[Region] = None, + ) -> str: + # Downscale below the model's image ceiling; when an ROI is supplied on + # a >1024px frame, send a GOLD composite (global overview + native-res + # local crop) within the same 1024px budget. + if roi is not None: + gold = gold_crop_for_model(screenshot, roi=roi) + sent = gold.composite_png if gold.used_gold else gold.global_png + else: + sent, _scale = _downscale_for_model(screenshot) data = self._client.verify_state(sent, expected_state) if data is None: return "uncertain" # SAFE: service down => unproven => halt @@ -289,9 +584,14 @@ def verify(self, screenshot: bytes, expected_state: str) -> str: return holds return "uncertain" - def holds(self, screenshot: bytes, expected_state: str) -> bool: + def holds( + self, + screenshot: bytes, + expected_state: str, + roi: Optional[Region] = None, + ) -> bool: """Convenience: True ONLY on a confident 'yes' (uncertain/no => False).""" - return self.verify(screenshot, expected_state) == "yes" + return self.verify(screenshot, expected_state, roi=roi) == "yes" @dataclass diff --git a/packages/flow/tests/test_effect_location.py b/packages/flow/tests/test_effect_location.py index 63b38b6d8e..fdd5b1af5b 100644 --- a/packages/flow/tests/test_effect_location.py +++ b/packages/flow/tests/test_effect_location.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +from decimal import Decimal from typing import Any import pytest @@ -192,6 +193,10 @@ def test_money_compares_whole_amounts_in_minor_units() -> None: 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" @@ -202,6 +207,10 @@ def test_units_and_numbers() -> None: 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" diff --git a/packages/flow/tests/test_local_vlm_gold_crop.py b/packages/flow/tests/test_local_vlm_gold_crop.py new file mode 100644 index 0000000000..8e33c0661a --- /dev/null +++ b/packages/flow/tests/test_local_vlm_gold_crop.py @@ -0,0 +1,500 @@ +"""Tests for Global-to-Local (GOLD) ROI cropping and VetoOnlyVLMGuard. + +Proves: +1. Zero behavior regression when ``roi`` is omitted or frames fit ``<= 1024px``. +2. Improved pixel-fidelity preservation on ``> 1024px`` synthetic frames within + the ``<= 1024px`` model ceiling, plus deterministic coordinate round-trips. +3. Strict veto-only semantics: ``VETO`` and ``ABSTAIN`` always halt; ``PASS`` + never overrides a failed deterministic check. +""" + +from __future__ import annotations + +import io +from typing import Optional + +import pytest +from PIL import Image, ImageDraw + +from openadapt_flow.runtime.grounder import component_may_egress +from openadapt_flow.runtime.identity import IdentityVLM +from openadapt_flow.runtime.identity_vlm import ( + VetoDecision, + VetoOnlyVLMGuard, + VetoVerdict, +) +from openadapt_flow.runtime.remote_vlm import ( + _MAX_MODEL_IMAGE_DIM, + IdentityVerdict, + RemoteGrounder, + RemoteIdentityVLM, + RemoteStateVerifier, + RemoteVLMClient, + _downscale_for_model, + gold_crop_for_model, +) +from openadapt_flow.runtime.replayer import EgressNotPermitted, Replayer + + +def _dims(png: bytes) -> tuple[int, int]: + return Image.open(io.BytesIO(png)).size + + +def _make_synthetic_banner_frame( + w: int = 2560, + h: int = 1440, + roi: tuple[int, int, int, int] = (900, 80, 320, 64), +) -> bytes: + """Create a >1024px frame with crisp alternating 2px vertical bars in ``roi``. + + Uniformly downscaling 2560 -> 1024 (0.4x) blurs 2px stripes into grey, + whereas a native-resolution GOLD ROI crop preserves full black/white contrast. + """ + img = Image.new("RGB", (w, h), (235, 235, 235)) + draw = ImageDraw.Draw(img) + rx, ry, rw, rh = roi + # Distinct red border around the alert banner region + draw.rectangle( + [rx, ry, rx + rw - 1, ry + rh - 1], fill=(255, 255, 255), outline=(220, 30, 30) + ) + # High-frequency 2px vertical bars inside the banner (proxy for small crisp text) + for x in range(rx + 8, rx + rw - 8, 4): + draw.rectangle([x, ry + 12, x + 1, ry + rh - 12], fill=(0, 0, 0)) + buf = io.BytesIO() + img.save(buf, format="PNG") + return buf.getvalue() + + +class _StubClient: + def __init__(self, *, ground_responses=None, state=None): + self._ground_responses = list(ground_responses or []) + self._state = state + self.ground_calls: list[tuple[tuple[int, int], str]] = [] + self.state_calls: list[tuple[tuple[int, int], str]] = [] + self.last_state_png: Optional[bytes] = None + + def ground(self, png, intent, ocr_text=None): + self.ground_calls.append((_dims(png), intent)) + if self._ground_responses: + return self._ground_responses.pop(0) + return None + + def verify_state(self, png, expected): + self.state_calls.append((_dims(png), expected)) + self.last_state_png = png + return self._state + + +# -------------------------------------------------------------------------- +# 1. Zero behavior regression +# -------------------------------------------------------------------------- + + +def test_gold_crop_no_roi_matches_downscale_exactly(): + frame = _make_synthetic_banner_frame(2560, 1440) + expected_png, expected_scale = _downscale_for_model(frame) + res = gold_crop_for_model(frame, roi=None) + assert res.used_gold is False + assert res.global_png == expected_png + assert res.local_png == expected_png + assert res.composite_png == expected_png + assert res.global_scale == expected_scale + assert res.local_scale == expected_scale + assert res.local_origin == (0, 0) + + +def test_gold_crop_small_frame_is_untouched(): + frame = _make_synthetic_banner_frame(800, 600, roi=(100, 50, 200, 60)) + res = gold_crop_for_model(frame, roi=(100, 50, 200, 60)) + assert res.used_gold is False + assert res.global_png == frame + assert res.composite_png == frame + assert res.global_scale == 1.0 + assert res.local_scale == 1.0 + + +@pytest.mark.parametrize( + "bad_roi", + [ + (0, 0, 0, 50), + (0, 0, 50, -10), + (5000, 5000, 100, 100), + ], +) +def test_gold_crop_invalid_roi_falls_back_cleanly(bad_roi): + frame = _make_synthetic_banner_frame(2048, 1200) + res = gold_crop_for_model(frame, roi=bad_roi) + assert res.used_gold is False + assert max(_dims(res.composite_png)) == _MAX_MODEL_IMAGE_DIM + + +def test_gold_crop_malformed_bytes_fail_safe(): + res = gold_crop_for_model(b"not-a-png", roi=(10, 10, 100, 50)) + assert res.used_gold is False + assert res.composite_png == b"not-a-png" + assert res.global_scale == 1.0 + + +# -------------------------------------------------------------------------- +# 2. Improved crop preservation on >1024px frames within the 1024px budget +# -------------------------------------------------------------------------- + + +def test_gold_crop_preserves_native_resolution_and_high_frequency_detail(): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + res = gold_crop_for_model(frame, roi=roi) + + assert res.used_gold is True + assert res.global_scale == pytest.approx(1024 / 2560) + assert res.local_scale == 1.0 + assert res.local_scale > res.global_scale + + # Every output stays strictly inside the 1024px model ceiling on both axes. + assert max(_dims(res.global_png)) <= _MAX_MODEL_IMAGE_DIM + assert max(_dims(res.local_png)) <= _MAX_MODEL_IMAGE_DIM + assert max(_dims(res.composite_png)) <= _MAX_MODEL_IMAGE_DIM + + # Verify high-frequency stripe contrast is preserved in local_png (black=0, white=255) + # whereas uniform global downscaling smears the stripes. + local_im = Image.open(io.BytesIO(res.local_png)).convert("L") + local_extrema = local_im.getextrema() + assert local_extrema == (0, 255) + + global_im = Image.open(io.BytesIO(res.global_png)).convert("L") + rx, ry, rw, rh = roi + gs = res.global_scale + global_banner = global_im.crop( + ( + int(rx * gs) + 4, + int(ry * gs) + 4, + int((rx + rw) * gs) - 4, + int((ry + rh) * gs) - 4, + ) + ) + g_lo, g_hi = global_banner.getextrema() + assert (g_hi - g_lo) < 255 # downscaled banner lost full black-white contrast + + +def test_gold_crop_oversized_roi_stays_within_budget_and_beats_global(): + frame = _make_synthetic_banner_frame(3200, 2400, roi=(400, 300, 1400, 900)) + res = gold_crop_for_model(frame, roi=(400, 300, 1400, 900)) + assert res.used_gold is True + assert max(_dims(res.local_png)) == _MAX_MODEL_IMAGE_DIM + assert max(_dims(res.composite_png)) <= _MAX_MODEL_IMAGE_DIM + assert res.local_scale > res.global_scale + + +def test_remote_grounder_gold_crop_maps_local_point_to_original_frame(): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + expected = gold_crop_for_model(frame, roi=roi) + ox, oy = expected.local_origin + + stub = _StubClient(ground_responses=[{"point": [100, 40], "confidence": 0.92}]) + grounder = RemoteGrounder(stub) + match = grounder.locate(frame, "Dismiss alert", roi=roi) + + assert len(stub.ground_calls) == 1 + assert stub.ground_calls[0][0] == _dims(expected.local_png) + assert match is not None + assert match.point == (ox + 100, oy + 40) + assert match.confidence == pytest.approx(0.92) + + +def test_remote_grounder_gold_crop_falls_back_to_global_when_local_misses(): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + + # Local ROI returns null; global pass finds target at (500, 200) in 1024x576 frame. + stub = _StubClient( + ground_responses=[ + {"point": None}, + {"point": [500, 200], "confidence": 0.85}, + ] + ) + grounder = RemoteGrounder(stub) + match = grounder.locate(frame, "Submit button", roi=roi) + + assert len(stub.ground_calls) == 2 + assert stub.ground_calls[1][0] == (1024, 576) + assert match is not None + assert match.point == (round(500 / (1024 / 2560)), round(200 / (1024 / 2560))) + + +def test_remote_state_verifier_uses_gold_composite_within_budget(): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + stub = _StubClient(state={"holds": "yes"}) + verifier = RemoteStateVerifier(stub) + + assert verifier.verify(frame, "error banner visible", roi=roi) == "yes" + assert len(stub.state_calls) == 1 + sent_w, sent_h = stub.state_calls[0][0] + assert max(sent_w, sent_h) <= _MAX_MODEL_IMAGE_DIM + # Composite is taller than plain 1024x576 global downscale because it appends the ROI crop. + assert sent_h > 576 + + +# -------------------------------------------------------------------------- +# 3. Unified Veto-Only Local VLM Guard semantics +# -------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("det_passed", "verdict", "expected"), + [ + (True, VetoVerdict.PASS, True), + (True, VetoVerdict.VETO, False), + (True, VetoVerdict.ABSTAIN, False), + # PASS must NEVER override a failed deterministic check. + (False, VetoVerdict.PASS, False), + (False, VetoVerdict.VETO, False), + (False, VetoVerdict.ABSTAIN, False), + ], +) +def test_veto_decision_strict_veto_only_truth_table(det_passed, verdict, expected): + decision = VetoDecision(verdict=verdict) + assert decision.should_halt is (verdict is not VetoVerdict.PASS) + assert decision.apply_to_deterministic(det_passed) is expected + + +class _FakeRemoteIdentity: + def __init__(self, verdict: IdentityVerdict): + self.verdict = verdict + self.seen_dims: list[tuple[tuple[int, int], tuple[int, int]]] = [] + + def compare(self, crop_a: bytes, crop_b: bytes) -> IdentityVerdict: + self.seen_dims.append((_dims(crop_a), _dims(crop_b))) + return self.verdict + + +class _FakeLocalIdentity: + def __init__(self, answer: str): + self.answer = answer + + def same_or_different(self, recorded_png: bytes, live_png: bytes) -> str: + return self.answer + + +class _ExplodingBackend: + def compare(self, crop_a: bytes, crop_b: bytes): + raise RuntimeError("backend crashed") + + def verify(self, screenshot: bytes, expected_state: str): + raise RuntimeError("backend crashed") + + +def test_guard_satisfies_identity_vlm_protocol(): + guard = VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("same")) + assert isinstance(guard, IdentityVLM) + + +def test_guard_identity_uses_gold_crop_and_maps_verdicts(): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + + remote_ok = _FakeRemoteIdentity(IdentityVerdict.VERIFY) + guard_ok = VetoOnlyVLMGuard(identity_vlm=remote_ok) + dec_ok = guard_ok.check_identity(frame, frame, roi=roi) + assert dec_ok.verdict is VetoVerdict.PASS + assert dec_ok.should_halt is False + assert dec_ok.used_gold_crop is True + assert max(remote_ok.seen_dims[0][0]) <= _MAX_MODEL_IMAGE_DIM + assert remote_ok.seen_dims[0][0][0] < 1024 # cropped ROI, not full 1024px frame + assert guard_ok.same_or_different(frame, frame, roi=roi) == "same" + + guard_mismatch = VetoOnlyVLMGuard( + identity_vlm=_FakeRemoteIdentity(IdentityVerdict.MISMATCH) + ) + dec_veto = guard_mismatch.check_identity(frame, frame, roi=roi) + assert dec_veto.verdict is VetoVerdict.VETO + assert dec_veto.should_halt is True + assert guard_mismatch.same_or_different(frame, frame, roi=roi) == "different" + + guard_abstain = VetoOnlyVLMGuard( + identity_vlm=_FakeRemoteIdentity(IdentityVerdict.ABSTAIN) + ) + dec_abs = guard_abstain.check_identity(frame, frame, roi=roi) + assert dec_abs.verdict is VetoVerdict.ABSTAIN + assert dec_abs.should_halt is True + assert guard_abstain.same_or_different(frame, frame, roi=roi) == "different" + + +def test_guard_local_identity_and_exceptions_fail_safe_to_halt(): + frame = _make_synthetic_banner_frame(800, 600) + + assert ( + VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("same")) + .check_identity(frame, frame) + .verdict + is VetoVerdict.PASS + ) + assert ( + VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("different")) + .check_identity(frame, frame) + .verdict + is VetoVerdict.VETO + ) + assert ( + VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("maybe")) + .check_identity(frame, frame) + .verdict + is VetoVerdict.ABSTAIN + ) + + exploding = VetoOnlyVLMGuard( + identity_vlm=_ExplodingBackend(), state_verifier=_ExplodingBackend() + ) + id_dec = exploding.check_identity(frame, frame) + st_dec = exploding.check_state(frame, "saved") + assert id_dec.verdict is VetoVerdict.ABSTAIN and id_dec.should_halt is True + assert st_dec.verdict is VetoVerdict.ABSTAIN and st_dec.should_halt is True + + empty = VetoOnlyVLMGuard() + assert empty.check_identity(frame, frame).verdict is VetoVerdict.ABSTAIN + assert empty.check_state(frame, "saved").verdict is VetoVerdict.ABSTAIN + + +def test_guard_state_check_uses_gold_composite_and_veto_only_semantics(): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + + for raw, expected_verdict in [ + ("yes", VetoVerdict.PASS), + ("no", VetoVerdict.VETO), + ("uncertain", VetoVerdict.ABSTAIN), + ]: + stub = _StubClient(state={"holds": raw}) + guard = VetoOnlyVLMGuard(state_verifier=RemoteStateVerifier(stub)) + dec = guard.check_state(frame, "alert visible", roi=roi) + assert dec.verdict is expected_verdict + assert dec.used_gold_crop is True + assert max(stub.state_calls[0][0]) <= _MAX_MODEL_IMAGE_DIM + + +# -------------------------------------------------------------------------- +# 4. Review regressions: egress propagation, bounds checks, symmetric ROI +# -------------------------------------------------------------------------- + + +def test_guard_propagates_egress_classification_to_replayer(): + remote_client = RemoteVLMClient("http://127.0.0.1:9") + remote_id_guard = VetoOnlyVLMGuard(identity_vlm=RemoteIdentityVLM(remote_client)) + remote_state_guard = VetoOnlyVLMGuard( + state_verifier=RemoteStateVerifier(remote_client) + ) + local_guard = VetoOnlyVLMGuard(identity_vlm=_FakeLocalIdentity("same")) + + assert component_may_egress(remote_id_guard) is True + assert component_may_egress(remote_state_guard) is True + assert component_may_egress(local_guard) is False + + # Replayer refuses a wrapped remote comparator without explicit opt-in. + with pytest.raises(EgressNotPermitted): + Replayer(backend=object(), vision=object(), identity_vlm=remote_id_guard) + + # With opt-in, Replayer wires it and sets the egress report flag. + replayer_remote = Replayer( + backend=object(), + vision=object(), + identity_vlm=remote_id_guard, + allow_model_grounding=True, + ) + assert replayer_remote._screenshots_may_leave_box is True + + # Purely local guard requires no opt-in and does not set the egress flag. + replayer_local = Replayer( + backend=object(), vision=object(), identity_vlm=local_guard + ) + assert replayer_local._screenshots_may_leave_box is False + + +@pytest.mark.parametrize( + "bad_point", + [ + [-1, 20], + [999, 20], + [20, 999], + [float("nan"), 20], + [float("inf"), 20], + [True, 20], + ], +) +def test_remote_grounder_rejects_out_of_bounds_local_and_falls_back_to_global( + bad_point, +): + roi = (900, 80, 320, 64) + frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + + # Invalid local point must NOT be translated; must trigger global fallback. + stub = _StubClient( + ground_responses=[ + {"point": bad_point, "confidence": 0.99}, + {"point": [500, 200], "confidence": 0.85}, + ] + ) + match = RemoteGrounder(stub).locate(frame, "Submit", roi=roi) + assert len(stub.ground_calls) == 2 + assert match is not None + assert match.point == (round(500 / (1024 / 2560)), round(200 / (1024 / 2560))) + + # Invalid global point must return None (no proposal). + stub_global_bad = _StubClient( + ground_responses=[ + {"point": bad_point, "confidence": 0.99}, + {"point": [2000, 2000], "confidence": 0.99}, + ] + ) + assert RemoteGrounder(stub_global_bad).locate(frame, "Submit", roi=roi) is None + + +def test_guard_identity_crops_both_frames_symmetrically_or_abstains(): + roi = (200, 80, 320, 64) + large_frame = _make_synthetic_banner_frame(2560, 1440, roi=roi) + small_frame = _make_synthetic_banner_frame(1024, 768, roi=roi) + + # Mixed sizes (one >1024px, one <=1024px): BOTH sides must get ROI crops, + # never a crop paired with an uncropped full screenshot. + backend = _FakeRemoteIdentity(IdentityVerdict.VERIFY) + guard = VetoOnlyVLMGuard(identity_vlm=backend) + dec = guard.check_identity(large_frame, small_frame, roi=roi) + assert dec.verdict is VetoVerdict.PASS + assert dec.used_gold_crop is True + assert len(backend.seen_dims) == 1 + rec_dims, live_dims = backend.seen_dims[0] + assert rec_dims == live_dims + assert rec_dims[0] < 1024 and rec_dims[1] < 768 + + # ROI partially clipped on the smaller frame (x=900..1220 exceeds 1024): + # must ABSTAIN without invoking the backend rather than comparing a partial + # crop against a full crop. + clipped_roi = (900, 80, 320, 64) + backend_clipped = _FakeRemoteIdentity(IdentityVerdict.VERIFY) + dec_clipped = VetoOnlyVLMGuard(identity_vlm=backend_clipped).check_identity( + large_frame, small_frame, roi=clipped_roi + ) + assert dec_clipped.verdict is VetoVerdict.ABSTAIN + assert dec_clipped.reason == "identity_roi_unavailable" + assert dec_clipped.should_halt is True + assert backend_clipped.seen_dims == [] + + # ROI outside the smaller frame: must ABSTAIN without invoking the backend. + oob_roi = (1500, 80, 320, 64) + backend_oob = _FakeRemoteIdentity(IdentityVerdict.VERIFY) + dec_oob = VetoOnlyVLMGuard(identity_vlm=backend_oob).check_identity( + large_frame, small_frame, roi=oob_roi + ) + assert dec_oob.verdict is VetoVerdict.ABSTAIN + assert dec_oob.reason == "identity_roi_unavailable" + assert dec_oob.should_halt is True + assert backend_oob.seen_dims == [] + + # Malformed bytes on one side: must ABSTAIN without invoking the backend. + backend_bad = _FakeRemoteIdentity(IdentityVerdict.VERIFY) + dec_bad = VetoOnlyVLMGuard(identity_vlm=backend_bad).check_identity( + large_frame, b"not-a-png", roi=roi + ) + assert dec_bad.verdict is VetoVerdict.ABSTAIN + assert dec_bad.should_halt is True + assert backend_bad.seen_dims == [] diff --git a/packages/flow/tests/test_remote_vlm.py b/packages/flow/tests/test_remote_vlm.py index 3bc16395d2..db0198cb88 100644 --- a/packages/flow/tests/test_remote_vlm.py +++ b/packages/flow/tests/test_remote_vlm.py @@ -7,8 +7,11 @@ from __future__ import annotations +import io + import httpx import pytest +from PIL import Image from openadapt_flow.runtime.grounder import Grounder, GrounderMatch from openadapt_flow.runtime.remote_vlm import ( @@ -19,7 +22,13 @@ RemoteVLMClient, ) -PNG = b"\x89PNG\r\n\x1a\n" # bytes need not be a real PNG for the client layer +PNG = b"\x89PNG\r\n\x1a\n" # unreadable stub header for transport-failure tests + + +def _valid_png(w: int = 200, h: int = 100) -> bytes: + buf = io.BytesIO() + Image.new("RGB", (w, h), (220, 220, 220)).save(buf, format="PNG") + return buf.getvalue() # --- happy path (baseline: clients pass through good answers) --------------- @@ -54,11 +63,23 @@ def test_grounder_pass_through_point(monkeypatch): ), ) g = RemoteGrounder(RemoteVLMClient("http://x", token="t")) - m = g.locate(PNG, "Save button") + m = g.locate(_valid_png(200, 100), "Save button") assert isinstance(m, GrounderMatch) assert m.point == (120, 45) +def test_grounder_refuses_unreadable_image_bytes(monkeypatch): + monkeypatch.setattr( + httpx, + "post", + lambda url, **kw: httpx.Response( + 200, json={"point": [120, 45], "confidence": 0.9} + ), + ) + g = RemoteGrounder(RemoteVLMClient("http://x", token="t")) + assert g.locate(PNG, "Save button") is None + + def test_remote_grounder_satisfies_protocol(): g = RemoteGrounder(RemoteVLMClient("http://x")) assert isinstance(g, Grounder) diff --git a/packages/flow/tests/test_wire_remote_vlm.py b/packages/flow/tests/test_wire_remote_vlm.py index beff66bab7..f58cfa03b1 100644 --- a/packages/flow/tests/test_wire_remote_vlm.py +++ b/packages/flow/tests/test_wire_remote_vlm.py @@ -112,8 +112,14 @@ def test_grounder_outage_returns_no_proposal(): def test_grounder_proposes_a_point_when_reachable(): + import io + + from PIL import Image + + buf = io.BytesIO() + Image.new("RGB", (200, 100), (220, 220, 220)).save(buf, format="PNG") g = RemoteGrounder(_StubClient(ground={"point": [120, 44], "confidence": 0.9})) - m = g.locate(b"png", "click Save", None) + m = g.locate(buf.getvalue(), "click Save", None) assert m is not None and m.point == (120, 44) From 52a0a7b14bac8ec9e916869ac8e4432ba06fbba4 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:09:55 -0500 Subject: [PATCH 3/5] feat(flow): reason codes on effect-location results; commit the mutant test KeyResult.code says why, from a fixed set (CODES), so a caller can tell "not found" from "found but unreadable" without matching English text. The planted-mutant check of the fail-open spec is now a test; it skips until the harness from #2476 is on the branch. --- .../effect_location/evaluator.py | 122 ++++++++++++++---- packages/flow/tests/test_effect_location.py | 27 ++++ .../tests/test_effect_location_mutants.py | 44 +++++++ 3 files changed, 171 insertions(+), 22 deletions(-) create mode 100644 packages/flow/tests/test_effect_location_mutants.py diff --git a/packages/flow/openadapt_flow/effect_location/evaluator.py b/packages/flow/openadapt_flow/effect_location/evaluator.py index b031a795f0..e139edf622 100644 --- a/packages/flow/openadapt_flow/effect_location/evaluator.py +++ b/packages/flow/openadapt_flow/effect_location/evaluator.py @@ -41,6 +41,7 @@ ) __all__ = [ + "CODES", "HELD", "NOT_CHECKED", "REFUTED", @@ -55,6 +56,32 @@ 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, @@ -81,6 +108,9 @@ class KeyResult: 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) @@ -165,31 +195,39 @@ def _basis(start: Start, claimed: Optional[str]) -> Optional[str]: def _judge(loc: EffectLocation, reading: Reading, run_id: str) -> dict[str, KeyResult]: """Each of ``loc``'s keys judged from one reading.""" - def nc(reason: str, shown: tuple[str, ...] = ()) -> dict[str, KeyResult]: + def nc(code: str, reason: str, shown: tuple[str, ...] = ()) -> dict[str, KeyResult]: return { - k: KeyResult(k, NOT_CHECKED, reason, locations=(loc.id,), shown=shown) + 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(problem) + return nc("bad_record", problem) if not run_id or reading.run_id != run_id: - return nc("the reading belongs to another run") + return nc("other_run", "the reading belongs to another run") if reading.error is not None: - return nc("the read failed") + return nc("read_failed", "the read failed") if not isinstance(reading.complete, bool): - return nc("the reading does not say whether it was complete") + 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("the reading did not start where the location requires") + return nc( + "start_not_met", "the reading did not start where the location requires" + ) found = len(reading.matches) if found == 0: - return nc("the location was not found") + 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(f"found {found} times, expected {loc.expected_count}", shown_all) + 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] @@ -197,11 +235,12 @@ def nc(reason: str, shown: tuple[str, ...] = ()) -> dict[str, KeyResult]: for key in loc.keys: codec = _codec_for(loc, key) - def result(status: str, reason: str) -> KeyResult: + 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,), @@ -209,13 +248,17 @@ def result(status: str, reason: str) -> KeyResult: ) if key not in loc.expected: - out[key] = result(NOT_CHECKED, "the location has no expected value") + 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, "the expected value is not in the codec's form" + NOT_CHECKED, + "bad_expected", + "the expected value is not in the codec's form", ) continue values = [d.get(key) for d in decoded] @@ -224,31 +267,38 @@ def result(status: str, reason: str) -> KeyResult: ] if wrong: # A partial read can refute: it showed a different value. - out[key] = result(REFUTED, "the location shows 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, "the displayed text could not be read") + 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, "the read was partial") + 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, "the baseline is not in the codec's form" + 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, "the location shows the expected value") + out[key] = result(HELD, "shown", "the location shows the expected value") return out @@ -262,13 +312,29 @@ def _combine(key: str, results: Sequence[KeyResult]) -> KeyResult: 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") + 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) + 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) + 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 @@ -279,6 +345,7 @@ def _combine(key: str, results: Sequence[KeyResult]) -> KeyResult: level=weakest.level, basis=basis, word=_compat.word(weakest.level, basis, confirmed=True), + code=weakest.code, locations=locs, shown=shown, ) @@ -343,6 +410,7 @@ def evaluate_all( NOT_CHECKED, "two locations share this id", locations=(loc.id,), + code="duplicate_location", ) ) continue @@ -351,7 +419,11 @@ def evaluate_all( for k in relevant: judged[k].append( KeyResult( - k, NOT_CHECKED, "the location was not read", locations=(loc.id,) + k, + NOT_CHECKED, + "the location was not read", + locations=(loc.id,), + code="not_read", ) ) continue @@ -370,6 +442,7 @@ def evaluate_all( "the location expects a different value than the plan", locations=(loc.id,), shown=r.shown, + code="stale_record", ) judged[k].append(r) @@ -377,7 +450,12 @@ def evaluate_all( for key in planned: if key in conflicted: results.append( - KeyResult(key, NOT_CHECKED, "the plan has two values for this key") + KeyResult( + key, + NOT_CHECKED, + "the plan has two values for this key", + code="plan_conflict", + ) ) else: results.append(_combine(key, judged[key])) diff --git a/packages/flow/tests/test_effect_location.py b/packages/flow/tests/test_effect_location.py index fdd5b1af5b..5a60d0a23b 100644 --- a/packages/flow/tests/test_effect_location.py +++ b/packages/flow/tests/test_effect_location.py @@ -484,3 +484,30 @@ 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" diff --git a/packages/flow/tests/test_effect_location_mutants.py b/packages/flow/tests/test_effect_location_mutants.py new file mode 100644 index 0000000000..826a964ab1 --- /dev/null +++ b/packages/flow/tests/test_effect_location_mutants.py @@ -0,0 +1,44 @@ +"""The fail-open harness kills planted mutants of the effect-location evaluator. + +Each mutant drops one rule (partial reads, the run binding, the expected +count, a read error). The harness must report a failure for each one. Skipped +where the harness (#2476) is not on the branch yet. +""" + +from __future__ import annotations + +from dataclasses import replace +from typing import Any, Callable + +import pytest + +harness = pytest.importorskip("tests.failopen.harness") + +from openadapt_flow.effect_location import evaluator # noqa: E402 + +_JUDGE = evaluator._judge + +MUTANTS: dict[str, Callable[..., Any]] = { + "partial read held": lambda loc, r, run: _JUDGE( + loc, replace(r, complete=True), run + ), + "run binding ignored": lambda loc, r, run: _JUDGE(loc, replace(r, run_id=run), run), + "only the first match": lambda loc, r, run: _JUDGE( + loc, replace(r, matches=r.matches[:1]), run + ), + "read error ignored": lambda loc, r, run: _JUDGE(loc, replace(r, error=None), run), +} + + +def _spec() -> Any: + return harness.load_all()["effect_location.evaluate_all"] + + +def test_the_real_evaluator_holds() -> None: + assert harness.run_site(_spec()) == [] + + +@pytest.mark.parametrize("name", sorted(MUTANTS)) +def test_each_mutant_is_killed(name: str, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(evaluator, "_judge", MUTANTS[name]) + assert harness.run_site(_spec()), f"the harness missed: {name}" From 34b3ce3cdba1c3345f6f88997daf962cbb3562e3 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:41:01 -0500 Subject: [PATCH 4/5] feat(flow): a proven fresh reload is level 3 in the effect-location evaluator Following the coordinator's ruling: a fresh navigation whose adapter names the fresh_reload basis (#2509: cache bypassed, the request kept as evidence) is a level 3 check, which the ladder words VERIFIED. Without that basis it stays level 2 (reopened), SHOWN. The claim never satisfies a location that requires a new session. --- .../effect_location/evaluator.py | 34 ++++++++++++--- packages/flow/tests/test_effect_location.py | 42 +++++++++++++++++++ 2 files changed, 70 insertions(+), 6 deletions(-) diff --git a/packages/flow/openadapt_flow/effect_location/evaluator.py b/packages/flow/openadapt_flow/effect_location/evaluator.py index e139edf622..135f0c8e40 100644 --- a/packages/flow/openadapt_flow/effect_location/evaluator.py +++ b/packages/flow/openadapt_flow/effect_location/evaluator.py @@ -182,14 +182,37 @@ def _shape_problem(loc: EffectLocation) -> Optional[str]: return None -def _basis(start: Start, claimed: Optional[str]) -> Optional[str]: +#: The basis an adapter names for a fresh navigation it proved fetched from +#: the server (cache bypassed, the request kept as evidence). +FRESH_RELOAD = "fresh_reload" + + +def _level_and_basis( + start: Start, claimed: Optional[str] +) -> tuple[CheckLevel, Optional[str]]: + """The level and basis a held check reaches from ``start``. + + A fresh navigation is level 2 (``reopened``, SHOWN) unless the adapter + names the ``fresh_reload`` basis and the ladder lists it at level 3; + then it is level 3, which the ladder words VERIFIED. Another channel is + level 4 with the basis the adapter names, if the ladder lists that basis + at level 4. + """ + + level = LEVEL_OF_START[start] if start is Start.NEW_SESSION: - return "separate_session" + return level, "separate_session" + if ( + start is Start.FRESH_NAVIGATION + and claimed == FRESH_RELOAD + and _compat.reaches(claimed, CheckLevel.SEPARATE_SESSION) + ): + return CheckLevel.SEPARATE_SESSION, claimed if start is Start.OTHER_CHANNEL and _compat.reaches( claimed, CheckLevel.SYSTEM_OF_RECORD ): - return claimed - return None + return level, claimed + return level, None def _judge(loc: EffectLocation, reading: Reading, run_id: str) -> dict[str, KeyResult]: @@ -230,8 +253,7 @@ def nc(code: str, reason: str, shown: tuple[str, ...] = ()) -> dict[str, KeyResu ) 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) + level, basis = _level_and_basis(got, reading.basis) for key in loc.keys: codec = _codec_for(loc, key) diff --git a/packages/flow/tests/test_effect_location.py b/packages/flow/tests/test_effect_location.py index 5a60d0a23b..f355cf23cd 100644 --- a/packages/flow/tests/test_effect_location.py +++ b/packages/flow/tests/test_effect_location.py @@ -432,6 +432,9 @@ def test_a_missing_run_id_never_passes() -> None: ("other_channel", "db_frame", "VERIFIED"), ("other_channel", "separate_session", "RECORDED"), ("same_screen", "db_frame", "SHOWN"), + ("fresh_navigation", "db_frame", "SHOWN"), + ("same_screen", "fresh_reload", "SHOWN"), + ("other_channel", "fresh_reload", "RECORDED"), ], ) def test_words_come_from_the_ladder(start: str, basis: str | None, word: str) -> None: @@ -511,3 +514,42 @@ def test_every_result_carries_a_listed_code() -> None: run_id=RUN, ) assert stale.results[0].code == "stale_record" + + +needs_reload = pytest.mark.skipif( + not _compat.reaches("fresh_reload", CheckLevel.SEPARATE_SESSION), + reason="the fresh_reload basis (#2509) is not on this branch yet", +) + + +@needs_reload +def test_a_proven_fresh_reload_is_level_3_and_verified() -> None: + proven = evaluate( + loc(start="fresh_navigation"), + reading("Ada Byron", start="fresh_navigation", basis="fresh_reload"), + run_id=RUN, + ) + assert proven.level is CheckLevel.SEPARATE_SESSION + assert proven.basis == "fresh_reload" + assert proven.word == "VERIFIED" + + +def test_a_fresh_navigation_without_proof_stays_reopened() -> None: + plain = evaluate( + loc(start="fresh_navigation"), + reading("Ada Byron", start="fresh_navigation"), + run_id=RUN, + ) + assert plain.level is CheckLevel.REOPENED + assert plain.basis is None + if _compat.has_ladder_words(): + assert plain.word == "SHOWN" + + +def test_a_reload_claim_never_meets_a_new_session_requirement() -> None: + report = evaluate( + loc(start="new_session"), + reading("Ada Byron", start="fresh_navigation", basis="fresh_reload"), + run_id=RUN, + ) + assert report.status == "not_checked" From 6e741bf7cab37a16d8776c03ef33f873db6587a4 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:41:41 -0500 Subject: [PATCH 5/5] docs(flow): the fresh_reload level in EFFECT_LOCATION.md --- packages/flow/docs/EFFECT_LOCATION.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/flow/docs/EFFECT_LOCATION.md b/packages/flow/docs/EFFECT_LOCATION.md index d8e4a8cbdb..6f3d0478d6 100644 --- a/packages/flow/docs/EFFECT_LOCATION.md +++ b/packages/flow/docs/EFFECT_LOCATION.md @@ -74,19 +74,21 @@ The check level comes from the start condition the adapter achieved: | Start | Check level | | --- | --- | | `same_screen` | 1, `same_screen` | -| `fresh_navigation` | 2, `reopened` | +| `fresh_navigation` | 2, `reopened`; 3 with basis `fresh_reload` when the adapter proves the navigation fetched from the server (cache bypassed, the request kept) | | `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 +fresh navigation without the reload proof is `SHOWN`; a proven fresh reload +is `VERIFIED`. 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`. +server; the adapter must prove it (a cache-bypassing request and its +response, kept as evidence) before it names the `fresh_reload` basis. ## Fail-open testing