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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions packages/flow/openadapt_flow/form_tx/judge.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,44 @@ def _extract_present_outputs(
return extracted, invalid_keys


def _row_verdicts(
rows: Sequence[Any],
snapshot: FormSnapshot,
expected_facts: Mapping[str, DossierFact],
run_id: str,
not_checked: Any,
failed: Any,
) -> list[ReadbackFieldVerdict]:
"""form_tx verdicts for the summary's multi-value rows (``row_location``)."""
if not rows:
return []
from openadapt_flow.form_tx.row_location import row_readback_results

out: list[ReadbackFieldVerdict] = []
results = row_readback_results(tuple(rows), snapshot, expected_facts, run_id=run_id)
for key, judged in results.items():
fact = expected_facts.get(key)
prov = fact.provenance if fact is not None else ProvenanceKind.INTAKE_DOCUMENT
part = next(p for r in rows for p in r.parts if p.dossier_key == key)
for status, reason in judged:
if status == "held":
out.append(
ReadbackFieldVerdict(
dossier_key=key,
codec_kind=part.codec.kind,
passed=True,
status=ReadbackStatus.PASSED,
provenance=prov,
reason="Read back from a summary row that shows several values",
)
)
elif status == "refuted":
out.append(failed(key, part.codec.kind, prov, f"Summary row: {reason}"))
else:
out.append(not_checked(key, prov, f"Summary row: {reason}"))
return out


class SummaryJudge:
"""Read-back verifier for committed form transactions (acting session)."""

Expand Down Expand Up @@ -545,6 +583,8 @@ def _failed(
}
for sd in summary_check.split_date_readbacks:
declared_keys |= {sd.day_key, sd.month_key, sd.year_key}
for row in summary_check.row_readbacks:
declared_keys |= {part.dossier_key for part in row.parts}
expected_keys = {
binding.dossier_key
for binding in active_pack.bindings
Expand Down Expand Up @@ -846,6 +886,19 @@ def _where(field_writes: Sequence[FieldWriteRecord]) -> str:
)
)

# Rows that show several values in one text ("Name (DOB)"), judged as
# effect locations: each key gets its own verdict.
verdicts.extend(
_row_verdicts(
summary_check.row_readbacks,
snapshot,
expected_facts,
active_dossier.digest(),
_not_checked,
_failed,
)
)

