diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 77cb5b857c..742b7a7f56 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -180,7 +180,7 @@ improvising or retrying when something is off. | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | -| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. Induction refuses a trace that shows no write it can attribute to a record (an update at the record's URL, or a create whose record is then read there) instead of guessing a route; the CLI allows a guessed item route only when it certifies the lens on a sandbox. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | +| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. Induction refuses a trace that shows no write it can attribute to a record (an update at the record's URL, or a create whose record is then read there) instead of guessing a route; the CLI allows a guessed item route only when it certifies the lens on a sandbox. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. A field the server is seen rewriting between `NULL` and `""` gets a `null_empty` codec, learned per field by the probe or from the trace, so that change alone is not a clobber; any other change on the field still is. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](packages/flow/docs/RECONCILE.md), [results](packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | diff --git a/llms-full.txt b/llms-full.txt index cfb52865db..1500b911d8 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -620,7 +620,7 @@ improvising or retrying when something is off. | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | -| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. Induction refuses a trace that shows no write it can attribute to a record (an update at the record's URL, or a create whose record is then read there) instead of guessing a route; the CLI allows a guessed item route only when it certifies the lens on a sandbox. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | +| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. Induction refuses a trace that shows no write it can attribute to a record (an update at the record's URL, or a create whose record is then read there) instead of guessing a route; the CLI allows a guessed item route only when it certifies the lens on a sandbox. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. A field the server is seen rewriting between `NULL` and `""` gets a `null_empty` codec, learned per field by the probe or from the trace, so that change alone is not a clobber; any other change on the field still is. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECONCILE.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | diff --git a/packages/flow/openadapt_flow/tx/induce.py b/packages/flow/openadapt_flow/tx/induce.py index 541863bca9..e94f07960d 100644 --- a/packages/flow/openadapt_flow/tx/induce.py +++ b/packages/flow/openadapt_flow/tx/induce.py @@ -726,6 +726,43 @@ def _looks_like_metadata_or_volatile(key: str, value: Any) -> bool: return False +def _null_or_empty(value: Any) -> bool: + return value is None or (isinstance(value, str) and value == "") + + +def learn_null_empty_codecs( + before: Mapping[str, Any], + after: Mapping[str, Any], + written_paths: Optional[set[str]] = None, +) -> dict[str, FieldCodec]: + """Fields whose value moved between ``None`` and ``""`` and nothing else. + + Many apps store an untouched optional field as ``NULL`` until a form save + sends ``""`` back for it, or the reverse. Without a declaration the judge + reads that as a clobber (OpenAdapt #2391). Each field this returns gets a + ``null_empty`` codec, so only that field treats the two as one value; any + non-empty change on it is still judged exactly. Fields in + ``written_paths`` are skipped: a value the write asked for is not a server + rewrite. + """ + flat_before = _flatten_record(before) + flat_after = _flatten_record(after) + skip = written_paths or set() + learned: dict[str, FieldCodec] = {} + for path, old in flat_before.items(): + if path in skip or path not in flat_after: + continue + new = flat_after[path] + if ( + old is not new + and old != new + and _null_or_empty(old) + and _null_or_empty(new) + ): + learned[path] = FieldCodec(kind="null_empty") + return learned + + def induce_lens_from_har( har: Mapping[str, Any], *, @@ -1140,6 +1177,7 @@ def induce_lens_from_har( elif path not in create_defaults_list: create_defaults_list.append(path) + null_empty_paths: list[str] = [] requested_values: set[tuple[str, str]] = set() for ex in scoped: if ex.method in {"POST", "PUT", "PATCH"} and ex.req_data: @@ -1158,6 +1196,12 @@ def induce_lens_from_har( old_val = prev_rec[path] if new_val == old_val: continue + # NULL became "" (or the reverse): one empty value, spelled two + # ways. Learn it for this field; never a clobber or a replace. + if _null_or_empty(old_val) and _null_or_empty(new_val): + if path not in null_empty_paths: + null_empty_paths.append(path) + continue # Auto-mutated server field: either echoed unchanged in request yet server # changed it, or server metadata key not in user-supplied fields. A # value some write in the trace asked for is the user's edit, not a @@ -1241,6 +1285,9 @@ def induce_lens_from_har( field_codecs[path] = codec break + for path in null_empty_paths: + field_codecs.setdefault(path, FieldCodec(kind="null_empty")) + # Step 7: Induce stable identity_fields. volatile_set = set(volatile_list) identity_candidates: list[str] = [] @@ -1816,6 +1863,13 @@ def probe_put_semantics( and _looks_like_metadata_or_volatile(path, m_val) ): volatile_list.append(path) + # The merged write sent every untouched field back as read; + # one the server stored as the other empty spelling gets + # a null_empty codec. + for path, codec in learn_null_empty_codecs( + r0, r_merged, set(flat_upd) + ).items(): + codecs.setdefault(path, codec) for path in pending_volatile: if path not in volatile_list and path not in create_defaults_list: @@ -2533,4 +2587,5 @@ def _make_expected_identity(r0: Mapping[str, Any]) -> dict[str, Any]: "induce_lens_from_har", "infer_field_codec", "probe_put_semantics", + "learn_null_empty_codecs", ] diff --git a/packages/flow/openadapt_flow/tx/judge.py b/packages/flow/openadapt_flow/tx/judge.py index cea477bb3d..c039f93996 100644 --- a/packages/flow/openadapt_flow/tx/judge.py +++ b/packages/flow/openadapt_flow/tx/judge.py @@ -154,6 +154,27 @@ def strict_equal(left: Any, right: Any) -> bool: return type(left) is type(right) and bool(left == right) +def is_null_or_empty(value: Any) -> bool: + """``None`` or the empty string, and nothing else (not 0, False or []).""" + return value is None or (isinstance(value, str) and value == "") + + +def null_empty_equivalent( + path: str, + v0: Any, + v1: Any, + field_codecs: Optional[Mapping[str, FieldCodec]], +) -> bool: + """True when ``path`` declares ``null_empty`` and both values are empty.""" + codec = _lookup_field_codec(path, field_codecs) + return ( + codec is not None + and codec.kind == "null_empty" + and is_null_or_empty(v0) + and is_null_or_empty(v1) + ) + + def _is_empty_server_default_value(value: Any) -> bool: """Return True if ``value`` is a benign empty/zero default on record creation.""" if value is None: @@ -601,6 +622,16 @@ def apply_field_codec( ) -> tuple[bool, str]: """Evaluate Tier-1 ``FieldCodec`` normalization or bijection between two values.""" kind = codec.kind + if kind == "null_empty": + ok = strict_equal(intended_val, stored_val) or ( + is_null_or_empty(intended_val) and is_null_or_empty(stored_val) + ) + return ( + ok, + "null_empty codec match" + if ok + else f"null_empty mismatch ({intended_val!r} != {stored_val!r})", + ) if kind == "exact": ok = strict_equal(intended_val, stored_val) return ( @@ -1405,6 +1436,22 @@ def _visit(path: str, v0: Any, v1: Any) -> None: reasons.append(inject_reason) return + if ( + v0 is not _MISSING + and v1 is not _MISSING + and null_empty_equivalent(path, v0, v1, field_codecs) + ): + verdicts.append( + FieldVerdict( + field_path=path, + category="frame", + passed=True, + tier_used="codec", + reason="null and empty string are one value (null_empty codec)", + ) + ) + return + if v1 is _MISSING: wipe_reason = f"untouched field {path!r} deleted in r1 (was {v0!r})" else: diff --git a/packages/flow/openadapt_flow/tx/lens.py b/packages/flow/openadapt_flow/tx/lens.py index eb92f004ac..7c65809f53 100644 --- a/packages/flow/openadapt_flow/tx/lens.py +++ b/packages/flow/openadapt_flow/tx/lens.py @@ -120,6 +120,8 @@ def _normalize_with_codec(val: Any, codec: FieldCodec) -> Any: kind = codec.kind if kind == "exact": return val + if kind == "null_empty": + return "" if val is None else val if kind == "bijection": s = str(val) return codec.mapping.get(s, s) @@ -275,6 +277,8 @@ def evaluate( volatile_fields: tuple[str, ...] = (), field_codecs: Optional[Mapping[str, FieldCodec]] = None, ) -> JudgeVerdict: + from openadapt_flow.tx.judge import null_empty_equivalent + codecs = dict(field_codecs or {}) flat_r1 = _flatten_leaves(r1) flat_delta = _flatten_leaves(intended_delta) @@ -378,7 +382,20 @@ def _covered_by_delta(candidate: str) -> bool: in_r0 = path in flat_r0 in_r1 = path in flat_r1 - if in_r0 and in_r1 and flat_r0[path] == flat_r1[path]: + if ( + in_r0 + and in_r1 + and null_empty_equivalent(path, flat_r0[path], flat_r1[path], codecs) + ): + verdicts.append( + FieldVerdict( + field_path=path, + category="frame", + passed=True, + tier_used="codec", + ) + ) + elif in_r0 and in_r1 and flat_r0[path] == flat_r1[path]: verdicts.append( FieldVerdict( field_path=path, diff --git a/packages/flow/openadapt_flow/tx/types.py b/packages/flow/openadapt_flow/tx/types.py index 0fcdd3280b..67ba4db299 100644 --- a/packages/flow/openadapt_flow/tx/types.py +++ b/packages/flow/openadapt_flow/tx/types.py @@ -36,6 +36,9 @@ "phone_digits", "iso_date", "bijection", + # ``None`` and ``""`` are the same empty value for this field; every + # other value compares exactly. Learned per field, never global. + "null_empty", ] JudgeTier = Literal[ "exact", diff --git a/packages/flow/tests/test_tx_null_empty.py b/packages/flow/tests/test_tx_null_empty.py new file mode 100644 index 0000000000..a7133bb9c6 --- /dev/null +++ b/packages/flow/tests/test_tx_null_empty.py @@ -0,0 +1,115 @@ +"""``NULL`` and ``""`` as one value, declared per field (#2391). + +The judge compared the frame with strict equality, so an app that stores an +untouched optional field as ``NULL`` and writes ``""`` back on a form save got +every correct save called a clobber. The fix is a ``null_empty`` field codec: +learned from what the server did, scoped to the field, and never treating +``0``, ``False``, ``[]`` or any non-empty value as empty. +``test_tx_null_empty_live.py`` reproduces the case on a real app. +""" + +from __future__ import annotations + +import pytest + +from openadapt_flow.tx.induce import induce_lens_from_har, learn_null_empty_codecs +from openadapt_flow.tx.judge import FrameAndIntentJudge, apply_field_codec +from openadapt_flow.tx.lens import _FallbackExactAndFrameJudge +from openadapt_flow.tx.types import FieldCodec + +NE = FieldCodec(kind="null_empty") +BEFORE = {"id": 1, "phone": "555-0100", "email": None, "city": None, "note": "x"} +AFTER = {"id": 1, "phone": "555-0199", "email": "", "city": "", "note": "x"} +INTENT = {"phone": "555-0199"} + + +@pytest.mark.parametrize( + "a,b,ok", + [ + (None, "", True), + ("", None, True), + (None, None, True), + ("a", "a", True), + (None, 0, False), + ("", False, False), + (None, [], False), + ("", "a", False), + (None, "None", False), + ], +) +def test_codec_equates_only_the_two_empty_spellings(a, b, ok) -> None: + assert apply_field_codec(NE, a, b)[0] is ok + + +@pytest.mark.parametrize( + "judge", [FrameAndIntentJudge(), _FallbackExactAndFrameJudge()] +) +def test_without_a_codec_the_rewrite_is_a_clobber(judge) -> None: + verdict = judge.evaluate(BEFORE, AFTER, INTENT) + assert not verdict.passed + assert set(verdict.clobbered_fields) == {"email", "city"} + + +@pytest.mark.parametrize( + "judge", [FrameAndIntentJudge(), _FallbackExactAndFrameJudge()] +) +def test_learned_codec_passes_the_rewrite_and_nothing_else(judge) -> None: + codecs = learn_null_empty_codecs(BEFORE, AFTER, set(INTENT)) + assert set(codecs) == {"email", "city"} + assert judge.evaluate(BEFORE, AFTER, INTENT, field_codecs=codecs).passed + + clobber = {**AFTER, "email": "someone@example.test", "note": ""} + verdict = judge.evaluate(BEFORE, clobber, INTENT, field_codecs=codecs) + assert not verdict.passed + assert set(verdict.clobbered_fields) == {"email", "note"} + + +def test_learner_skips_written_fields_and_non_empty_changes() -> None: + before = {"a": None, "b": "", "c": 0, "d": "x", "e": None} + after = {"a": "", "b": None, "c": None, "d": "", "e": ""} + assert set(learn_null_empty_codecs(before, after, {"e"})) == {"a", "b"} + + +def test_codec_on_an_unrelated_field_does_not_cover_others() -> None: + codecs = {"email": NE} + verdict = FrameAndIntentJudge().evaluate(BEFORE, AFTER, INTENT, field_codecs=codecs) + assert verdict.clobbered_fields == ("city",) + + +def _entry(method: str, url: str, req: object, resp: object) -> dict: + import json + + out: dict = { + "request": {"method": method, "url": url, "headers": []}, + "response": { + "status": 200, + "headers": [], + "content": {"mimeType": "application/json", "text": json.dumps(resp)}, + }, + } + if req is not None: + out["request"]["postData"] = { + "mimeType": "application/json", + "text": json.dumps(req), + } + return out + + +def test_har_induction_learns_the_codec_instead_of_replace_mode() -> None: + base = "http://127.0.0.1:8000" + r0 = {"id": 7, "phone": "1", "email": None, "city": None} + r1 = {"id": 7, "phone": "2", "email": "", "city": ""} + har = { + "log": { + "version": "1.2", + "entries": [ + _entry("GET", f"{base}/api/rec/7", None, r0), + _entry("PUT", f"{base}/api/rec/7", {"phone": "2"}, r1), + _entry("GET", f"{base}/api/rec/7", None, r1), + ], + } + } + lens = induce_lens_from_har(har) + assert lens.field_codecs["email"].kind == "null_empty" + assert lens.field_codecs["city"].kind == "null_empty" + assert lens.write_mode == "patch" diff --git a/packages/flow/tests/test_tx_null_empty_live.py b/packages/flow/tests/test_tx_null_empty_live.py new file mode 100644 index 0000000000..b46f3588a1 --- /dev/null +++ b/packages/flow/tests/test_tx_null_empty_live.py @@ -0,0 +1,170 @@ +"""``NULL`` versus ``""`` on a real app's first form save (#2391), lab only. + +The real-app benchmark saw OpenEMR's demographics form write ``""`` back for +optional fields that were ``NULL``, so the judge called every correct GUI +save a clobber. This test reproduces that on a local OpenEMR 7.0.3 with a +headless browser, then checks the general fix: the change is learned per +field as a ``null_empty`` codec, the correct save passes, and a real clobber +on the same save is still caught. + +Set ``OAFLOW_TX_LIVE_OPENEMR_URL`` (for example ``http://127.0.0.1:9746``) and +``OAFLOW_TX_LIVE_OPENEMR_SQL`` (a command that runs SQL from stdin against the +app's database, for example ``docker exec -i mariadb -uopenemr +-popenemr openemr``). The sign-in defaults are the fixture account from +``benchmark/openemr_live/docker-compose.yml``. Synthetic records only; the +browser is headless. +""" + +from __future__ import annotations + +import os +import secrets +import shlex +import subprocess +from typing import Any + +import pytest + +URL = os.environ.get("OAFLOW_TX_LIVE_OPENEMR_URL", "").strip().rstrip("/") +SQL = os.environ.get("OAFLOW_TX_LIVE_OPENEMR_SQL", "").strip() +USER = os.environ.get("OAFLOW_TX_LIVE_OPENEMR_USER", "admin") +PASS = os.environ.get("OAFLOW_TX_LIVE_OPENEMR_PASS", "pass") + +pytestmark = pytest.mark.skipif( + not (URL and SQL), reason="set OAFLOW_TX_LIVE_OPENEMR_URL and _SQL" +) + +#: Columns the test reads. ``phone_home`` is the field the save intends to +#: change; the rest are optional demographics left NULL at seed time. +COLUMNS = ( + "pid", + "fname", + "lname", + "DOB", + "phone_home", + "phone_cell", + "email", + "street", + "city", + "postal_code", + "occupation", +) + + +def _sql(statement: str) -> str: + done = subprocess.run( + shlex.split(SQL), input=statement, capture_output=True, text=True, timeout=60 + ) + assert done.returncode == 0, done.stderr[-400:] + return done.stdout + + +def _row(pid: int) -> dict[str, Any]: + out = _sql( + "SELECT " + + ", ".join(f"IFNULL(CONCAT('=', {c}), '') AS {c}" for c in COLUMNS) + + f" FROM patient_data WHERE pid = {pid};" + ) + header, values = out.strip().splitlines()[:2] + row: dict[str, Any] = {} + for name, raw in zip(header.split("\t"), values.split("\t")): + row[name] = None if raw == "" else raw[1:] + return row + + +def _seed() -> int: + tag = secrets.token_hex(3) + out = _sql( + "SET @p := (SELECT COALESCE(MAX(pid),0)+1 FROM patient_data); " + "INSERT INTO patient_data (pid, pubpid, fname, lname, DOB, phone_home, " + "uuid, date, regdate) VALUES (@p, 'LENS%s', 'Test', 'Aalens%s', " + "'1970-01-01', '555-0100', UNHEX(REPLACE(UUID(),'-','')), NOW(), NOW()); " + "SELECT @p;" % (tag, tag) + ) + return int(out.strip().splitlines()[-1]) + + +def _gui_save(pid: int, phone: str) -> None: + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + browser = pw.chromium.launch(headless=True) + try: + page = browser.new_context().new_page() + page.set_default_timeout(60_000) + page.goto(URL + "/interface/login/login.php?site=default") + page.fill("#authUser", USER) + page.fill("#clearPass", PASS) + page.click("#login-button") + page.wait_for_selector("#mainBox", state="attached") + page.goto( + URL + f"/interface/patient_file/summary/demographics.php?set_pid={pid}" + ) + page.goto(URL + "/interface/patient_file/summary/demographics_full.php") + page.wait_for_selector("input[name=form_phone_home]", state="attached") + page.eval_on_selector( + "input[name=form_phone_home]", "(e, v) => { e.value = v; }", phone + ) + with page.expect_navigation(wait_until="domcontentloaded"): + page.click("#submit_btn") + finally: + browser.close() + + +@pytest.fixture(scope="module") +def first_save() -> tuple[dict[str, Any], dict[str, Any]]: + pid = _seed() + try: + before = _row(pid) + _gui_save(pid, "555-0199") + after = _row(pid) + finally: + _sql(f"DELETE FROM patient_data WHERE pid = {pid};") + return before, after + + +def test_live_first_form_save_rewrites_null_to_empty(first_save) -> None: + """The app behaviour the benchmark saw, reproduced.""" + before, after = first_save + assert after["phone_home"] == "555-0199" + rewritten = [ + c for c in COLUMNS if before[c] is None and after[c] == "" and c != "phone_home" + ] + assert rewritten, (before, after) + + +def test_live_judge_without_codec_calls_the_correct_save_a_clobber(first_save) -> None: + from openadapt_flow.tx.judge import FrameAndIntentJudge + + before, after = first_save + verdict = FrameAndIntentJudge().evaluate(before, after, {"phone_home": "555-0199"}) + assert not verdict.passed and verdict.clobbered_fields + + +def test_live_learned_codec_passes_the_correct_save(first_save) -> None: + from openadapt_flow.tx.induce import learn_null_empty_codecs + from openadapt_flow.tx.judge import FrameAndIntentJudge + + before, after = first_save + codecs = learn_null_empty_codecs(before, after, {"phone_home"}) + assert codecs and all(c.kind == "null_empty" for c in codecs.values()) + verdict = FrameAndIntentJudge().evaluate( + before, after, {"phone_home": "555-0199"}, field_codecs=codecs + ) + assert verdict.passed, verdict.reasons + + +def test_live_learned_codec_still_catches_a_real_clobber(first_save) -> None: + """The codec covers only the two empty spellings on the learned fields.""" + from openadapt_flow.tx.induce import learn_null_empty_codecs + from openadapt_flow.tx.judge import FrameAndIntentJudge + + before, after = first_save + codecs = learn_null_empty_codecs(before, after, {"phone_home"}) + learned = sorted(codecs)[0] + clobbered = {**after, learned: "overwritten", "lname": ""} + verdict = FrameAndIntentJudge().evaluate( + before, clobbered, {"phone_home": "555-0199"}, field_codecs=codecs + ) + assert not verdict.passed + assert set(verdict.clobbered_fields) >= {learned, "lname"}