From 8bce1e344f368ca4c7f892748155c6d880e4b90b Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 1 Dec 2026 02:25:50 -0500 Subject: [PATCH 1/4] fix(transducer): resume from the WAL without losing or duplicating a save After a crash, wrap could neither confirm the saves made before the restart (the values it would look for were in memory) nor stop the fresh session from saving them again: the WAL skips a repeated commit only once it is VERIFIED, and pre-crash commits are still pending. A live control on a web EMR (save, kill, redo the item) ended with two records and a VERIFIED receipt (#2869). Each commit now stores the field-bound values it saved in its WAL summary. On resume they are rebuilt; once they reappear on a saved screen of the pinned record, the commit is marked verified and the agent is told the record already exists. A commit whose form carries exactly the values of an earlier commit (including an unconfirmed one from before the restart) is refused with a hint to check first, and a second attempt hands the item to a person. The done gate never verifies when two commits carry identical values. A navigation click ends the form a commit saves, so a search query on the way is not part of it. Fixes #2869. --- openadapt/simplex_transducer.py | 30 +++++++ openadapt/transducer_v3_runtime.py | 128 +++++++++++++++++++++++++++- tests/test_transducer_v3_runtime.py | 86 +++++++++++++++++++ 3 files changed, 243 insertions(+), 1 deletion(-) diff --git a/openadapt/simplex_transducer.py b/openadapt/simplex_transducer.py index 8f5803dbbf..c18efa6196 100644 --- a/openadapt/simplex_transducer.py +++ b/openadapt/simplex_transducer.py @@ -3826,11 +3826,41 @@ def _route_action_inner( action = self._v3.egress_gate(state, action, observation, task, history) if self._is_commit_boundary(action): + dup = self._v3.duplicate_of(state) + if dup is not None: + ep = self._v3.ep(state) + if dup in ep.duplicate_warned: + return self._abstain_action( + state, + trap_code="DUPLICATE_SAVE", + reason=( + f"The same values were saved before (commit #{dup}); " + "saving them again could duplicate the record." + ), + commit_index=dup, + ) + ep.duplicate_warned.add(dup) + self._deliver_intervention( + state, + kind="DUPLICATE_SAVE", + hint=( + f"DUPLICATE_SAVE: these exact values were already sent in " + f"commit #{dup} and may already be stored. Do not save them " + "again. Open the record and check whether it is there; if it " + "is, finish or continue with what is left." + ), + delta_note=f"duplicate_of={dup}", + fast_forward_obs=observation, + ) + return self._reenter(state, observation, task, history) self._v3.note_commit(state, action) fp = _commit_fingerprint(action, observation=observation) safe_summary = { "type": _action_type_str(action), "raw_action": self.vault.redact(_action_raw_dict(action)), + "field_writes": self.vault.redact( + self._v3.field_writes_for(state, commit_index) + ), } existing_rec = self.wal.get(run_id, task_id, commit_index) if existing_rec is None: diff --git a/openadapt/transducer_v3_runtime.py b/openadapt/transducer_v3_runtime.py index 14eebb0364..e261590a70 100644 --- a/openadapt/transducer_v3_runtime.py +++ b/openadapt/transducer_v3_runtime.py @@ -189,6 +189,11 @@ class SavedWrite: value: str commit_index: int confirmed: bool = False + # Typed into the form that the commit saved (after the last non-commit + # click), as opposed to a search box on the way there. + in_form: bool = True + # Rebuilt from the on-disk WAL after a restart. + restored: bool = False @dataclass @@ -222,6 +227,11 @@ class V3EpisodeState: writes: list[SavedWrite] = field(default_factory=list) typed_keys_since_commit: set[str] = field(default_factory=set) identity_seen: bool = False + # Keys typed since the last non-commit click: the form a commit saves. + form_keys: set[str] = field(default_factory=set) + writes_restored: bool = False + duplicate_warned: set[int] = field(default_factory=set) + reconciled_notified: set[int] = field(default_factory=set) class TransducerV3Hooks: @@ -566,9 +576,14 @@ def note_commit(self, state: EpisodeState, action: Any) -> None: """Count a routed commit as a workspace write or a GUI/remote commit.""" ep = self.ep(state) for key, value in ep.drafts.items(): - ep.writes.append(SavedWrite(key, value, state.next_commit_index)) + ep.writes.append( + SavedWrite( + key, value, state.next_commit_index, in_form=key in ep.form_keys + ) + ) ep.drafts.clear() ep.typed_keys_since_commit.clear() + ep.form_keys.clear() raw = _raw(action) or {} remote = ( raw.get("wire_mutation") is True @@ -625,6 +640,8 @@ def after_step( if kind in _EDIT_ACTION_TYPES or raw.get("fs_write") is True: ep.mutated = True self._note_drafts(ep, observation, action) + if kind == "click" and not self.owner._is_commit_boundary(action): + ep.form_keys.clear() # a navigation click leaves the form if ep.obligations and kind in ("fill", "type", "input", "set_value"): text = _get(action, "text") or raw.get("value") or raw.get("text") or "" mark_drafted_from_action(ep.obligations, str(text)) @@ -1012,6 +1029,106 @@ def _note_drafts(self, ep: V3EpisodeState, observation: Any, action: Any) -> Non continue ep.drafts[key] = str(value) ep.typed_keys_since_commit.add(key) + ep.form_keys.add(key) + + # -- crash resume ------------------------------------------------------- + def field_writes_for( + self, state: EpisodeState, commit_index: int + ) -> list[dict[str, Any]]: + """The writes a commit saved, for the WAL, so a restart can confirm them.""" + ep = self.ep(state) + return [ + {"field_key": w.field_key, "value": w.value, "in_form": w.in_form} + for w in ep.writes + if w.commit_index == commit_index and not w.restored + ] + + def _restore_writes(self, state: EpisodeState, ep: V3EpisodeState) -> None: + """After a restart, rebuild each earlier commit's writes from the WAL.""" + if ep.writes_restored or not state.loaded_from_cold_wal: + return + ep.writes_restored = True + for rec in state.saga_commits: + summary = ( + rec.action_summary if isinstance(rec.action_summary, Mapping) else {} + ) + for fw in summary.get("field_writes") or []: + if isinstance(fw, Mapping) and fw.get("field_key"): + ep.writes.append( + SavedWrite( + str(fw["field_key"]), + str(fw.get("value") or ""), + rec.commit_index, + in_form=bool(fw.get("in_form", True)), + restored=True, + ) + ) + + @staticmethod + def _form_groups(ep: V3EpisodeState) -> dict[tuple[int, bool], dict[str, str]]: + """(commit index, restored) -> {field key: value} of what that commit's form saved.""" + groups: dict[tuple[int, bool], dict[str, str]] = {} + for w in ep.writes: + if w.in_form and w.value.strip(): + groups.setdefault((w.commit_index, w.restored), {})[w.field_key] = ( + _norm_text(w.value) + ) + return groups + + def _reconcile_restored( + self, state: EpisodeState, ep: V3EpisodeState, observation: Any + ) -> None: + """A commit from before the restart whose saved values are all on screen + again (for the pinned record) is stored: mark it verified and say so.""" + for (idx, restored), _values in self._form_groups(ep).items(): + if not restored or idx in ep.reconciled_notified: + continue + group = [ + w + for w in ep.writes + if w.restored + and w.commit_index == idx + and w.in_form + and w.value.strip() + ] + if group and all(w.confirmed for w in group): + ep.reconciled_notified.add(idx) + self.owner._mark_verified(state, idx, tier=1) + self.owner._deliver_intervention( + state, + kind="COMMIT_ALREADY_SAVED", + hint=( + f"COMMIT_ALREADY_SAVED: the save from before the restart (commit " + f"#{idx}) is already stored for this record; its values are on " + "screen. Do not enter it again. Continue with what is left, or finish." + ), + delta_note=f"restored_commit_confirmed={idx}", + fast_forward_obs=observation, + ) + + def duplicate_of(self, state: EpisodeState) -> int | None: + """The earlier commit whose form saved exactly the values about to be saved. + + Saving the same values again makes a second record, or re-saves one that + exists; neither is needed. A commit from before a restart counts even if it + was never confirmed: it may already be stored. + """ + ep = self.ep(state) + current = { + k: _norm_text(v) + for k, v in ep.drafts.items() + if k in ep.form_keys and str(v).strip() + } + if not current: + return None + for (idx, _restored), values in self._form_groups(ep).items(): + if values == current: + return idx + return None + + def has_duplicate_commits(self, state: EpisodeState) -> bool: + groups = [v for v in self._form_groups(self.ep(state)).values() if v] + return any(groups[i] == groups[j] for i in range(len(groups)) for j in range(i)) def observe_saved(self, state: EpisodeState, observation: Any, task: Any) -> None: """Confirm writes that reappear on a saved screen of the pinned record. @@ -1026,6 +1143,7 @@ def observe_saved(self, state: EpisodeState, observation: Any, task: Any) -> Non agent has not typed into that field since the save. """ ep = self.ep(state) + self._restore_writes(state, ep) pins = [_norm_text(v) for v in self.owner.pinned.values() if str(v).strip()] if not pins or not ep.writes: return @@ -1056,6 +1174,7 @@ def observe_saved(self, state: EpisodeState, observation: Any, task: Any) -> Non w.confirmed = True elif len(value) >= _MIN_VERBATIM_CHARS and value in saved: w.confirmed = True + self._reconcile_restored(state, ep, observation) def _met_by_saved_writes( self, ob: CompiledFieldObligation, writes: Sequence[SavedWrite] @@ -1200,6 +1319,13 @@ def pre_done( is_toast=bool(back.get("is_toast")), completeness_auditor=self.completeness_auditor, ) + if self.has_duplicate_commits(state): + self._release_unverified( + state, + commit_idx, + "Two saves carried the same values: the record may be duplicated.", + ) + return action if ( not diff.all_verified and self.completeness_auditor is None diff --git a/tests/test_transducer_v3_runtime.py b/tests/test_transducer_v3_runtime.py index 7a3603a43d..a8cbeea4a4 100644 --- a/tests/test_transducer_v3_runtime.py +++ b/tests/test_transducer_v3_runtime.py @@ -348,3 +348,89 @@ def test_value_typed_after_the_save_does_not_confirm_it(): reopened = _fb_dom("CPT 29881; units 1", "2026-12-16", reopened=True) receipt = _fb_run(reopened, _HEADER, retype) assert receipt is None or receipt.outcome != ReceiptOutcome.VERIFIED + + +# -- crash resume: confirm pre-crash saves from the WAL, refuse a duplicate ------- + + +def _crash_wrap(tmp_path, *actions): + from openadapt.simplex_transducer import WriteAheadSagaLog + + agent = Mock() + agent.act.side_effect = list(actions) + [{"type": "done"}] * 6 + wrapped = SimplexTransducer( + agent, + wal=WriteAheadSagaLog(tmp_path / "wal.jsonl"), + pinned=_FB_PINNED, + config=SupervisorConfig(enable_obligation_compiler=True), + ) + return wrapped, agent + + +def _first_session(tmp_path): + wrapped, _ = _crash_wrap(tmp_path, _FB_FILL, _FB_SAVE) + wrapped.act(_fb_obs(_fb_dom(), _HEADER), _FB_TASK) + wrapped.act(_fb_obs(_fb_dom("CPT 29881; units 1", "2026-12-16"), _HEADER), _FB_TASK) + # the process dies here, after the save was sent + + +def test_commit_persists_the_values_it_saved(tmp_path): + import json as _json + + _first_session(tmp_path) + rows = [ + _json.loads(x) for x in (tmp_path / "wal.jsonl").read_text().splitlines() if x + ] + writes = [ + fw + for r in rows + for fw in (r.get("action_summary") or {}).get("field_writes") or [] + ] + assert {fw["value"] for fw in writes if fw["in_form"]} == { + "CPT 29881; units 1", + "2026-12-16", + } + + +def test_restart_confirms_the_pre_crash_save_on_screen(tmp_path): + _first_session(tmp_path) + wrapped, agent = _crash_wrap(tmp_path, _FB_EDIT) + reopened = _fb_dom("CPT 29881; units 1", "2026-12-16", reopened=True) + wrapped.act(_fb_obs(reopened, _HEADER), _FB_TASK) + state = wrapped.get_state("default-run", "default-task") + hints = [str(iv) for iv in state.intervention_log] + assert any("COMMIT_ALREADY_SAVED" in h for h in hints) + from openadapt.simplex_transducer import SagaState + + assert any( + c.state is SagaState.VERIFIED + for c in wrapped.wal.commits_for("default-run", "default-task") + ) + + +def test_restart_refuses_to_save_the_same_values_again(tmp_path): + _first_session(tmp_path) + # the fresh session repeats the whole item without checking first + wrapped, agent = _crash_wrap(tmp_path, _FB_FILL, _FB_SAVE, _FB_SAVE, _FB_SAVE) + wrapped.act(_fb_obs(_fb_dom(), _HEADER), _FB_TASK) + filled = _fb_dom("CPT 29881; units 1", "2026-12-16") + first = wrapped.act(_fb_obs(filled, _HEADER), _FB_TASK) + state = wrapped.get_state("default-run", "default-task") + assert any("DUPLICATE_SAVE" in str(iv) for iv in state.intervention_log) + assert not (isinstance(first, dict) and first.get("is_commit")) + second = wrapped.act(_fb_obs(filled, _HEADER), _FB_TASK) + assert getattr(second, "is_abstained", False) + assert second.raw_action["trap_code"] == "DUPLICATE_SAVE" + + +def test_identical_re_save_in_one_session_is_not_released(tmp_path): + # In one process the in-memory form latch already stops this; the WAL-based + # duplicate check is what covers it after a restart. + wrapped, _ = _crash_wrap(tmp_path, _FB_FILL, _FB_SAVE, _FB_FILL, _FB_SAVE, _FB_SAVE) + filled = _fb_dom("CPT 29881; units 1", "2026-12-16") + for dom in (_fb_dom(), filled, _fb_dom(), filled): + out = wrapped.act(_fb_obs(dom, _HEADER), _FB_TASK) + state = wrapped.get_state("default-run", "default-task") + hints = " ".join(str(iv) for iv in state.intervention_log) + assert "DUPLICATE_SAVE" in hints or "FORM_COMMIT_LATCHED" in hints + assert not (isinstance(out, dict) and out.get("is_commit")) From d44cb10eb29109405d87063409880dc9ebf4843a Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 1 Dec 2026 04:29:49 -0500 Subject: [PATCH 2/4] fix(transducer): scope duplicate refusal to the pinned record and to repeats the task names The same values on another record, or a second identical entry the task asks for, are not duplicates. A commit now records whether its screen showed the pinned record. The refusal and the done rule compare only commits on the pinned record, and allow as many identical commits as the instruction names that content (its longest value). Without a pinned identity nothing is refused. The in-session form latch follows the same rule for repeats the task names. --- openadapt/simplex_transducer.py | 2 +- openadapt/transducer_fact_ledger.py | 3 + openadapt/transducer_v3_runtime.py | 105 ++++++++++++++++++++++------ tests/test_transducer_v3_runtime.py | 79 +++++++++++++++++++++ 4 files changed, 166 insertions(+), 23 deletions(-) diff --git a/openadapt/simplex_transducer.py b/openadapt/simplex_transducer.py index c18efa6196..fb5fdf0121 100644 --- a/openadapt/simplex_transducer.py +++ b/openadapt/simplex_transducer.py @@ -3826,7 +3826,7 @@ def _route_action_inner( action = self._v3.egress_gate(state, action, observation, task, history) if self._is_commit_boundary(action): - dup = self._v3.duplicate_of(state) + dup = self._v3.duplicate_of(state, task) if dup is not None: ep = self._v3.ep(state) if dup in ep.duplicate_warned: diff --git a/openadapt/transducer_fact_ledger.py b/openadapt/transducer_fact_ledger.py index 27303226c6..68dc82cd67 100644 --- a/openadapt/transducer_fact_ledger.py +++ b/openadapt/transducer_fact_ledger.py @@ -701,6 +701,9 @@ def latch_gate( raw = _get(action, "raw_action") if isinstance(raw, Mapping) and raw.get("allow_duplicate") is True: return action + v3 = getattr(owner, "_v3", None) + if v3 is not None and v3.repeat_allowed(state, task): + return action # the task names this content again: not a re-submit key = submit_control_key(action) text = " ".join([submit_text(action), *state.form_latch.typed()]) hit = state.form_latch.match(key, text) diff --git a/openadapt/transducer_v3_runtime.py b/openadapt/transducer_v3_runtime.py index e261590a70..e8929b152d 100644 --- a/openadapt/transducer_v3_runtime.py +++ b/openadapt/transducer_v3_runtime.py @@ -194,6 +194,9 @@ class SavedWrite: in_form: bool = True # Rebuilt from the on-disk WAL after a restart. restored: bool = False + # The screen at commit time showed every pinned identity value: the save + # belongs to the pinned record. + on_record: bool = False @dataclass @@ -230,6 +233,7 @@ class V3EpisodeState: # Keys typed since the last non-commit click: the form a commit saves. form_keys: set[str] = field(default_factory=set) writes_restored: bool = False + screen_on_record: bool = False duplicate_warned: set[int] = field(default_factory=set) reconciled_notified: set[int] = field(default_factory=set) @@ -578,7 +582,11 @@ def note_commit(self, state: EpisodeState, action: Any) -> None: for key, value in ep.drafts.items(): ep.writes.append( SavedWrite( - key, value, state.next_commit_index, in_form=key in ep.form_keys + key, + value, + state.next_commit_index, + in_form=key in ep.form_keys, + on_record=ep.screen_on_record, ) ) ep.drafts.clear() @@ -1038,7 +1046,12 @@ def field_writes_for( """The writes a commit saved, for the WAL, so a restart can confirm them.""" ep = self.ep(state) return [ - {"field_key": w.field_key, "value": w.value, "in_form": w.in_form} + { + "field_key": w.field_key, + "value": w.value, + "in_form": w.in_form, + "on_record": w.on_record, + } for w in ep.writes if w.commit_index == commit_index and not w.restored ] @@ -1061,14 +1074,19 @@ def _restore_writes(self, state: EpisodeState, ep: V3EpisodeState) -> None: rec.commit_index, in_form=bool(fw.get("in_form", True)), restored=True, + on_record=bool(fw.get("on_record", False)), ) ) @staticmethod - def _form_groups(ep: V3EpisodeState) -> dict[tuple[int, bool], dict[str, str]]: + def _form_groups( + ep: V3EpisodeState, *, on_record_only: bool = False + ) -> dict[tuple[int, bool], dict[str, str]]: """(commit index, restored) -> {field key: value} of what that commit's form saved.""" groups: dict[tuple[int, bool], dict[str, str]] = {} for w in ep.writes: + if on_record_only and not w.on_record: + continue if w.in_form and w.value.strip(): groups.setdefault((w.commit_index, w.restored), {})[w.field_key] = ( _norm_text(w.value) @@ -1106,29 +1124,70 @@ def _reconcile_restored( fast_forward_obs=observation, ) - def duplicate_of(self, state: EpisodeState) -> int | None: - """The earlier commit whose form saved exactly the values about to be saved. - - Saving the same values again makes a second record, or re-saves one that - exists; neither is needed. A commit from before a restart counts even if it - was never confirmed: it may already be stored. - """ - ep = self.ep(state) - current = { + def _current_form(self, ep: V3EpisodeState) -> dict[str, str]: + return { k: _norm_text(v) for k, v in ep.drafts.items() if k in ep.form_keys and str(v).strip() } + + def _times_task_names( + self, state: EpisodeState, task: Any, values: Mapping[str, str] + ) -> int: + """How many times the instruction names this content (its longest value). + A task that wants two identical entries names the content twice.""" + longest = max(values.values(), key=len, default="") + if len(longest) < _MIN_VERBATIM_CHARS: + return 1 + return max(1, _norm_text(self._instruction(state, task)).count(longest)) + + def repeat_allowed(self, state: EpisodeState, task: Any) -> bool: + """The form about to be saved repeats earlier content the task asks for again.""" + ep = self.ep(state) + current = self._current_form(ep) if not current: + return False + same = sum(1 for v in self._form_groups(ep).values() if v == current) + return 0 < same < self._times_task_names(state, task, current) + + def duplicate_of(self, state: EpisodeState, task: Any = None) -> int | None: + """The earlier commit, on the same pinned record, whose form saved exactly + the values about to be saved, beyond what the task asks for. + + Saving the same values again on the same record makes a second entry, + or re-saves one that exists. A commit from before a restart counts even + if it was never confirmed: it may already be stored. The same values on + another record, or repeats the task names, are not duplicates. Without a + pinned record identity there is no record to scope to, so nothing is + refused. + """ + ep = self.ep(state) + if not [v for v in self.owner.pinned.values() if str(v).strip()]: return None - for (idx, _restored), values in self._form_groups(ep).items(): - if values == current: - return idx - return None + if not ep.screen_on_record: + return None + current = self._current_form(ep) + if not current: + return None + same = [ + idx + for (idx, _r), values in self._form_groups(ep, on_record_only=True).items() + if values == current + ] + if not same or len(same) < self._times_task_names(state, task, current): + return None + return same[0] - def has_duplicate_commits(self, state: EpisodeState) -> bool: - groups = [v for v in self._form_groups(self.ep(state)).values() if v] - return any(groups[i] == groups[j] for i in range(len(groups)) for j in range(i)) + def has_duplicate_commits(self, state: EpisodeState, task: Any = None) -> bool: + """More commits on the pinned record carried identical values than the task names.""" + ep = self.ep(state) + groups = [v for v in self._form_groups(ep, on_record_only=True).values() if v] + for g in groups: + if sum(1 for h in groups if h == g) > self._times_task_names( + state, task, g + ): + return True + return False def observe_saved(self, state: EpisodeState, observation: Any, task: Any) -> None: """Confirm writes that reappear on a saved screen of the pinned record. @@ -1145,13 +1204,15 @@ def observe_saved(self, state: EpisodeState, observation: Any, task: Any) -> Non ep = self.ep(state) self._restore_writes(state, ep) pins = [_norm_text(v) for v in self.owner.pinned.values() if str(v).strip()] - if not pins or not ep.writes: + if not pins: return back = self.readback(state, observation, task) if back is None or back.get("is_toast") or back.get("is_editable"): + ep.screen_on_record = False return saved = _norm_text(back.get("readback_text") or "") - if not saved or not all(p in saved for p in pins): + ep.screen_on_record = bool(saved) and all(p in saved for p in pins) + if not ep.screen_on_record or not ep.writes: return ep.identity_seen = True raw_obs = _get(observation, "raw_observation") @@ -1319,7 +1380,7 @@ def pre_done( is_toast=bool(back.get("is_toast")), completeness_auditor=self.completeness_auditor, ) - if self.has_duplicate_commits(state): + if self.has_duplicate_commits(state, task): self._release_unverified( state, commit_idx, diff --git a/tests/test_transducer_v3_runtime.py b/tests/test_transducer_v3_runtime.py index a8cbeea4a4..c38c6a9d9f 100644 --- a/tests/test_transducer_v3_runtime.py +++ b/tests/test_transducer_v3_runtime.py @@ -434,3 +434,82 @@ def test_identical_re_save_in_one_session_is_not_released(tmp_path): hints = " ".join(str(iv) for iv in state.intervention_log) assert "DUPLICATE_SAVE" in hints or "FORM_COMMIT_LATCHED" in hints assert not (isinstance(out, dict) and out.get("is_commit")) + + +def _item_run(tmp_path, pinned, header, task): + from openadapt.simplex_transducer import WriteAheadSagaLog + + agent = Mock() + agent.act.side_effect = [_FB_FILL, _FB_SAVE, _FB_EDIT] + [{"type": "done"}] * 5 + wrapped = SimplexTransducer( + agent, + wal=WriteAheadSagaLog(tmp_path / "wal.jsonl"), # one WAL for the whole batch + pinned=pinned, + config=SupervisorConfig(enable_obligation_compiler=True), + ) + filled = _fb_dom("CPT 29881; units 1", "2026-12-16") + reopened = _fb_dom("CPT 29881; units 1", "2026-12-16", reopened=True) + wrapped.act(_fb_obs(_fb_dom(), header), task) + wrapped.act(_fb_obs(filled, header), task) + for _ in range(6): + wrapped.act(_fb_obs(reopened, header), task) + if wrapped.last_receipt is not None: + break + return wrapped.last_receipt + + +def test_same_values_on_two_records_both_verify(tmp_path): + # The same note on two patients, one task item per patient, one batch WAL. + a = {"task_id": "item-a", **_FB_TASK} + b = { + "task_id": "item-b", + "instruction": _FB_TASK["instruction"].replace( + "Ada Quill, date of birth 1959-08-03", "Bo Reyes, date of birth 1970-02-11" + ), + } + ra = _item_run(tmp_path, _FB_PINNED, _HEADER, a) + rb = _item_run( + tmp_path, + {"patient": "Bo Reyes", "date_of_birth": "1970-02-11"}, + "Bo Reyes DOB: 1970-02-11", + b, + ) + assert ra is not None and ra.outcome == ReceiptOutcome.VERIFIED + assert rb is not None and rb.outcome == ReceiptOutcome.VERIFIED + + +def test_task_that_names_two_identical_entries_verifies(tmp_path): + from openadapt.simplex_transducer import WriteAheadSagaLog + + task = { + "instruction": ( + "For Ada Quill, date of birth 1959-08-03, add two entries, each with the " + 'comments exactly as: "CPT 29881; units 1" and the start date 2026-12-16. ' + 'First entry: "CPT 29881; units 1". Second entry: "CPT 29881; units 1".' + ) + } + agent = Mock() + agent.act.side_effect = [_FB_FILL, _FB_SAVE, _FB_FILL, _FB_SAVE, _FB_EDIT] + [ + {"type": "done"} + ] * 5 + wrapped = SimplexTransducer( + agent, + wal=WriteAheadSagaLog(tmp_path / "wal.jsonl"), + pinned=_FB_PINNED, + config=SupervisorConfig(enable_obligation_compiler=True), + ) + filled = _fb_dom("CPT 29881; units 1", "2026-12-16") + reopened = _fb_dom("CPT 29881; units 1", "2026-12-16", reopened=True) + released = [] + for dom in (_fb_dom(), filled, _fb_dom(), filled): + released.append(wrapped.act(_fb_obs(dom, _HEADER), task)) + assert sum(1 for x in released if isinstance(x, dict) and x.get("is_commit")) == 2 + for _ in range(6): + wrapped.act(_fb_obs(reopened, _HEADER), task) + if wrapped.last_receipt is not None: + break + state = wrapped.get_state("default-run", "default-task") + assert not any("DUPLICATE_SAVE" in str(iv) or "FORM_COMMIT_LATCHED" in str(iv) + for iv in state.intervention_log) # fmt: skip + assert wrapped.last_receipt is not None + assert wrapped.last_receipt.outcome == ReceiptOutcome.VERIFIED From 75f97fa870e759b6157f583574282540d32d3dc2 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 1 Dec 2026 05:08:25 -0500 Subject: [PATCH 3/4] fix(transducer): a save submits the fields on screen in its container, not the fields typed since the last click Review (Grok) found that any non-commit click cleared the set of fields a save submits, so a click inside the form (a date picker, the next field) dropped earlier fields from the save. A resumed duplicate then went through, and the typed-values gate could miss a dropped value. A draft field now belongs to a save when it is still on screen when the save is clicked and, when the read-back provider reports a container (frame or form), sits in the save control's container. Clicks no longer matter. A search box in another container is still left out. Tests cover a click inside the form before a crash and redo, typing A, clicking B and typing B, and a search box in another container. --- openadapt/simplex_transducer.py | 2 +- openadapt/transducer_fact_ledger.py | 2 +- openadapt/transducer_v3_runtime.py | 102 ++++++++++++++++++++-------- tests/test_transducer_v3_runtime.py | 61 +++++++++++++++++ 4 files changed, 135 insertions(+), 32 deletions(-) diff --git a/openadapt/simplex_transducer.py b/openadapt/simplex_transducer.py index fb5fdf0121..c3c50705f7 100644 --- a/openadapt/simplex_transducer.py +++ b/openadapt/simplex_transducer.py @@ -3826,7 +3826,7 @@ def _route_action_inner( action = self._v3.egress_gate(state, action, observation, task, history) if self._is_commit_boundary(action): - dup = self._v3.duplicate_of(state, task) + dup = self._v3.duplicate_of(state, task, action) if dup is not None: ep = self._v3.ep(state) if dup in ep.duplicate_warned: diff --git a/openadapt/transducer_fact_ledger.py b/openadapt/transducer_fact_ledger.py index 68dc82cd67..979049aebd 100644 --- a/openadapt/transducer_fact_ledger.py +++ b/openadapt/transducer_fact_ledger.py @@ -702,7 +702,7 @@ def latch_gate( if isinstance(raw, Mapping) and raw.get("allow_duplicate") is True: return action v3 = getattr(owner, "_v3", None) - if v3 is not None and v3.repeat_allowed(state, task): + if v3 is not None and v3.repeat_allowed(state, task, action): return action # the task names this content again: not a re-submit key = submit_control_key(action) text = " ".join([submit_text(action), *state.form_latch.typed()]) diff --git a/openadapt/transducer_v3_runtime.py b/openadapt/transducer_v3_runtime.py index e8929b152d..c3816edb58 100644 --- a/openadapt/transducer_v3_runtime.py +++ b/openadapt/transducer_v3_runtime.py @@ -231,7 +231,11 @@ class V3EpisodeState: typed_keys_since_commit: set[str] = field(default_factory=set) identity_seen: bool = False # Keys typed since the last non-commit click: the form a commit saves. - form_keys: set[str] = field(default_factory=set) + # The current screen's controls: selector -> (field key, container). The + # container (frame or form, when the read-back provider reports one) tells + # which fields a save button submits. + screen_map: dict[str, tuple[str, str]] = field(default_factory=dict) + draft_containers: dict[str, str] = field(default_factory=dict) writes_restored: bool = False screen_on_record: bool = False duplicate_warned: set[int] = field(default_factory=set) @@ -579,19 +583,20 @@ def shell_gate( def note_commit(self, state: EpisodeState, action: Any) -> None: """Count a routed commit as a workspace write or a GUI/remote commit.""" ep = self.ep(state) + form = self._form_of(ep, action) for key, value in ep.drafts.items(): ep.writes.append( SavedWrite( key, value, state.next_commit_index, - in_form=key in ep.form_keys, + in_form=key in form, on_record=ep.screen_on_record, ) ) ep.drafts.clear() + ep.draft_containers.clear() ep.typed_keys_since_commit.clear() - ep.form_keys.clear() raw = _raw(action) or {} remote = ( raw.get("wire_mutation") is True @@ -648,8 +653,6 @@ def after_step( if kind in _EDIT_ACTION_TYPES or raw.get("fs_write") is True: ep.mutated = True self._note_drafts(ep, observation, action) - if kind == "click" and not self.owner._is_commit_boundary(action): - ep.form_keys.clear() # a navigation click leaves the form if ep.obligations and kind in ("fill", "type", "input", "set_value"): text = _get(action, "text") or raw.get("value") or raw.get("text") or "" mark_drafted_from_action(ep.obligations, str(text)) @@ -984,21 +987,6 @@ def _abstain_egress( ) # -- field-bound read-back --------------------------------------------- - @staticmethod - def _field_keys(observation: Any) -> dict[str, str]: - """selector -> field key (tag and visible label) for the screen's controls.""" - raw_obs = _get(observation, "raw_observation") - dom = raw_obs.get("dom_elements") if isinstance(raw_obs, Mapping) else None - keys: dict[str, str] = {} - for el in dom or []: - if not isinstance(el, Mapping): - continue - selector = str(el.get("selector") or "") - label = _norm_text(el.get("text") or el.get("name") or "") - if selector and label: - keys[selector] = f"{str(el.get('tag') or '').lower()}|{label}" - return keys - def _note_drafts(self, ep: V3EpisodeState, observation: Any, action: Any) -> None: """Remember which field each typed or selected value went into.""" kind = _type(action) @@ -1030,14 +1018,62 @@ def _note_drafts(self, ep: V3EpisodeState, observation: Any, action: Any) -> Non pairs.append((write.get("selector"), write.get("value"))) if not pairs: return - keys = self._field_keys(observation) + smap = self._screen_map(observation) for target, value in pairs: - key = keys.get(str(target or "")) - if key is None or value is None: + hit = smap.get(str(target or "")) + if hit is None or value is None: continue + key, container = hit ep.drafts[key] = str(value) + ep.draft_containers[key] = container ep.typed_keys_since_commit.add(key) - ep.form_keys.add(key) + + @staticmethod + def _screen_map(observation: Any) -> dict[str, tuple[str, str]]: + """selector -> (field key, container) for the screen's controls.""" + raw_obs = _get(observation, "raw_observation") + dom = raw_obs.get("dom_elements") if isinstance(raw_obs, Mapping) else None + out: dict[str, tuple[str, str]] = {} + for el in dom or []: + if not isinstance(el, Mapping): + continue + selector = str(el.get("selector") or "") + label = _norm_text(el.get("text") or el.get("name") or "") + if selector and label: + container = str( + el.get("container") or el.get("form") or el.get("frame") or "" + ) + out[selector] = ( + f"{str(el.get('tag') or '').lower()}|{label}", + container, + ) + return out + + def _form_of(self, ep: V3EpisodeState, action: Any) -> set[str]: + """Draft fields that a save submits: still on screen when the save is + clicked and, when the provider reports containers, in the save + control's container. A search box in another frame or form is not part + of the save; a click inside the form (a date picker, the next field) + does not take a field out of it.""" + raw = _raw(action) or {} + target = str( + _get(action, "target_name") + or raw.get("target_name") + or raw.get("selector") + or (raw.get("parsed_json") or {}).get("target_name") + or "" + ) + target_container = ep.screen_map.get(target, ("", ""))[1] + on_screen = {key: cont for key, cont in ep.screen_map.values()} + form: set[str] = set() + for key in ep.drafts: + if key not in on_screen: + continue + cont = ep.draft_containers.get(key, "") or on_screen[key] + if target_container and cont and cont != target_container: + continue + form.add(key) + return form # -- crash resume ------------------------------------------------------- def field_writes_for( @@ -1124,11 +1160,12 @@ def _reconcile_restored( fast_forward_obs=observation, ) - def _current_form(self, ep: V3EpisodeState) -> dict[str, str]: + def _current_form(self, ep: V3EpisodeState, action: Any) -> dict[str, str]: + form = self._form_of(ep, action) return { k: _norm_text(v) for k, v in ep.drafts.items() - if k in ep.form_keys and str(v).strip() + if k in form and str(v).strip() } def _times_task_names( @@ -1141,16 +1178,20 @@ def _times_task_names( return 1 return max(1, _norm_text(self._instruction(state, task)).count(longest)) - def repeat_allowed(self, state: EpisodeState, task: Any) -> bool: + def repeat_allowed( + self, state: EpisodeState, task: Any, action: Any = None + ) -> bool: """The form about to be saved repeats earlier content the task asks for again.""" ep = self.ep(state) - current = self._current_form(ep) + current = self._current_form(ep, action) if not current: return False same = sum(1 for v in self._form_groups(ep).values() if v == current) return 0 < same < self._times_task_names(state, task, current) - def duplicate_of(self, state: EpisodeState, task: Any = None) -> int | None: + def duplicate_of( + self, state: EpisodeState, task: Any = None, action: Any = None + ) -> int | None: """The earlier commit, on the same pinned record, whose form saved exactly the values about to be saved, beyond what the task asks for. @@ -1166,7 +1207,7 @@ def duplicate_of(self, state: EpisodeState, task: Any = None) -> int | None: return None if not ep.screen_on_record: return None - current = self._current_form(ep) + current = self._current_form(ep, action) if not current: return None same = [ @@ -1202,6 +1243,7 @@ def observe_saved(self, state: EpisodeState, observation: Any, task: Any) -> Non agent has not typed into that field since the save. """ ep = self.ep(state) + ep.screen_map = self._screen_map(observation) self._restore_writes(state, ep) pins = [_norm_text(v) for v in self.owner.pinned.values() if str(v).strip()] if not pins: diff --git a/tests/test_transducer_v3_runtime.py b/tests/test_transducer_v3_runtime.py index c38c6a9d9f..f79f1db0c6 100644 --- a/tests/test_transducer_v3_runtime.py +++ b/tests/test_transducer_v3_runtime.py @@ -513,3 +513,64 @@ def test_task_that_names_two_identical_entries_verifies(tmp_path): for iv in state.intervention_log) # fmt: skip assert wrapped.last_receipt is not None assert wrapped.last_receipt.outcome == ReceiptOutcome.VERIFIED + + +_FB_CLICK_IN_FORM = { + "type": "click", + "target_name": "[f.s]", +} # e.g. opens a date picker + + +def test_click_inside_the_form_keeps_fields_in_the_save_after_a_restart(tmp_path): + # fill, a non-save click on a form field, save; crash; the fresh session does the same + first, _ = _crash_wrap(tmp_path, _FB_FILL, _FB_CLICK_IN_FORM, _FB_SAVE) + filled = _fb_dom("CPT 29881; units 1", "2026-12-16") + for dom in (_fb_dom(), filled, filled): + first.act(_fb_obs(dom, _HEADER), _FB_TASK) + state = first.get_state("default-run", "default-task") + assert {w.value for w in first._v3.ep(state).writes if w.in_form} == { + "CPT 29881; units 1", + "2026-12-16", + } + again, _ = _crash_wrap( + tmp_path, _FB_FILL, _FB_CLICK_IN_FORM, _FB_SAVE, _FB_SAVE, _FB_SAVE + ) + for dom in (_fb_dom(), filled, filled): + out = again.act(_fb_obs(dom, _HEADER), _FB_TASK) + state = again.get_state("default-run", "default-task") + assert any("DUPLICATE_SAVE" in str(iv) for iv in state.intervention_log) + assert not (isinstance(out, dict) and out.get("is_commit")) + + +def test_type_a_click_b_type_b_keeps_both_fields(tmp_path): + type_a = {"type": "type", "target_name": "[f.c]", "text": "CPT 29881; units 1"} + type_b = {"type": "type", "target_name": "[f.s]", "text": "2026-12-16"} + wrapped, _ = _crash_wrap(tmp_path, type_a, _FB_CLICK_IN_FORM, type_b, _FB_SAVE) + for dom in ( + _fb_dom(), + _fb_dom("CPT 29881; units 1"), + _fb_dom("CPT 29881; units 1"), + _fb_dom("CPT 29881; units 1", "2026-12-16"), + ): + wrapped.act(_fb_obs(dom, _HEADER), _FB_TASK) + state = wrapped.get_state("default-run", "default-task") + assert {w.value for w in wrapped._v3.ep(state).writes if w.in_form} == { + "CPT 29881; units 1", + "2026-12-16", + } + + +def test_search_box_in_another_container_is_not_part_of_the_save(tmp_path): + search = {"type": "type", "target_name": "[m.q]", "text": "Quill"} + wrapped, _ = _crash_wrap(tmp_path, search, _FB_FILL, _FB_SAVE) + + def dom(c="", s=""): + rows = [dict(e, container="form") for e in _fb_dom(c, s)] + return rows + [{"selector": "[m.q]", "tag": "input", "text": "Search", + "value": "Quill", "container": "main"}] # fmt: skip + + for d in (dom(), dom(), dom("CPT 29881; units 1", "2026-12-16")): + wrapped.act(_fb_obs(d, _HEADER), _FB_TASK) + state = wrapped.get_state("default-run", "default-task") + in_form = {w.value for w in wrapped._v3.ep(state).writes if w.in_form} + assert in_form == {"CPT 29881; units 1", "2026-12-16"} From 1cc4cbf7761f91be65671d4f9f48eaa6568ae298 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 1 Dec 2026 05:48:40 -0500 Subject: [PATCH 4/4] fix(transducer): without a pinned record, a resumed save that repeats a pre-crash commit goes to a person With no pinned identity the duplicate refusal could not be scoped to a record and refused nothing, so a crash-then-redo duplicate could get through. When a session resumed from the WAL is about to save exactly the values of a commit from before the restart and no record identity is pinned, wrap now abstains (RESUME_DUPLICATE_UNCERTAIN) and hands the item to a person instead of saving. --- openadapt/simplex_transducer.py | 13 +++++++++++++ openadapt/transducer_v3_runtime.py | 25 +++++++++++++++++++++++++ tests/test_transducer_v3_runtime.py | 24 ++++++++++++++++++++++++ 3 files changed, 62 insertions(+) diff --git a/openadapt/simplex_transducer.py b/openadapt/simplex_transducer.py index c3c50705f7..dbc3b4f768 100644 --- a/openadapt/simplex_transducer.py +++ b/openadapt/simplex_transducer.py @@ -3826,6 +3826,19 @@ def _route_action_inner( action = self._v3.egress_gate(state, action, observation, task, history) if self._is_commit_boundary(action): + unscoped = self._v3.unscoped_resume_duplicate(state, task, action) + if unscoped is not None: + return self._abstain_action( + state, + trap_code="RESUME_DUPLICATE_UNCERTAIN", + reason=( + f"These values were saved before the restart (commit " + f"#{unscoped}) and no record identity is pinned, so it " + "cannot be told whether saving again would duplicate the " + "record. Handing the item to a person instead of saving." + ), + commit_index=unscoped, + ) dup = self._v3.duplicate_of(state, task, action) if dup is not None: ep = self._v3.ep(state) diff --git a/openadapt/transducer_v3_runtime.py b/openadapt/transducer_v3_runtime.py index c3816edb58..bb4f08b059 100644 --- a/openadapt/transducer_v3_runtime.py +++ b/openadapt/transducer_v3_runtime.py @@ -1219,6 +1219,31 @@ def duplicate_of( return None return same[0] + def unscoped_resume_duplicate( + self, state: EpisodeState, task: Any = None, action: Any = None + ) -> int | None: + """Without a pinned record identity, a save after a restart whose values + equal a commit from before the restart cannot be scoped to a record: it + may duplicate that commit. Return that commit so the item goes to a + person instead of being saved.""" + ep = self.ep(state) + if [v for v in self.owner.pinned.values() if str(v).strip()]: + return None + if not any(w.restored for w in ep.writes): + return None + current = self._current_form(ep, action) + if not current: + return None + restored = { + idx: values + for (idx, was_restored), values in self._form_groups(ep).items() + if was_restored + } + for idx, values in restored.items(): + if values == current: + return idx + return None + def has_duplicate_commits(self, state: EpisodeState, task: Any = None) -> bool: """More commits on the pinned record carried identical values than the task names.""" ep = self.ep(state) diff --git a/tests/test_transducer_v3_runtime.py b/tests/test_transducer_v3_runtime.py index f79f1db0c6..29efea0da8 100644 --- a/tests/test_transducer_v3_runtime.py +++ b/tests/test_transducer_v3_runtime.py @@ -574,3 +574,27 @@ def dom(c="", s=""): state = wrapped.get_state("default-run", "default-task") in_form = {w.value for w in wrapped._v3.ep(state).writes if w.in_form} assert in_form == {"CPT 29881; units 1", "2026-12-16"} + + +def test_unpinned_resumed_save_with_pre_crash_values_goes_to_a_person(tmp_path): + from openadapt.simplex_transducer import WriteAheadSagaLog + + def unpinned(*actions): + agent = Mock() + agent.act.side_effect = list(actions) + [{"type": "done"}] * 6 + return SimplexTransducer( + agent, + wal=WriteAheadSagaLog(tmp_path / "wal.jsonl"), + config=SupervisorConfig(enable_obligation_compiler=True), + ) + + filled = _fb_dom("CPT 29881; units 1", "2026-12-16") + first = unpinned(_FB_FILL, _FB_SAVE) + first.act(_fb_obs(_fb_dom(), _HEADER), _FB_TASK) + first.act(_fb_obs(filled, _HEADER), _FB_TASK) + # crash; the fresh session repeats the item with no record identity to scope to + again = unpinned(_FB_FILL, _FB_SAVE) + again.act(_fb_obs(_fb_dom(), _HEADER), _FB_TASK) + out = again.act(_fb_obs(filled, _HEADER), _FB_TASK) + assert getattr(out, "is_abstained", False) + assert out.raw_action["trap_code"] == "RESUME_DUPLICATE_UNCERTAIN"