# Fields no binding covers that held a value this run did not set.
for label, shown in sorted((uncovered or {}).items()):
verdicts.append(
Expand Down
177 changes: 177 additions & 0 deletions packages/flow/openadapt_flow/form_tx/row_location.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
"""A summary row that shows several values, judged as one effect location.

A summary often shows two intake values in one row: "Ada Byron (01/31/1990)"
holds a traveller's name and date of birth. Without a way to read the row as
two values, both keys ended ``not_checked``; a pack could only check a derived
string built from both, which says nothing about either key on its own.

A :class:`~openadapt_flow.form_tx.types.SummaryRowReadbackSpec` is turned into
an ``openadapt.effect-location/v1`` record with a ``template`` codec (start
``same_screen``) and judged by the shared evaluator. Each key gets its own
verdict: a row whose date is wrong refutes the date and still checks the name.

Codec mapping (the shared codecs read the displayed part; form_tx's codec
reads the intake value, so the intake keeps its own formats):

- ``whitespace_collapse`` reads as ``text``, ``casefold`` as ``fold``;
- ``iso_date`` reads as ``date`` in the part's ``date_order``.

A part with any other codec leaves every key of the row ``not_checked``.
"""

from __future__ import annotations

import re
from collections.abc import Mapping
from typing import Any

from openadapt_flow.effect_location import (
Codec,
EffectLocation,
Locator,
Reading,
evaluate_all,
)
from openadapt_flow.effect_location.record import Part
from openadapt_flow.form_tx.codecs import (
CodecValueError,
collapse_whitespace,
normalize_with_codec,
)
from openadapt_flow.form_tx.surface import (
AmbiguousAnchorError,
match_anchor_in_snapshot,
match_text_pair_in_snapshot,
)
from openadapt_flow.form_tx.types import (
FieldCodecSpec,
FormCodecKind,
FormSnapshot,
SummaryRowReadbackSpec,
)

__all__ = ["row_readback_results"]

#: The verdicts this module returns, by key: (status, reason).
RowResult = tuple[str, str]


def _codec(spec: FieldCodecSpec) -> Codec:
if spec.kind == FormCodecKind.WHITESPACE_COLLAPSE:
return Codec("text")
if spec.kind == FormCodecKind.CASEFOLD:
return Codec("fold")
if spec.kind == FormCodecKind.ISO_DATE:
return Codec("date", date_order=spec.date_order)
# Any other codec: the shared evaluator judges the record not_checked.
return Codec(f"form_tx:{spec.kind.value}")


def _location(row: SummaryRowReadbackSpec, index: int) -> EffectLocation:
return EffectLocation(
id=f"summary_row:{index}",
keys=tuple(p.dossier_key for p in row.parts),
path=(),
start="same_screen",
locator=Locator(
kind="label",
value="|".join(row.anchor.label_patterns),
section="|".join(row.anchor.section_patterns),
),
codec=Codec(
"template",
pattern=row.pattern,
parts=tuple(
Part(p.group, p.dossier_key, _codec(p.codec)) for p in row.parts
),
),
expected_count=1,
source="form_tx.summary_check.row_readbacks",
)


def _shown(row: SummaryRowReadbackSpec, snapshot: FormSnapshot) -> Reading:
"""What the summary shows for the row, as a reading (not yet bound)."""

try:
ctrl = match_anchor_in_snapshot(row.anchor, snapshot, include_readonly=True)
if ctrl is not None:
texts: tuple[str, ...] = (ctrl.current_value,)
else:
pair = match_text_pair_in_snapshot(row.anchor, snapshot)
texts = (pair.value,) if pair is not None else ()
error = None
except AmbiguousAnchorError:
# Shown more than once: never read as proof.
texts, error = (), "the row is shown more than once"
return Reading(
location_id="",
run_id="",
start="same_screen",
matches=tuple({"text": t} for t in texts),
complete=True,
error=error,
)


def row_readback_results(
rows: tuple[SummaryRowReadbackSpec, ...],
snapshot: FormSnapshot,
expected: Mapping[str, Any],
*,
run_id: str,
) -> dict[str, list[RowResult]]:
"""Each key's verdicts from the summary rows: ``held``, ``refuted`` or
``not_checked``, with a reason.

``expected`` maps an intake key to its value (or to an object with a
``value``). A key with no intake value is not judged here. An intake
value the part's form_tx codec can't read is ``not_checked``.
"""

out: dict[str, list[RowResult]] = {}
for index, row in enumerate(rows):
location = _location(row, index)
plan: dict[str, Any] = {}
for part in row.parts:
if part.dossier_key not in expected:
continue
raw = getattr(
expected[part.dossier_key], "value", expected[part.dossier_key]
)
try:
plan[part.dossier_key] = normalize_with_codec(raw, part.codec)
except CodecValueError:
out.setdefault(part.dossier_key, []).append(
("not_checked", "The intake value can't be read by this codec")
)
shown = _shown(row, snapshot)
# A part with no intake value: like a field read-back, the summary
# must not show a value the run never had (a portal prefill).
for part in row.parts:
if part.dossier_key in expected or part.dossier_key in out:
continue
for match in shown.matches:
fits = re.fullmatch(row.pattern, collapse_whitespace(match["text"]))
group = fits.group(part.group) if fits else None
if group is not None and group.strip():
out.setdefault(part.dossier_key, []).append(
(
"refuted",
"The row shows a value for a key the intake has no value for",
)
)
if not plan:
continue
reading = Reading(
location_id=location.id,
run_id=run_id,
start=shown.start,
matches=shown.matches,
complete=shown.complete,
error=shown.error,
)
report = evaluate_all(plan, [location], [reading], run_id=run_id)
for result in report.results:
out.setdefault(result.key, []).append((result.status, result.reason))
return out
56 changes: 55 additions & 1 deletion packages/flow/openadapt_flow/form_tx/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,14 @@
from enum import Enum
from typing import Any, Literal, Optional

from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from pydantic import (
BaseModel,
ConfigDict,
Field,
field_validator,
model_serializer,
model_validator,
)

FORM_DOSSIER_SCHEMA: Literal["openadapt.form-dossier/v1"] = "openadapt.form-dossier/v1"
UI_PROFILE_SCHEMA: Literal["openadapt.ui-profile/v1"] = "openadapt.ui-profile/v1"
Expand Down Expand Up @@ -465,6 +472,42 @@ class SplitDateReadbackSpec(BaseModel):
date_order: Literal["YMD", "MDY", "DMY"] = "MDY"


class SummaryRowPartSpec(BaseModel):
"""One named group of a summary row and the intake key it shows."""

model_config = ConfigDict(extra="forbid", frozen=True)

group: str = Field(min_length=1)
dossier_key: str = Field(min_length=1)
codec: FieldCodecSpec = Field(default_factory=FieldCodecSpec)


class SummaryRowReadbackSpec(BaseModel):
"""One summary row that shows several intake values in one text.

A row such as "Ada Byron (01/31/1990)" shows a name and a date of birth.
``pattern`` must match the whole shown text; each of ``parts`` reads one
named group as one intake key. The row is judged as an
``openadapt.effect-location/v1`` template location, so each key gets its
own verdict.
"""

model_config = ConfigDict(extra="forbid", frozen=True)

anchor: FieldAnchorSpec
pattern: str = Field(min_length=1)
parts: tuple[SummaryRowPartSpec, ...] = Field(min_length=1)

@field_validator("pattern")
@classmethod
def _pattern_compiles(cls, value: str) -> str:
try:
re.compile(value)
except re.error as exc:
raise ValueError(f"Invalid row pattern {value!r}: {exc}") from exc
return value


class SummaryCheckSpec(BaseModel):
"""Summary/search read-back verification contract (read by the acting session)."""

Expand All @@ -482,8 +525,19 @@ class SummaryCheckSpec(BaseModel):
# review does not show is left to the post-submit read-back.
review_readbacks: tuple[FieldBindingSpec, ...] = ()
split_date_readbacks: tuple[SplitDateReadbackSpec, ...] = ()
# Rows that show several intake values in one text ("Name (DOB)").
row_readbacks: tuple[SummaryRowReadbackSpec, ...] = ()
outputs: tuple[OutputExtractionSpec, ...] = ()

@model_serializer(mode="wrap")
def _omit_empty_rows(self, handler: Any) -> Any:
# Left out while empty, so a pack written before the field existed
# dumps and hashes exactly as before.
data = handler(self)
if isinstance(data, dict) and not data.get("row_readbacks"):
data.pop("row_readbacks", None)
return data


class UnboundControlSpec(BaseModel):
"""A control the pack does not fill, and the value it shows when blank."""
Expand Down
Loading
Loading