From f0b77e0fac542be61550b28f2af88c4fee420f7b Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:08:52 -0500 Subject: [PATCH 1/4] refactor(flow): move the replayer's settling concern to a mixin, unchanged --- packages/flow/docs/design/DECOMPOSITION.md | 2 +- .../openadapt_flow/runtime/replay/settling.py | 666 ++++++++++++++++++ .../flow/openadapt_flow/runtime/replayer.py | 550 +-------------- 3 files changed, 674 insertions(+), 544 deletions(-) create mode 100644 packages/flow/openadapt_flow/runtime/replay/settling.py diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 2baa1c3f58..32028d90ec 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -605,7 +605,7 @@ PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwrigh | File | Line budget | |---|---:| -| `packages/flow/openadapt_flow/runtime/replayer.py` | 19229 | +| `packages/flow/openadapt_flow/runtime/replayer.py` | 18693 | | `packages/flow/openadapt_flow/__main__.py` | 14331 | | `packages/flow/openadapt_flow/qualification.py` | 5963 | | `packages/flow/openadapt_flow/ir.py` | 6830 | diff --git a/packages/flow/openadapt_flow/runtime/replay/settling.py b/packages/flow/openadapt_flow/runtime/replay/settling.py new file mode 100644 index 0000000000..27ae5cb7c2 --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/replay/settling.py @@ -0,0 +1,666 @@ +# mypy: disable-error-code="empty-body" +"""Moved replayer code. + +Moved verbatim from ``openadapt_flow.runtime.replayer.Replayer`` by +scripts/extract_mixin.py (docs/design/DECOMPOSITION.md, section 4.1). +``_SettlingAndInterstitialsHost`` declares, for mypy only, what this code reads from the +Replayer it is mixed into. +""" + +from __future__ import annotations + +import hashlib +from contextlib import ExitStack +from datetime import datetime, timezone +from typing import TYPE_CHECKING, Any, Literal, Optional # noqa: F401 + +from openadapt_flow.backend import FreshActuationRequired, StructuralResolutionRefused +from openadapt_flow.interruptions import ( + LabelChangedDuringClick, + class_texts, + dismiss_label, + whole_interruption_error, +) +from openadapt_flow.ir import ( + ActionDeliveryUncertainty, + Interstitial, + InterstitialActionResult, + Resolution, +) +from openadapt_flow.runtime.effect_watch import EffectWatchReport, watch_effects +from openadapt_flow.runtime.replay._shared import _frame_viewport +from openadapt_flow.runtime.resolver import resolve +from openadapt_flow.runtime.step_timing import timed_span + +if TYPE_CHECKING: + from pathlib import Path + from typing import Callable, Mapping + + from openadapt_flow.backend import Backend + from openadapt_flow.ir import ( + Predicate, + Step, + StepResult, + StructuralHandle, + StructuralLocator, + Workflow, + ) + from openadapt_flow.runtime.authorization import RuntimeParamScalar + from openadapt_flow.runtime.effects import EffectVerifier + from openadapt_flow.runtime.replay._shared import _DeliveryResultT + + +class _SettlingAndInterstitialsHost: + _active_delivery_acknowledgers: tuple[Any, ...] + _asset_bytes: Any + + @staticmethod + def _canonical_interstitial_snapshot( + declarations: Any, + ) -> tuple[tuple[Interstitial, ...], tuple[str, ...]]: ... + def _deliver_backend_call( + self, result: StepResult, call: Callable[[], _DeliveryResultT] + ) -> _DeliveryResultT: ... + def _deliver_guarded_dismissal( + self, + result: StepResult, + event: InterstitialActionResult, + locator: StructuralLocator, + handle: Optional[StructuralHandle], + native_act: Callable[..., Any], + ) -> None: ... + def _delivery_authorization_refusal( + self, + workflow: Workflow, + params: Mapping[str, RuntimeParamScalar], + step: Step, + result: StepResult, + *, + interstitial: bool = False, + api_delivery: bool = False, + ) -> Optional[str]: ... + @staticmethod + def _describe_predicate(pred: Predicate) -> str: ... + + _durable_continuation_guard: Optional[Any] + _governed_asset_mutation: Optional[str] + + def _interruption_control_error( + self, it: Interstitial, resolution: Optional[Resolution] + ) -> Optional[str]: ... + + _interstitials: Any + + def _predicate_holds( + self, + pred: Predicate, + frame_png: bytes, + bundle_dir: Path, + params: Mapping[str, RuntimeParamScalar], + *, + workflow: Optional[Workflow] = None, + ) -> bool: ... + + _require_qualification_environment_current: Any + _runtime_interstitial_snapshot: Any + _runtime_interstitial_snapshot_error: Optional[str] + _runtime_interstitial_source: Any + _settle_seed: Optional[tuple[Any, int]] + _workflow_interstitial_snapshot: tuple[str, ...] + _workflow_interstitial_snapshot_error: Optional[str] + _workflow_interstitials: tuple[Interstitial, ...] + backend: Backend + effect_verifier: Optional[EffectVerifier] + poll_interval_s: float + settle_readiness_timeout_s: float + use_structural: bool + vision: Any + + +if TYPE_CHECKING: + _Base = _SettlingAndInterstitialsHost +else: + _Base = object + + +class SettlingAndInterstitials(_Base): + """Moved replayer code.""" + + @timed_span("settle") + def _settle_seeded(self) -> bytes: + """``vision.wait_settled`` that can extend the last settled run. + + Same contract as ``vision.wait_settled``: a fresh frame is always + captured and returned, and it counts as settled only after a run of + identical frames polled at the normal interval. When the previous + settle on this backend ended settled and no input was delivered since + (every input crosses ``_deliver_backend_call``, which bumps the + epoch), an identical fresh frame extends that already-observed run + instead of starting a new one, saving one poll interval. A changed + frame starts over exactly as before. + """ + + seed_entry = getattr(self, "_settle_seed", None) + self._settle_seed = None + epoch = getattr(self, "_actuation_epoch", 0) + seeded = getattr(self.vision, "wait_settled_seeded", None) + seed_type = getattr(self.vision, "SettleSeed", None) + if seeded is None or seed_type is None: + return self.vision.wait_settled(self.backend) + seed = None + if seed_entry is not None and seed_entry[1] == epoch: + seed = seed_entry[0] + result = seeded(self.backend, seed) + if result.settled and result.phash: + seed_kwargs: dict[str, Any] = {} + if getattr(result, "mode", "pixel") == "page": + seed_kwargs["png"] = result.png + self._settle_seed = ( + seed_type( + phash=result.phash, + stable_frames=result.stable_frames, + captured_at=result.captured_at, + **seed_kwargs, + ), + epoch, + ) + return result.png + + def _interstitial_declaration_mutation( + self, workflow: Optional[Workflow] + ) -> Optional[str]: + """Return a refusal when caller-owned declarations changed mid-run.""" + + snapshot_error = ( + self._runtime_interstitial_snapshot_error + or self._workflow_interstitial_snapshot_error + ) + if snapshot_error is not None: + return f"{snapshot_error} - refusing to emit an action; run aborted." + try: + _runtime, runtime_snapshot = self._canonical_interstitial_snapshot( + self._runtime_interstitial_source + ) + workflow_snapshot: tuple[str, ...] = () + if workflow is not None: + _workflow, workflow_snapshot = self._canonical_interstitial_snapshot( + workflow.interstitials + ) + except Exception as exc: + return ( + "Interstitial declarations changed after admission and are no " + f"longer valid ({type(exc).__name__}) - refusing to emit an " + "action; run aborted." + ) + if ( + runtime_snapshot != self._runtime_interstitial_snapshot + or workflow_snapshot != self._workflow_interstitial_snapshot + ): + return ( + "Interstitial declarations changed after admission - refusing " + "to emit an action under a stale authorization; run aborted." + ) + return None + + def _resettle_after_interstitial( + self, before_png: bytes + ) -> tuple[bytes, Optional[str]]: + """Require a settled frame after every automatic dismissal. + + Interstitial handling is itself opt-in, so unlike the legacy entry-frame + behavior there is no backwards-compatibility reason to accept a + proceed-anyway settle timeout here. A transient blank frame could make a + ``TEXT_ABSENT`` clearance pass immediately before the overlay returned. + """ + fn = getattr(self.vision, "wait_settled_result", None) + if not callable(fn): + return before_png, ( + "The configured vision facade cannot verify that the screen " + "settled after an interstitial dismissal - refusing to act; " + "run aborted." + ) + try: + result = fn( + self.backend, + interval_s=self.poll_interval_s, + timeout_s=self.settle_readiness_timeout_s, + ) + frame = result.png + settled = result.settled + if not isinstance(frame, bytes) or not isinstance(settled, bool): + raise TypeError("invalid settle result") + except Exception as exc: + return before_png, ( + "The screen readiness check failed after dismissing an " + f"interstitial ({type(exc).__name__}) - refusing to act; run " + "aborted." + ) + if not settled: + return frame, ( + "The screen did not settle after the interstitial dismissal " + f"within {self.settle_readiness_timeout_s:.1f}s - refusing to " + "verify clearance on a mid-transition frame or act beneath it; " + "run aborted." + ) + return frame, None + + @timed_span("postcondition") + def _handle_interstitials( + self, + step: Step, + before_png: bytes, + bundle_dir: Path, + params: Mapping[str, RuntimeParamScalar], + result: StepResult, + audit_events: list[InterstitialActionResult], + workflow: Optional[Workflow], + ) -> tuple[bytes, Optional[str]]: + """Detect + handle KNOWN interstitials on the entry frame (model-free). + + A detected interstitial with an explicitly reversible, + non-consequential dismissal (``dismiss_key`` / ``dismiss_anchor``) gets + one audited action followed by its declared visual clearance check. A + delivery/clearance failure, persistent detection, or a detected + interstitial with NO dismissal HALTs the run GRACEFULLY naming it. Returns + ``(frame, None)`` when the screen is clear, else ``(frame, halt_reason)``. + + Unknown / undeclared overlays are NOT guessed at here: one that covers + the step's target still HALTs safely downstream (the anchor does not + resolve). This method only automates the RECURRING, declared ones so + they do not force a babysit-the-queue halt every time they appear. + """ + mutation_error = self._interstitial_declaration_mutation(workflow) + if mutation_error is not None: + return before_png, mutation_error + interstitials = [*self._workflow_interstitials, *self._interstitials] + if not interstitials: + return before_png, None + + # Revalidate serialized values at the point of use. Pydantic validates + # construction/load, but models are intentionally mutable; an in-memory + # edit or model_construct must not bypass affirmative detection, visual + # clearance, Escape-only, or reversible/non-consequential policy. + validated: list[Interstitial] = [] + for candidate in interstitials: + try: + validated.append( + Interstitial.model_validate(candidate.model_dump(mode="python")) + ) + except Exception as exc: + return before_png, ( + f"Interstitial '{candidate.name}' has an invalid automatic " + f"dismissal declaration ({type(exc).__name__}) - refusing " + "to emit an action; run aborted." + ) + interstitials = validated + + handled_indices: set[int] = set() + while True: + mutation_error = self._interstitial_declaration_mutation(workflow) + if mutation_error is not None: + return before_png, mutation_error + active_index = next( + ( + index + for index, candidate in enumerate(interstitials) + if self._predicate_holds( + candidate.detect, + before_png, + bundle_dir, + params, + workflow=workflow, + ) + ), + None, + ) + # Detection invokes vision and can therefore cross a callback + # boundary. Recheck the caller-owned declarations before trusting + # its result or preparing an action. + mutation_error = self._interstitial_declaration_mutation(workflow) + if mutation_error is not None: + return before_png, mutation_error + if active_index is None: + return before_png, None + it = interstitials[active_index] + if active_index in handled_indices: + return before_png, ( + f"Interstitial '{it.name}' reappeared after a verified " + "dismissal in the same step - refusing an automatic retry; " + "run aborted." + ) + if len(handled_indices) >= len(interstitials): + return before_png, ( + "The interstitial dismissal bound was exhausted before the " + "step entry state became clear - refusing further automatic " + "actions; run aborted." + ) + if it.dismiss_key is None and it.dismiss_anchor is None: + # A known BLOCKING interstitial with no safe auto-dismissal. + return before_png, ( + f"Known blocking interstitial '{it.name}' is on screen " + f"({self._describe_predicate(it.detect)}) and declares no " + "automatic dismissal - refusing to act beneath it; run " + "aborted (handle it, then re-run)." + ) + if ( + it.risk != "reversible" + or it.consequential is not False + or it.clearance is None + or (it.dismiss_key is not None and it.dismiss_key != "Escape") + ): + # Defensive runtime check in addition to Pydantic validation: + # model_construct/in-memory mutation must never turn this into + # an ungoverned consequential or unverifiable action. + return before_png, ( + f"Interstitial '{it.name}' does not declare an automatic " + "dismissal that is reversible, non-consequential, and " + "visually verifiable - refusing to emit an action; run " + "aborted." + ) + + resolution: Optional[Resolution] = None + action: Literal["key", "click"] + if it.dismiss_key is not None: + action = "key" + else: + assert it.dismiss_anchor is not None + structural_only = ( + not it.dismiss_anchor.template.strip() + and it.dismiss_anchor.structural is not None + ) + structural = ( + self.backend + if self.use_structural + and hasattr(self.backend, "locate_structural") + else None + ) + if structural_only and structural is None: + return before_png, ( + f"Interstitial '{it.name}' requires a structural-only " + "dismissal, but this backend cannot perform structural " + "resolution - refusing an OCR/geometry/coordinate " + "downgrade; run aborted." + ) + template_png = self._asset_bytes( + bundle_dir, + it.dismiss_anchor.template, + workflow=workflow, + ) + if self._governed_asset_mutation is not None: + return before_png, self._governed_asset_mutation + res = resolve( + it.dismiss_anchor, + before_png, + self.vision, + None, # NEVER ground a dismissal: stay model-free + it.name, + template_png=template_png, + viewport=_frame_viewport(before_png), + structural=structural, + ) + if res is None: + return before_png, ( + f"Interstitial '{it.name}' detected " + f"({self._describe_predicate(it.detect)}) but its dismiss " + "control did not resolve on screen - refusing to act; run " + "aborted." + ) + resolution, _region = res + if structural_only and resolution.rung != "structural": + return before_png, ( + f"Interstitial '{it.name}' structural dismissal did not " + "resolve uniquely - refusing an OCR/geometry/coordinate " + "downgrade; run aborted." + ) + action = "click" + + # Resolution can invoke vision or a structural backend. A callback + # must not be able to replace the declaration between authorization + # and the audit-before-delivery boundary. + mutation_error = self._interstitial_declaration_mutation(workflow) + if mutation_error is not None: + return before_png, mutation_error + if it.effect_watch: + # Classify the whole interruption, never its button word: a + # business question dressed as a session prompt halts here, + # before any input. + reader = getattr(self.backend, "interruption_text", None) + locator = ( + it.dismiss_anchor.structural + if it.dismiss_anchor is not None + else None + ) + try: + whole = ( + reader(locator, class_texts(it)) if callable(reader) else None + ) + except Exception: # noqa: BLE001 - unreadable means unproven + whole = None + class_error = whole_interruption_error(it, whole) + if class_error is None and it.dismiss_anchor is not None: + # The declared label proves nothing until the control + # that will be clicked is shown to carry it. + class_error = self._interruption_control_error(it, resolution) + if class_error is not None: + return before_png, ( + f"Interruption '{it.name}' was not cleared: {class_error} " + "- refusing to act beneath it; run aborted." + ) + # Append BEFORE delivery: a backend exception can never create an + # unreported key/click attempt. The event carries the exact admitted + # policy and expected visual outcome. + event = InterstitialActionResult( + control_label=dismiss_label(it), + interstitial=it.name, + action=action, + key=it.dismiss_key, + expected_clearance=it.clearance, + resolution=resolution, + before_frame_sha256=hashlib.sha256(before_png).hexdigest(), + ) + audit_events.append(event) + handled_indices.add(active_index) + if workflow is not None: + authorization_error = self._delivery_authorization_refusal( + workflow, params, step, result, interstitial=True + ) + if authorization_error is not None: + event.error = authorization_error + return before_png, authorization_error + elif self._durable_continuation_guard is not None: + # Normal replay always supplies ``workflow``. Keep the shared + # continuation fence fail-closed for direct helper/test use as + # well: every backend input edge must cross the same lease. + try: + self._durable_continuation_guard.before_delivery() + self._active_delivery_acknowledgers = ( + self._durable_continuation_guard, + ) + except Exception as exc: # noqa: BLE001 - fencing boundary + result.failure_category = "continuation_preempted" + result.safety_halt = True + event.error = ( + f"durable continuation was preempted before delivery: {exc}" + ) + return before_png, event.error + watch_stack = ExitStack() + watch: Optional[EffectWatchReport] = None + if it.effect_watch: + # An interruption class is cleared only when the dismissal is + # proven write-free: every watcher this run has is up around + # it, or nothing is sent. + watched: list[EffectWatchReport] = [] + + def _record_watch() -> None: + # Registered first, so it runs after the watchers close + # on every exit, a failed delivery included. + if watched: + event.effect_watchers = list(watched[0].watchers) + event.write_attempts = list(watched[0].attempts) + event.requests_seen = list(watched[0].requests) + + watch_stack.callback(_record_watch) + watch = watch_stack.enter_context( + watch_effects(self.backend, self.effect_verifier) + ) + watched.append(watch) + if watch.refusal is not None: + watch_stack.close() + event.error = f"dismissal not watched: {watch.refusal}" + return before_png, ( + f"Interruption '{it.name}' can't be cleared: " + f"{watch.refusal} - refusing to act beneath it; run " + "aborted." + ) + with watch_stack: + try: + if it.dismiss_key is not None: + self._require_qualification_environment_current() + self._deliver_backend_call( + result, + lambda: self.backend.press(it.dismiss_key or "Escape"), + ) + else: + assert resolution is not None + assert it.dismiss_anchor is not None + if resolution.rung == "structural": + native_act = getattr(self.backend, "act_structural", None) + structural_anchor = it.dismiss_anchor.structural + if ( + not callable(native_act) + or resolution.structural_handle is None + or structural_anchor is None + ): + raise StructuralResolutionRefused( + "structural dismissal cannot be delivered " + "natively without a stable element handle" + ) + if it.effect_watch: + # Again at the last no-input boundary: the + # label may have changed since the check. + control_error = self._interruption_control_error( + it, resolution + ) + if control_error is not None: + raise StructuralResolutionRefused(control_error) + self._require_qualification_environment_current() + self._deliver_guarded_dismissal( + result, + event, + structural_anchor, + resolution.structural_handle, + native_act, + ) + else: + self._require_qualification_environment_current() + self._deliver_backend_call( + result, + lambda: native_act( + structural_anchor, + resolution.structural_handle, + ), + ) + else: + self._require_qualification_environment_current() + self._deliver_backend_call( + result, + lambda: self.backend.click( + int(resolution.point[0]), int(resolution.point[1]) + ), + ) + event.delivered = True + except Exception as exc: + if isinstance(exc, LabelChangedDuringClick): + # The press reached the page's guard, which blocked + # it: delivery was attempted, and nothing beneath + # the label change is trusted. + event.delivered = True + event.label_violations = list(exc.violations) + result.safety_halt = True + if not isinstance( + exc, (FreshActuationRequired, StructuralResolutionRefused) + ): + target_fingerprint = None + if ( + resolution is not None + and resolution.structural_handle is not None + ): + target_fingerprint = ( + resolution.structural_handle.target_fingerprint + ) + result.delivery_uncertainty = ActionDeliveryUncertainty( + operation="interstitial_dismiss", + native=( + resolution is not None + and resolution.rung == "structural" + ), + target_fingerprint=target_fingerprint, + observed_at=datetime.now(timezone.utc).isoformat(), + cause_type=type(exc).__name__, + ) + event.error = ( + "dismissal delivery failed " + f"({type(exc).__name__}); outcome is unknown" + ) + if it.effect_watch and str(exc): + event.error += f": {exc}" + return before_png, ( + f"Interstitial '{it.name}' dismissal delivery failed " + f"({type(exc).__name__}" + + (f": {exc}" if it.effect_watch and str(exc) else "") + + ") - refusing to act beneath it; run aborted." + ) + + before_png, settle_error = self._resettle_after_interstitial(before_png) + if watch is not None: + if watch.attempts: + event.after_frame_sha256 = hashlib.sha256(before_png).hexdigest() + event.error = "the dismissal tried to write" + result.safety_halt = True + return before_png, ( + f"Interruption '{it.name}': its dismissal tried to " + f"write ({'; '.join(watch.attempts)}) - it is not a " + "benign interruption; refusing to continue; run aborted." + ) + event.after_frame_sha256 = hashlib.sha256(before_png).hexdigest() + if settle_error is not None: + event.error = settle_error + return before_png, settle_error + + clearance_holds = self._predicate_holds( + it.clearance, + before_png, + bundle_dir, + params, + workflow=workflow, + ) + if self._governed_asset_mutation is not None: + event.clearance_ok = False + event.error = self._governed_asset_mutation + return before_png, self._governed_asset_mutation + still_detected = False + if clearance_holds: + still_detected = self._predicate_holds( + it.detect, + before_png, + bundle_dir, + params, + workflow=workflow, + ) + if self._governed_asset_mutation is not None: + event.clearance_ok = False + event.error = self._governed_asset_mutation + return before_png, self._governed_asset_mutation + event.clearance_ok = clearance_holds and not still_detected + event.ok = event.delivered and event.clearance_ok + if not event.ok: + event.error = ( + "declared visual clearance did not hold" + if not clearance_holds + else "interstitial remained detected after dismissal" + ) + return before_png, ( + f"Interstitial '{it.name}' did not satisfy its declared " + "visual clearance after one dismissal - refusing a blind " + "retry or action beneath it; run aborted." + ) diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 4e7c5054da..0ec215ccbe 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -49,7 +49,7 @@ import time import uuid from collections import Counter -from contextlib import ExitStack +from contextlib import ExitStack # noqa: F401 from copy import deepcopy from dataclasses import dataclass # noqa: F401 from datetime import datetime, timezone @@ -101,7 +101,7 @@ normalize_signal_text, parameterize_identity_text, ) -from openadapt_flow.interruptions import ( +from openadapt_flow.interruptions import ( # noqa: F401 LabelChangedDuringClick, class_texts, dismiss_label, @@ -227,7 +227,7 @@ from openadapt_flow.runtime.durable.program_checkpoint import ( history_hash as _history_hash, ) -from openadapt_flow.runtime.effect_watch import EffectWatchReport, watch_effects +from openadapt_flow.runtime.effect_watch import EffectWatchReport, watch_effects # noqa: F401 from openadapt_flow.runtime.effects import ( Effect, EffectState, @@ -347,9 +347,12 @@ from openadapt_flow.runtime.replay.qualification_faults import ( QualificationFaultInjection, ) +from openadapt_flow.runtime.replay.settling import SettlingAndInterstitials -class Replayer(QualificationFaultInjection, AssetsHealingAndEvidence): +class Replayer( + QualificationFaultInjection, AssetsHealingAndEvidence, SettlingAndInterstitials +): """Replays a Workflow against a Backend using injected vision. Args: @@ -11495,46 +11498,6 @@ def _resolve_drag_end( ) return resolution, region, error - @timed_span("settle") - def _settle_seeded(self) -> bytes: - """``vision.wait_settled`` that can extend the last settled run. - - Same contract as ``vision.wait_settled``: a fresh frame is always - captured and returned, and it counts as settled only after a run of - identical frames polled at the normal interval. When the previous - settle on this backend ended settled and no input was delivered since - (every input crosses ``_deliver_backend_call``, which bumps the - epoch), an identical fresh frame extends that already-observed run - instead of starting a new one, saving one poll interval. A changed - frame starts over exactly as before. - """ - - seed_entry = getattr(self, "_settle_seed", None) - self._settle_seed = None - epoch = getattr(self, "_actuation_epoch", 0) - seeded = getattr(self.vision, "wait_settled_seeded", None) - seed_type = getattr(self.vision, "SettleSeed", None) - if seeded is None or seed_type is None: - return self.vision.wait_settled(self.backend) - seed = None - if seed_entry is not None and seed_entry[1] == epoch: - seed = seed_entry[0] - result = seeded(self.backend, seed) - if result.settled and result.phash: - seed_kwargs: dict[str, Any] = {} - if getattr(result, "mode", "pixel") == "page": - seed_kwargs["png"] = result.png - self._settle_seed = ( - seed_type( - phash=result.phash, - stable_frames=result.stable_frames, - captured_at=result.captured_at, - **seed_kwargs, - ), - epoch, - ) - return result.png - def _deliver_backend_call( self, result: StepResult, @@ -13935,42 +13898,6 @@ def _interruption_control_error( ) return live_control_error(it, self.backend, resolution.structural_handle) - def _interstitial_declaration_mutation( - self, workflow: Optional[Workflow] - ) -> Optional[str]: - """Return a refusal when caller-owned declarations changed mid-run.""" - - snapshot_error = ( - self._runtime_interstitial_snapshot_error - or self._workflow_interstitial_snapshot_error - ) - if snapshot_error is not None: - return f"{snapshot_error} - refusing to emit an action; run aborted." - try: - _runtime, runtime_snapshot = self._canonical_interstitial_snapshot( - self._runtime_interstitial_source - ) - workflow_snapshot: tuple[str, ...] = () - if workflow is not None: - _workflow, workflow_snapshot = self._canonical_interstitial_snapshot( - workflow.interstitials - ) - except Exception as exc: - return ( - "Interstitial declarations changed after admission and are no " - f"longer valid ({type(exc).__name__}) - refusing to emit an " - "action; run aborted." - ) - if ( - runtime_snapshot != self._runtime_interstitial_snapshot - or workflow_snapshot != self._workflow_interstitial_snapshot - ): - return ( - "Interstitial declarations changed after admission - refusing " - "to emit an action under a stale authorization; run aborted." - ) - return None - @timed_span("settle") def _wait_starting_state_settled( self, before_png: bytes @@ -14257,469 +14184,6 @@ def _require_locale_invariants_before_keyboard( return exc.reason return None - def _resettle_after_interstitial( - self, before_png: bytes - ) -> tuple[bytes, Optional[str]]: - """Require a settled frame after every automatic dismissal. - - Interstitial handling is itself opt-in, so unlike the legacy entry-frame - behavior there is no backwards-compatibility reason to accept a - proceed-anyway settle timeout here. A transient blank frame could make a - ``TEXT_ABSENT`` clearance pass immediately before the overlay returned. - """ - fn = getattr(self.vision, "wait_settled_result", None) - if not callable(fn): - return before_png, ( - "The configured vision facade cannot verify that the screen " - "settled after an interstitial dismissal - refusing to act; " - "run aborted." - ) - try: - result = fn( - self.backend, - interval_s=self.poll_interval_s, - timeout_s=self.settle_readiness_timeout_s, - ) - frame = result.png - settled = result.settled - if not isinstance(frame, bytes) or not isinstance(settled, bool): - raise TypeError("invalid settle result") - except Exception as exc: - return before_png, ( - "The screen readiness check failed after dismissing an " - f"interstitial ({type(exc).__name__}) - refusing to act; run " - "aborted." - ) - if not settled: - return frame, ( - "The screen did not settle after the interstitial dismissal " - f"within {self.settle_readiness_timeout_s:.1f}s - refusing to " - "verify clearance on a mid-transition frame or act beneath it; " - "run aborted." - ) - return frame, None - - @timed_span("postcondition") - def _handle_interstitials( - self, - step: Step, - before_png: bytes, - bundle_dir: Path, - params: Mapping[str, RuntimeParamScalar], - result: StepResult, - audit_events: list[InterstitialActionResult], - workflow: Optional[Workflow], - ) -> tuple[bytes, Optional[str]]: - """Detect + handle KNOWN interstitials on the entry frame (model-free). - - A detected interstitial with an explicitly reversible, - non-consequential dismissal (``dismiss_key`` / ``dismiss_anchor``) gets - one audited action followed by its declared visual clearance check. A - delivery/clearance failure, persistent detection, or a detected - interstitial with NO dismissal HALTs the run GRACEFULLY naming it. Returns - ``(frame, None)`` when the screen is clear, else ``(frame, halt_reason)``. - - Unknown / undeclared overlays are NOT guessed at here: one that covers - the step's target still HALTs safely downstream (the anchor does not - resolve). This method only automates the RECURRING, declared ones so - they do not force a babysit-the-queue halt every time they appear. - """ - mutation_error = self._interstitial_declaration_mutation(workflow) - if mutation_error is not None: - return before_png, mutation_error - interstitials = [*self._workflow_interstitials, *self._interstitials] - if not interstitials: - return before_png, None - - # Revalidate serialized values at the point of use. Pydantic validates - # construction/load, but models are intentionally mutable; an in-memory - # edit or model_construct must not bypass affirmative detection, visual - # clearance, Escape-only, or reversible/non-consequential policy. - validated: list[Interstitial] = [] - for candidate in interstitials: - try: - validated.append( - Interstitial.model_validate(candidate.model_dump(mode="python")) - ) - except Exception as exc: - return before_png, ( - f"Interstitial '{candidate.name}' has an invalid automatic " - f"dismissal declaration ({type(exc).__name__}) - refusing " - "to emit an action; run aborted." - ) - interstitials = validated - - handled_indices: set[int] = set() - while True: - mutation_error = self._interstitial_declaration_mutation(workflow) - if mutation_error is not None: - return before_png, mutation_error - active_index = next( - ( - index - for index, candidate in enumerate(interstitials) - if self._predicate_holds( - candidate.detect, - before_png, - bundle_dir, - params, - workflow=workflow, - ) - ), - None, - ) - # Detection invokes vision and can therefore cross a callback - # boundary. Recheck the caller-owned declarations before trusting - # its result or preparing an action. - mutation_error = self._interstitial_declaration_mutation(workflow) - if mutation_error is not None: - return before_png, mutation_error - if active_index is None: - return before_png, None - it = interstitials[active_index] - if active_index in handled_indices: - return before_png, ( - f"Interstitial '{it.name}' reappeared after a verified " - "dismissal in the same step - refusing an automatic retry; " - "run aborted." - ) - if len(handled_indices) >= len(interstitials): - return before_png, ( - "The interstitial dismissal bound was exhausted before the " - "step entry state became clear - refusing further automatic " - "actions; run aborted." - ) - if it.dismiss_key is None and it.dismiss_anchor is None: - # A known BLOCKING interstitial with no safe auto-dismissal. - return before_png, ( - f"Known blocking interstitial '{it.name}' is on screen " - f"({self._describe_predicate(it.detect)}) and declares no " - "automatic dismissal - refusing to act beneath it; run " - "aborted (handle it, then re-run)." - ) - if ( - it.risk != "reversible" - or it.consequential is not False - or it.clearance is None - or (it.dismiss_key is not None and it.dismiss_key != "Escape") - ): - # Defensive runtime check in addition to Pydantic validation: - # model_construct/in-memory mutation must never turn this into - # an ungoverned consequential or unverifiable action. - return before_png, ( - f"Interstitial '{it.name}' does not declare an automatic " - "dismissal that is reversible, non-consequential, and " - "visually verifiable - refusing to emit an action; run " - "aborted." - ) - - resolution: Optional[Resolution] = None - action: Literal["key", "click"] - if it.dismiss_key is not None: - action = "key" - else: - assert it.dismiss_anchor is not None - structural_only = ( - not it.dismiss_anchor.template.strip() - and it.dismiss_anchor.structural is not None - ) - structural = ( - self.backend - if self.use_structural - and hasattr(self.backend, "locate_structural") - else None - ) - if structural_only and structural is None: - return before_png, ( - f"Interstitial '{it.name}' requires a structural-only " - "dismissal, but this backend cannot perform structural " - "resolution - refusing an OCR/geometry/coordinate " - "downgrade; run aborted." - ) - template_png = self._asset_bytes( - bundle_dir, - it.dismiss_anchor.template, - workflow=workflow, - ) - if self._governed_asset_mutation is not None: - return before_png, self._governed_asset_mutation - res = resolve( - it.dismiss_anchor, - before_png, - self.vision, - None, # NEVER ground a dismissal: stay model-free - it.name, - template_png=template_png, - viewport=_frame_viewport(before_png), - structural=structural, - ) - if res is None: - return before_png, ( - f"Interstitial '{it.name}' detected " - f"({self._describe_predicate(it.detect)}) but its dismiss " - "control did not resolve on screen - refusing to act; run " - "aborted." - ) - resolution, _region = res - if structural_only and resolution.rung != "structural": - return before_png, ( - f"Interstitial '{it.name}' structural dismissal did not " - "resolve uniquely - refusing an OCR/geometry/coordinate " - "downgrade; run aborted." - ) - action = "click" - - # Resolution can invoke vision or a structural backend. A callback - # must not be able to replace the declaration between authorization - # and the audit-before-delivery boundary. - mutation_error = self._interstitial_declaration_mutation(workflow) - if mutation_error is not None: - return before_png, mutation_error - if it.effect_watch: - # Classify the whole interruption, never its button word: a - # business question dressed as a session prompt halts here, - # before any input. - reader = getattr(self.backend, "interruption_text", None) - locator = ( - it.dismiss_anchor.structural - if it.dismiss_anchor is not None - else None - ) - try: - whole = ( - reader(locator, class_texts(it)) if callable(reader) else None - ) - except Exception: # noqa: BLE001 - unreadable means unproven - whole = None - class_error = whole_interruption_error(it, whole) - if class_error is None and it.dismiss_anchor is not None: - # The declared label proves nothing until the control - # that will be clicked is shown to carry it. - class_error = self._interruption_control_error(it, resolution) - if class_error is not None: - return before_png, ( - f"Interruption '{it.name}' was not cleared: {class_error} " - "- refusing to act beneath it; run aborted." - ) - # Append BEFORE delivery: a backend exception can never create an - # unreported key/click attempt. The event carries the exact admitted - # policy and expected visual outcome. - event = InterstitialActionResult( - control_label=dismiss_label(it), - interstitial=it.name, - action=action, - key=it.dismiss_key, - expected_clearance=it.clearance, - resolution=resolution, - before_frame_sha256=hashlib.sha256(before_png).hexdigest(), - ) - audit_events.append(event) - handled_indices.add(active_index) - if workflow is not None: - authorization_error = self._delivery_authorization_refusal( - workflow, params, step, result, interstitial=True - ) - if authorization_error is not None: - event.error = authorization_error - return before_png, authorization_error - elif self._durable_continuation_guard is not None: - # Normal replay always supplies ``workflow``. Keep the shared - # continuation fence fail-closed for direct helper/test use as - # well: every backend input edge must cross the same lease. - try: - self._durable_continuation_guard.before_delivery() - self._active_delivery_acknowledgers = ( - self._durable_continuation_guard, - ) - except Exception as exc: # noqa: BLE001 - fencing boundary - result.failure_category = "continuation_preempted" - result.safety_halt = True - event.error = ( - f"durable continuation was preempted before delivery: {exc}" - ) - return before_png, event.error - watch_stack = ExitStack() - watch: Optional[EffectWatchReport] = None - if it.effect_watch: - # An interruption class is cleared only when the dismissal is - # proven write-free: every watcher this run has is up around - # it, or nothing is sent. - watched: list[EffectWatchReport] = [] - - def _record_watch() -> None: - # Registered first, so it runs after the watchers close - # on every exit, a failed delivery included. - if watched: - event.effect_watchers = list(watched[0].watchers) - event.write_attempts = list(watched[0].attempts) - event.requests_seen = list(watched[0].requests) - - watch_stack.callback(_record_watch) - watch = watch_stack.enter_context( - watch_effects(self.backend, self.effect_verifier) - ) - watched.append(watch) - if watch.refusal is not None: - watch_stack.close() - event.error = f"dismissal not watched: {watch.refusal}" - return before_png, ( - f"Interruption '{it.name}' can't be cleared: " - f"{watch.refusal} - refusing to act beneath it; run " - "aborted." - ) - with watch_stack: - try: - if it.dismiss_key is not None: - self._require_qualification_environment_current() - self._deliver_backend_call( - result, - lambda: self.backend.press(it.dismiss_key or "Escape"), - ) - else: - assert resolution is not None - assert it.dismiss_anchor is not None - if resolution.rung == "structural": - native_act = getattr(self.backend, "act_structural", None) - structural_anchor = it.dismiss_anchor.structural - if ( - not callable(native_act) - or resolution.structural_handle is None - or structural_anchor is None - ): - raise StructuralResolutionRefused( - "structural dismissal cannot be delivered " - "natively without a stable element handle" - ) - if it.effect_watch: - # Again at the last no-input boundary: the - # label may have changed since the check. - control_error = self._interruption_control_error( - it, resolution - ) - if control_error is not None: - raise StructuralResolutionRefused(control_error) - self._require_qualification_environment_current() - self._deliver_guarded_dismissal( - result, - event, - structural_anchor, - resolution.structural_handle, - native_act, - ) - else: - self._require_qualification_environment_current() - self._deliver_backend_call( - result, - lambda: native_act( - structural_anchor, - resolution.structural_handle, - ), - ) - else: - self._require_qualification_environment_current() - self._deliver_backend_call( - result, - lambda: self.backend.click( - int(resolution.point[0]), int(resolution.point[1]) - ), - ) - event.delivered = True - except Exception as exc: - if isinstance(exc, LabelChangedDuringClick): - # The press reached the page's guard, which blocked - # it: delivery was attempted, and nothing beneath - # the label change is trusted. - event.delivered = True - event.label_violations = list(exc.violations) - result.safety_halt = True - if not isinstance( - exc, (FreshActuationRequired, StructuralResolutionRefused) - ): - target_fingerprint = None - if ( - resolution is not None - and resolution.structural_handle is not None - ): - target_fingerprint = ( - resolution.structural_handle.target_fingerprint - ) - result.delivery_uncertainty = ActionDeliveryUncertainty( - operation="interstitial_dismiss", - native=( - resolution is not None - and resolution.rung == "structural" - ), - target_fingerprint=target_fingerprint, - observed_at=datetime.now(timezone.utc).isoformat(), - cause_type=type(exc).__name__, - ) - event.error = ( - "dismissal delivery failed " - f"({type(exc).__name__}); outcome is unknown" - ) - if it.effect_watch and str(exc): - event.error += f": {exc}" - return before_png, ( - f"Interstitial '{it.name}' dismissal delivery failed " - f"({type(exc).__name__}" - + (f": {exc}" if it.effect_watch and str(exc) else "") - + ") - refusing to act beneath it; run aborted." - ) - - before_png, settle_error = self._resettle_after_interstitial(before_png) - if watch is not None: - if watch.attempts: - event.after_frame_sha256 = hashlib.sha256(before_png).hexdigest() - event.error = "the dismissal tried to write" - result.safety_halt = True - return before_png, ( - f"Interruption '{it.name}': its dismissal tried to " - f"write ({'; '.join(watch.attempts)}) - it is not a " - "benign interruption; refusing to continue; run aborted." - ) - event.after_frame_sha256 = hashlib.sha256(before_png).hexdigest() - if settle_error is not None: - event.error = settle_error - return before_png, settle_error - - clearance_holds = self._predicate_holds( - it.clearance, - before_png, - bundle_dir, - params, - workflow=workflow, - ) - if self._governed_asset_mutation is not None: - event.clearance_ok = False - event.error = self._governed_asset_mutation - return before_png, self._governed_asset_mutation - still_detected = False - if clearance_holds: - still_detected = self._predicate_holds( - it.detect, - before_png, - bundle_dir, - params, - workflow=workflow, - ) - if self._governed_asset_mutation is not None: - event.clearance_ok = False - event.error = self._governed_asset_mutation - return before_png, self._governed_asset_mutation - event.clearance_ok = clearance_holds and not still_detected - event.ok = event.delivered and event.clearance_ok - if not event.ok: - event.error = ( - "declared visual clearance did not hold" - if not clearance_holds - else "interstitial remained detected after dismissal" - ) - return before_png, ( - f"Interstitial '{it.name}' did not satisfy its declared " - "visual clearance after one dismissal - refusing a blind " - "retry or action beneath it; run aborted." - ) - # -- Workflow-program IR gates: guard + wait_until -------------------------- def _apply_step_gates( From 6c809f549e71e627adab5621cf4c38bbb5ce1a7c Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:09:22 -0500 Subject: [PATCH 2/4] refactor(flow): move the replayer's effects concern to a mixin, unchanged --- packages/flow/docs/design/DECOMPOSITION.md | 2 +- .../openadapt_flow/runtime/replay/effects.py | 912 ++++++++++++++++++ .../flow/openadapt_flow/runtime/replayer.py | 845 +--------------- 3 files changed, 925 insertions(+), 834 deletions(-) create mode 100644 packages/flow/openadapt_flow/runtime/replay/effects.py diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 32028d90ec..4dfe67a693 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -605,7 +605,7 @@ PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwrigh | File | Line budget | |---|---:| -| `packages/flow/openadapt_flow/runtime/replayer.py` | 18693 | +| `packages/flow/openadapt_flow/runtime/replayer.py` | 17872 | | `packages/flow/openadapt_flow/__main__.py` | 14331 | | `packages/flow/openadapt_flow/qualification.py` | 5963 | | `packages/flow/openadapt_flow/ir.py` | 6830 | diff --git a/packages/flow/openadapt_flow/runtime/replay/effects.py b/packages/flow/openadapt_flow/runtime/replay/effects.py new file mode 100644 index 0000000000..be4cf6310a --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/replay/effects.py @@ -0,0 +1,912 @@ +# mypy: disable-error-code="empty-body" +"""Moved replayer code. + +Moved verbatim from ``openadapt_flow.runtime.replayer.Replayer`` by +scripts/extract_mixin.py (docs/design/DECOMPOSITION.md, section 4.1). +``_EffectChecksHost`` declares, for mypy only, what this code reads from the +Replayer it is mixed into. +""" + +from __future__ import annotations + +import hashlib +import threading +from types import SimpleNamespace +from typing import TYPE_CHECKING, Any, Optional # noqa: F401 + +from openadapt_flow.assurance import effect_read_wording as _effect_read_wording +from openadapt_flow.ir import EffectVerificationEvidence, HaltObservation, StepResult +from openadapt_flow.qualification_faults import effect_verifier_input_sha256 +from openadapt_flow.runtime.authorization import runtime_param_text +from openadapt_flow.runtime.durable.first_local_runtime import ( + placeholder_effect_refusal, +) +from openadapt_flow.runtime.effects import EffectState, reconcile_or_escalate +from openadapt_flow.runtime.effects.adapter import _probe_adapter_connection +from openadapt_flow.runtime.effects.adapter import ( + verifier_identity as effect_verifier_identity, +) +from openadapt_flow.runtime.effects.pipeline_safety import _pipeline_safe_verifier +from openadapt_flow.runtime.replay._shared import ( + _MAX_SERVER_RESPONSES, + effect_endpoint_scope, + effect_field_checks, +) +from openadapt_flow.runtime.step_timing import timed_span +from openadapt_flow.verification import ( + EffectContractMutationError, + verifier_effect_tier, + verify_effect_without_mutation, +) + +if TYPE_CHECKING: + from typing import Literal, Mapping + + from openadapt_flow.backend import Backend + from openadapt_flow.ir import Region, RunReport, Step, Workflow + from openadapt_flow.qualification_faults import ( + FaultMutationReceipt, + QualificationFaultGate, + ) + from openadapt_flow.runtime.authorization import ( + GovernedRunAuthorization, + RuntimeParamScalar, + ) + from openadapt_flow.runtime.effects import Effect, EffectVerifier + from openadapt_flow.runtime.readback_pipeline import ( + PipelinedReadback, + ReadbackPipeline, + ) + + +class _EffectChecksHost: + _durable_continuation_guard: Optional[Any] + _pipelined_readback: Optional["PipelinedReadback"] + _qualification_fault_context: Any + _qualification_fault_mutations: list[FaultMutationReceipt] + _readback_verifier: Any + _require_current_fault_driver_binding: Any + _run_id: str + _validate_fault_mutation: Any + backend: Backend + checkpoint_key: Optional[str] + durable: bool + effect_compensator: Optional[Any] + effect_verifier: Optional[EffectVerifier] + governed_authorization: Optional[GovernedRunAuthorization] + readback_pipeline: Optional["ReadbackPipeline"] + + +if TYPE_CHECKING: + _Base = _EffectChecksHost +else: + _Base = object + + +class EffectChecks(_Base): + """Moved replayer code.""" + + def _may_pipeline_readback( + self, verifier: Any, step: Optional[Step] = None + ) -> bool: + """Whether this effect's read-back may run on the side thread. + + A durable run defers the record check only when the durable pause + can hold it (docs/THROUGHPUT.md): a linear run, an encrypted + checkpoint store, and the item's last step, so nothing else in the + item waits on the check. + """ + + pipeline = getattr(self, "readback_pipeline", None) + if pipeline is None: + return False + reason = None + if getattr(self, "_program_durable", None) is not None: + reason = "durable program runs verify inline" + elif self.durable and self._durable_continuation_guard is not None: + reason = "a resumed durable run verifies inline" + elif self.durable and not self.checkpoint_key: + reason = ( + "a durable run without an encrypted checkpoint store verifies " + "inline (the deferred check keeps record rows)" + ) + elif self.durable and ( + step is None or step.id != getattr(self, "_linear_final_step_id", None) + ): + reason = ( + "a durable run defers only its last step's record check; this " + "one verifies inline" + ) + elif getattr(self, "idempotency_ledger", None) is not None: + reason = "idempotency-ledger runs verify inline" + elif getattr(self, "_pipelined_readback", None) is not None: + reason = "an earlier read-back in this item is still pending" + else: + target = verifier if verifier is not None else self.effect_verifier + if not _pipeline_safe_verifier(target): + reason = ( + "only REST, FHIR, GraphQL and SQL read-backs run alongside " + "the next item; this one verifies inline" + ) + pipeline.inline_reason = reason + return reason is None + + def _defer_readback( + self, + step: Step, + before: EffectState, + result: StepResult, + *, + effects: Optional[list["Effect"]], + verifier: Any, + actuation: Literal["gui", "api"] = "gui", + ) -> None: + assert self.readback_pipeline is not None + scratch = StepResult(step_id=step.id, intent=step.intent, ok=True) + # A durable run's check starts only once the durable pause holds it, + # so a crash in between can't leave a sent save without its pause. + # Whatever waits on the check also starts it. + start = threading.Event() + if not self.durable: + start.set() + + def verify() -> Optional[str]: + start.wait() + return self._verify_effects( + step, before, scratch, effects=effects, verifier=verifier + ) + + entry = self.readback_pipeline.submit(step.id, verify) + entry.start = start # type: ignore[attr-defined] + entry.scratch = scratch # type: ignore[attr-defined] + entry.result = result # type: ignore[attr-defined] + entry.intent = step.intent # type: ignore[attr-defined] + # What a durable pause needs to re-run this check after a crash. + entry.step = step # type: ignore[attr-defined] + entry.before = before # type: ignore[attr-defined] + entry.actuation = actuation # type: ignore[attr-defined] + entry.durable_run = None # type: ignore[attr-defined] + result.effect_verified = None + result.effect_results.append("[pipelined] system-of-record read-back pending") + self._pipelined_readback = entry + + def _join_pipelined_readback(self, *, keep: bool = False) -> Optional[str]: + """Wait for a pending read-back, apply it to its step, return its error.""" + + entry = getattr(self, "_pipelined_readback", None) + if entry is None: + return None + start = getattr(entry, "start", None) + if start is not None: + start.set() + try: + error = entry.verdict.result() + except Exception as exc: # noqa: BLE001 - a raising verifier fails closed + error = f"read-back raised {type(exc).__name__}; reconciliation is required" + self._copy_pipelined_evidence(entry, error) + if not keep: + self._pipelined_readback = None + return error + + def _copy_pipelined_evidence(self, entry: Any, error: Optional[str]) -> None: + result: StepResult = entry.result + scratch: StepResult = entry.scratch + result.effect_results = [ + r for r in result.effect_results if not r.startswith("[pipelined]") + ] + result.effect_results.extend(scratch.effect_results) + result.effect_evidence.extend(scratch.effect_evidence) + result.effect_field_checks.extend(scratch.effect_field_checks) + result.effect_verified = scratch.effect_verified + if scratch.failure_category is not None: + result.failure_category = scratch.failure_category + if error is not None: + result.ok = False + result.error = error + result.safety_halt = True + if result.failure_category is None: + result.failure_category = ( + "governed_refusal" + if self.governed_authorization is not None + else "safety_halt" + ) + else: + result.safety_halt = result.safety_halt or scratch.safety_halt + + def _apply_pipelined_verdict( + self, + report: RunReport, + error: Optional[str], + *, + entry: Optional["PipelinedReadback"] = None, + ) -> None: + if error is None: + return + report.success = False + report.execution_completed = False + report.terminal_outcome = "halt" + report.results.append( + StepResult( + step_id="", + intent="program halt", + ok=False, + error=error, + safety_halt=True, + ) + ) + if entry is None: + entry = getattr(self, "_pipelined_readback", None) + report.halt = HaltObservation( + state_id=getattr(entry, "step_id", "") or "", + intent=getattr(entry, "intent", "") or "", + reason=error, + outcome="halt", + # The screen now belongs to the next item; nothing is probed. + observed_texts=[], + completed_intents=[ + r.intent for r in report.results if r.ok and not r.skipped + ], + ) + + def recheck_deferred_readback( + self, + workflow: Workflow, + deferred: Any, + *, + params: Mapping[str, RuntimeParamScalar], + run_id: str, + read_only: bool = False, + ) -> StepResult: + """Re-run a durable pause's deferred record check; send nothing. + + The check runs against the snapshot of the system of record taken + before the save, with this replayer's system-of-record verifier. + Returns the save's result with the verdict applied: ``ok`` when the + record check confirmed the save. + """ + + from openadapt_flow.policy import effects_for_actuation + from openadapt_flow.runtime.durable.approval import StateDiverged + + step = workflow.steps[deferred.step_index] + if step.id != deferred.step_id: + raise StateDiverged( + "the deferred record check names a different step than the bundle" + ) + verifier = self.effect_verifier + if verifier is None or not _pipeline_safe_verifier(verifier): + raise StateDiverged( + "re-running a deferred record check needs the run's REST, FHIR, " + "GraphQL or SQL record checker" + ) + self._run_id = run_id + effects = self._resolve_effects( + list(effects_for_actuation(step, deferred.actuation)), params + ) + before = EffectState.model_validate(deferred.before) + result = deferred.result.model_copy(deep=True) + scratch = StepResult(step_id=step.id, intent=step.intent, ok=True) + try: + error = self._verify_effects( + step, + before, + scratch, + effects=effects, + verifier=verifier, + read_only=read_only, + ) + except Exception as exc: # noqa: BLE001 - a raising verifier fails closed + error = f"read-back raised {type(exc).__name__}; reconciliation is required" + self._copy_pipelined_evidence( + SimpleNamespace(result=result, scratch=scratch), error + ) + return result + + def _apply_effect_fault_mutation( + self, + *, + gate: QualificationFaultGate, + step: Step, + actuation_path: Literal["gui", "api"], + effect_verifier: Any, + effects: tuple[Any, ...], + ) -> Any: + if self._qualification_fault_mutations: + return effect_verifier + before_sha256 = effect_verifier_input_sha256(effect_verifier, effects) + context = self._qualification_fault_context( + gate=gate, + step=step, + actuation_path=actuation_path, + before_input_sha256=before_sha256, + effect_verifier=effect_verifier, + effects=effects, + ) + if context is None: + return effect_verifier + driver = self._require_current_fault_driver_binding() + mutation = driver.mutate(context) + if mutation is None: + return effect_verifier + if not mutation.replace_effect_verifier: + raise RuntimeError("qualification_effect_fault_did_not_replace_verifier") + after_sha256 = effect_verifier_input_sha256( + mutation.effect_verifier, + effects, + ) + self._validate_fault_mutation( + context, + mutation.receipt, + after_input_sha256=after_sha256, + ) + return mutation.effect_verifier + + def _resolve_effects( + self, effects: list["Effect"], params: Mapping[str, RuntimeParamScalar] + ) -> list["Effect"]: + """Bind each effect's ``ValueExpr`` contract to THIS run's params (P0-3). + + Mirrors how an ``ApiBinding``'s ``{param}`` templates are filled at + actuation time: the effect a PARAMETERIZED workflow verifies must + describe the record IT WROTE THIS RUN, not the demonstration's. The + reserved ``__run_id__`` param exposes the stable-per-run identity so an + idempotency key can be bound per-run. A pure-literal (v1) effect is + returned value-identical -- ``resolve`` is a no-op for it. + """ + namespace = { + **{name: runtime_param_text(value) for name, value in params.items()}, + "__run_id__": self._run_id, + } + run_id_sha256 = hashlib.sha256(self._run_id.encode("utf-8")).hexdigest() + return [ + effect.resolve( + namespace, + opaque_param_sha256={"__run_id__": run_id_sha256}, + ) + for effect in effects + ] + + @staticmethod + def _capture_effect_pre_state(verifier: Any, effects: list["Effect"]) -> Any: + """Capture the pre-action baseline for resolved effect contracts. + + Multi-candidate deployments select an adapter per resolved effect. A + normal verifier keeps the established single snapshot behavior. + """ + capture_for_effects = getattr(verifier, "capture_pre_state_for_effects", None) + if callable(capture_for_effects): + return capture_for_effects(effects) + if getattr(verifier, "_openadapt_requires_preflight", False): + probe = _probe_adapter_connection(verifier) + if not probe.ok: + raise ValueError( + "the selected effect verifier failed its read-only connection " + f"preflight ({probe.substrate}: {probe.reason})" + ) + return verifier.capture_pre_state() + + def _keep_undo_prior_state( + self, + workflow: Workflow, + step: Step, + before: Any, + effects: Optional[list["Effect"]], + params: Mapping[str, Any], + ) -> None: + """Keep what a locating or restoring undo of ``step`` needs. + + Reads only the pre-action baseline already captured; never raises and + never changes the step's result (``after_stop.keep_prior_state``). + """ + run_dir = getattr(self, "_undo_prior_run_dir", None) + if run_dir is None or not workflow.undo_steps or not effects: + return + try: + state = self._effect_pre_state_for(before, effects[0]) + except Exception: # noqa: BLE001 - bookkeeping never stops a run + return + if getattr(state, "reachable", None) is not True: + return + from openadapt_flow.after_stop import keep_prior_state + + keep_prior_state( + workflow, step, list(getattr(state, "records", []) or []), params, run_dir + ) + + @staticmethod + def _effect_pre_state_for(before: Any, effect: "Effect") -> Any: + """Return one selected effect baseline, or a normal shared baseline.""" + selected = getattr(before, "for_effect", None) + if callable(selected): + return selected(effect).state + return before + + @staticmethod + def _effect_binding_for( + verifier: Any, before: Any, effect: "Effect" + ) -> tuple[Any, Any, Optional[Any], str]: + """Return the exact adapter, state, tier, and identity bound to an effect.""" + + selected = getattr(before, "for_effect", None) + if callable(selected): + binding = selected(effect) + return ( + binding.verifier, + binding.state, + binding.tier, + binding.verifier_identity, + ) + return ( + verifier, + before, + verifier_effect_tier(verifier, effect), + effect_verifier_identity(verifier), + ) + + @staticmethod + def _candidate_binding_refusal( + before: Any, effects: list["Effect"] + ) -> Optional[str]: + """Refuse a candidate whose identity or tier changed after selection.""" + + selected = getattr(before, "for_effect", None) + if not callable(selected): + return None + for effect in effects: + binding = selected(effect) + current_tier = verifier_effect_tier(binding.verifier, effect) + current_identity = effect_verifier_identity(binding.verifier) + if ( + current_tier != binding.tier + or current_identity != binding.verifier_identity + ): + return ( + "the selected effect verifier identity or evidence tier changed " + "after pre-action binding; refusing to use a different proof" + ) + return None + + @staticmethod + def _verify_current_effect( + verifier: Any, effect: "Effect", current: EffectState + ) -> Any: + """Use an adapter's current-state path without inventing a new baseline.""" + + candidate = effect.model_copy(deep=True) + original = candidate.model_dump(mode="json") + callback = getattr(verifier, "verify_current_state", None) + if callable(callback): + verdict = callback(candidate, current) + else: + from openadapt_flow.runtime.effects._common import judge_records + + # An effect whose CLAIM is a delta (``exact_new_set``) cannot be + # judged against a synthesized empty baseline: every record in + # scope would read as an addition, so the verdict would be + # fabricated rather than proved. Mark the synthetic baseline + # UNREACHABLE for those effects and let the judge return its own + # structured INDETERMINATE refusal. Every pre-existing kind keeps + # the readable empty baseline and is judged exactly as before. + needs_baseline = bool(candidate.requires_baseline) + detail: dict[str, Any] = {"current_state_readback": True} + if needs_baseline: + detail["baseline_unavailable_for_delta"] = True + baseline = EffectState( + substrate=current.substrate, + reachable=not needs_baseline, + records=[], + detail=detail, + ) + verdict = judge_records( + candidate, + baseline, + current.records if current.reachable is True else None, + substrate=current.substrate, + ) + if candidate.model_dump(mode="json") != original: + raise EffectContractMutationError( + "effect verifier changed the resolved effect contract" + ) + return verdict + + @classmethod + def _required_effect_pre_state_unreadable( + cls, verifier: Any, before: Any, effects: list["Effect"] + ) -> bool: + """Return true only when a selected effect needs, but lacks, a baseline. + + Different-path on-screen read-back proves persistence after input and + deliberately has no readable pre-action state. Delta, duplicate, and + collateral checks still require their selected verifier baseline. + """ + requirement = getattr(verifier, "requires_readable_pre_state_for", None) + selected = getattr(before, "for_effect", None) + missing_reachability = object() + for effect in effects: + if callable(selected): + required = bool(selected(effect).requires_readable_pre_state) + else: + required = ( + bool(requirement(effect)) + if callable(requirement) + else bool(effect.requires_baseline or effect.forbid_collateral_loss) + ) + state = cls._effect_pre_state_for(before, effect) + # Legacy in-process verifiers may retain an opaque pre-state for + # their own verify implementation. Their established verification + # path decides whether it is usable. If a legacy state exposes + # reachability, it must state exactly True; None, falsey values, + # and truthy non-bools are not evidence that its baseline is + # readable. Candidate deployments are stricter: their verifier + # accepts only EffectState, so a missing reachability value cannot + # bypass its pre-actuation guard. + reachable = getattr(state, "reachable", missing_reachability) + if ( + required + and reachable is not missing_reachability + and reachable is not True + ): + return True + return False + + def _profile_effect_tier_refusal( + self, + workflow: Workflow, + step: Step, + actuation_path: Literal["gui", "api"], + effects: list["Effect"], + verifier: object, + ) -> Optional[str]: + """Recheck effect strength immediately before governed actuation.""" + + authorization = self.governed_authorization + if authorization is None or authorization.execution_profile is None: + return None + from openadapt_flow.execution_profiles import required_effect_tier + from openadapt_flow.verification import VerificationTier + + minimum = ( + VerificationTier(authorization.minimum_effect_tier) + if authorization.minimum_effect_tier is not None + else required_effect_tier(workflow, authorization.execution_profile) + ) + if minimum is None: + return None + requirements = authorization.effect_requirements(step.id, actuation_path) + if requirements: + from openadapt_flow.policy import effects_for_actuation + + declared = effects_for_actuation( + step, "api" if actuation_path == "api" else "guarded_coordinate" + ) + if len(requirements) != len(declared) or len(effects) != len(declared): + return ( + "Qualified effect requirements changed after admission — " + "refusing to actuate; run aborted" + ) + for index, requirement in enumerate(requirements): + if ( + requirement.effect_index != index + or requirement.effect_contract_hash + != declared[index].contract_hash() + ): + return ( + "Qualified effect contract changed after admission — " + "refusing to actuate; run aborted" + ) + weak = [] + for index, effect in enumerate(effects): + required = ( + VerificationTier(requirements[index].minimum_tier) + if requirements + else minimum + ) + actual = verifier_effect_tier(verifier, effect) + if actual is None or not actual.satisfies(required): + weak.append("untyped" if actual is None else actual.name.lower()) + if not weak: + return None + observed = ", ".join(sorted(set(weak))) + return ( + "Effect verifier strength changed after admission: " + f"{observed} evidence cannot satisfy the required " + "qualified effect tier — refusing to actuate; run aborted" + ) + + def _all_default_readback(self, effects: list["Effect"]) -> bool: + """Whether EVERY declared effect is an auto-derived DIFFERENT-PATH + on-screen read-back that may be verified out of the box with no + connector (measured false-CONFIRM ~0). A same-surface read-back or any + structured system-of-record effect makes this False — those still + require a configured verifier (fail-safe).""" + from openadapt_flow.runtime.effects.onscreen import is_default_readback_effect + + return bool(effects) and all(is_default_readback_effect(e) for e in effects) + + def _auto_readback_verifier(self) -> Any: + """The backend-bound on-screen read-back verifier for the no-connector + default path (built once, reused across steps).""" + verifier = getattr(self, "_readback_verifier", None) + if verifier is None: + from openadapt_flow.runtime.effects.onscreen import ( + OnScreenReadbackVerifier, + ) + + verifier = OnScreenReadbackVerifier(backend=self.backend) + self._readback_verifier = verifier + return verifier + + def _server_response_mark(self) -> Optional[int]: + """Where the backend's server-answer log stands, or None when the + backend doesn't see server answers (every non-browser backend).""" + + mark = getattr(self.backend, "server_response_mark", None) + if not callable(mark): + return None + try: + return int(mark()) + except Exception: # noqa: BLE001 - evidence only, never a failure + return None + + def _collect_server_responses(self, result: StepResult, mark: int) -> None: + since = getattr(self.backend, "server_responses_since", None) + if not callable(since): + return + try: + responses = list(since(mark)) + except Exception: # noqa: BLE001 - evidence only, never a failure + return + result.server_responses = responses[:_MAX_SERVER_RESPONSES] + + @timed_span("readback") + def _verify_effects( + self, + step: Step, + before: EffectState, + result: StepResult, + effects: Optional[list["Effect"]] = None, + verifier: Any = None, + *, + read_only: bool = False, + ) -> Optional[str]: + """Verify each declared Effect against the system of record; HALT on + any non-CONFIRMED verdict. + + Runs AFTER the action and its screen postconditions (for a GUI write), + or immediately after an API actuation. For each effect the configured + verifier rules CONFIRMED / REFUTED / INDETERMINATE against the REAL + record (an API/DB read, never the screen). A CONFIRMED effect proceeds; + a non-CONFIRMED effect halts, except that an IRREVERSIBLE effect is + first routed through ``reconcile_or_escalate`` -- a duplicate the + configured compensator can undo is RECONCILED (proceed), everything else + ESCALATEs (halt). Every verdict is recorded on ``result.effect_results`` + for the audit trail. Makes ZERO model calls (the $0 runtime guarantee). + + Args: + step: The step being verified (for the audit/error text). + before: The pre-action snapshot of the system of record. + result: The step result to record verdicts on. + effects: The effects to verify; defaults to ``step.effects`` (the + GUI path). The API tier passes ``api_binding.effects`` only. + + Returns an error string (HALT) or None (all effects confirmed or + reconciled). + """ + # ``verifier`` is the configured one by default, but the caller may pass + # the auto-wired backend-bound read-back verifier (the no-connector + # default path) for a step whose effects are different-path read-backs. + if verifier is None: + verifier = self.effect_verifier + assert verifier is not None # guaranteed by the caller + if effects is None: + effects = step.effects + for effect in effects: + refusal = placeholder_effect_refusal(step, effect, result) + if refusal is not None: + return refusal + try: + verdict = verify_effect_without_mutation(verifier, effect, before) + scope = effect_endpoint_scope(verifier) + selected_pre_state = getattr(before, "for_effect", None) + if callable(selected_pre_state): + # Candidate selection and its evidence strength are pinned + # before input. Do not recompute the tier after delivery: + # a stateful plugin must not change the receipt contract. + binding = selected_pre_state(effect) + tier = binding.tier + identity = binding.verifier_identity + scope = effect_endpoint_scope(binding.verifier) + if ( + verifier_effect_tier(binding.verifier, effect) != tier + or effect_verifier_identity(binding.verifier) != identity + ): + result.effect_verified = False + result.safety_halt = True + result.failure_category = "governed_refusal" + result.effect_results.append( + "selected effect verifier identity or evidence tier " + "changed after input; HALT" + ) + return ( + f"Effect verifier binding changed after input for step " + f"'{step.id}' — refusing evidence from a different " + "adapter or tier; reconciliation is required" + ) + else: + tier = verifier_effect_tier(verifier, effect) + identity = effect_verifier_identity(verifier) + except EffectContractMutationError: + result.effect_verified = False + result.safety_halt = True + result.failure_category = "governed_refusal" + result.effect_results.append( + "effect verifier changed the resolved effect contract; HALT" + ) + return ( + f"Effect verifier changed the resolved contract for step " + f"'{step.id}' — refusing mutable verification evidence; " + "run aborted" + ) + result.effect_field_checks.extend( + effect_field_checks(effect, verdict, tier) + ) + if verdict.confirmed: + result.effect_evidence.append( + EffectVerificationEvidence( + effect_contract_hash=effect.contract_hash(), + substrate=verdict.substrate, + verifier_identity=identity, + verification_tier=(int(tier) if tier is not None else None), + initial_verdict=verdict.verdict.value, + final_verdict=verdict.verdict.value, + observed_effect=verdict.observed_effect, + endpoint_scope=scope, + read_evidence=verdict.read_evidence, + ) + ) + result.effect_results.append( + f"[{verdict.substrate}] {effect.kind.value}: CONFIRMED" + + (f" — {verdict.reason}" if verdict.reason else "") + ) + continue + + # Non-CONFIRMED: never proceed on an unverified/contradicted write. + # An irreversible effect gets one reconcile-or-escalate pass (a + # compensable duplicate is fixable; missing / partial / collateral + # loss / INDETERMINATE always escalate). A reversible effect just + # halts. Either way the run stops -- this is the same + # refuse-rather-than-guess posture as the identity gate. + if effect.risk == "irreversible" and not read_only: + comp = reconcile_or_escalate( + effect, + verdict, + verifier=verifier, + before=before, + compensator=self.effect_compensator, + ) + if comp.proceed: + final_verdict = comp.final_verdict or verdict + result.effect_evidence.append( + EffectVerificationEvidence( + effect_contract_hash=effect.contract_hash(), + substrate=final_verdict.substrate, + verifier_identity=identity, + verification_tier=(int(tier) if tier is not None else None), + initial_verdict=verdict.verdict.value, + final_verdict=final_verdict.verdict.value, + observed_effect=final_verdict.observed_effect, + endpoint_scope=scope, + read_evidence=final_verdict.read_evidence, + reconciliation_completed=True, + reconciliation_actions=comp.actions_taken, + ) + ) + result.effect_results.append( + f"[{verdict.substrate}] {effect.kind.value}: " + f"{verdict.verdict.value.upper()} → RECONCILED " + f"({comp.actions_taken} action(s)) — {comp.reason}" + ) + continue + result.effect_verified = False + final_verdict = comp.final_verdict or verdict + result.effect_evidence.append( + EffectVerificationEvidence( + effect_contract_hash=effect.contract_hash(), + substrate=final_verdict.substrate, + verifier_identity=identity, + verification_tier=(int(tier) if tier is not None else None), + initial_verdict=verdict.verdict.value, + final_verdict=final_verdict.verdict.value, + observed_effect=final_verdict.observed_effect, + endpoint_scope=scope, + read_evidence=final_verdict.read_evidence, + reconciliation_actions=comp.actions_taken, + deferred_check=verdict.deferred_check, + ) + ) + result.effect_results.append( + f"[{verdict.substrate}] {effect.kind.value}: " + f"{verdict.verdict.value.upper()} → " + f"{comp.outcome.value.upper()} — {comp.reason}" + ) + prefix, read = _effect_read_wording(tier) + return ( + f"{prefix} HALTED step " + f"'{step.id}' ({step.intent}): {effect.kind.value} " + f"{verdict.verdict.value} against the {verdict.substrate} " + f"{read} and could not be reconciled " + f"({comp.outcome.value}) — " + f"{comp.escalation or comp.reason} — run aborted" + ) + + result.effect_verified = False + result.effect_evidence.append( + EffectVerificationEvidence( + effect_contract_hash=effect.contract_hash(), + substrate=verdict.substrate, + verifier_identity=identity, + verification_tier=(int(tier) if tier is not None else None), + initial_verdict=verdict.verdict.value, + final_verdict=verdict.verdict.value, + observed_effect=verdict.observed_effect, + endpoint_scope=scope, + read_evidence=verdict.read_evidence, + deferred_check=verdict.deferred_check, + ) + ) + result.effect_results.append( + f"[{verdict.substrate}] {effect.kind.value}: " + f"{verdict.verdict.value.upper()} — {verdict.reason}" + ) + prefix, read = _effect_read_wording(tier) + return ( + f"{prefix} HALTED step " + f"'{step.id}' ({step.intent}): {effect.kind.value} " + f"{verdict.verdict.value} against the {verdict.substrate} " + f"{read} (the screen indicated completion but the " + f"declared outcome is contradicted or unverifiable) — " + f"{verdict.reason} — run aborted" + ) + + result.effect_verified = True + return None + + @staticmethod + def _mapped_selection_readback_region( + recorded_target: Region, + recorded_readback: Region, + live_target: Region, + frame_png: bytes, + ) -> Optional[Region]: + """Map the recorded readback band onto a fresh live target. + + Absolute recording coordinates never drive verification. The mapping + preserves the band's target-relative offsets while allowing the + already-qualified target geometry to translate or scale modestly, then + clamps it to the exact final frame. + """ + + from openadapt_flow.vision import imgops + + frame = imgops.decode_bgr(frame_png) + if frame is None: + return None + frame_h, frame_w = frame.shape[:2] + target_x, target_y, target_w, target_h = recorded_target + read_x, read_y, read_w, read_h = recorded_readback + live_x, live_y, live_w, live_h = live_target + if min(target_w, target_h, read_w, read_h, live_w, live_h) <= 0: + return None + scale_x = live_w / target_w + scale_y = live_h / target_h + mapped_x = round(live_x + (read_x - target_x) * scale_x) + mapped_y = round(live_y + (read_y - target_y) * scale_y) + mapped_w = max(1, round(read_w * scale_x)) + mapped_h = max(1, round(read_h * scale_y)) + left = max(0, mapped_x) + top = max(0, mapped_y) + right = min(frame_w, mapped_x + mapped_w) + bottom = min(frame_h, mapped_y + mapped_h) + if right <= left or bottom <= top: + return None + return (left, top, right - left, bottom - top) diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 0ec215ccbe..69a97053f2 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -54,7 +54,7 @@ from dataclasses import dataclass # noqa: F401 from datetime import datetime, timezone from pathlib import Path -from types import SimpleNamespace +from types import SimpleNamespace # noqa: F401 from typing import ( # noqa: F401 TYPE_CHECKING, Any, @@ -70,7 +70,7 @@ from urllib.parse import urlsplit from openadapt_flow import sealed_set as _sealed -from openadapt_flow.assurance import effect_read_wording as _effect_read_wording +from openadapt_flow.assurance import effect_read_wording as _effect_read_wording # noqa: F401 from openadapt_flow.backend import ( ActionDeliveryUncertain, Backend, @@ -204,7 +204,7 @@ from openadapt_flow.runtime.durable import program_runtime as _program_runtime from openadapt_flow.runtime.durable.approval import StateDiverged from openadapt_flow.runtime.durable.first_local_delivery import FirstLocalDeliveryHeld -from openadapt_flow.runtime.durable.first_local_runtime import ( +from openadapt_flow.runtime.durable.first_local_runtime import ( # noqa: F401 FirstLocalDeliveryStep, arm_first_local_delivery, first_local_effect_refusal, @@ -228,19 +228,19 @@ history_hash as _history_hash, ) from openadapt_flow.runtime.effect_watch import EffectWatchReport, watch_effects # noqa: F401 -from openadapt_flow.runtime.effects import ( +from openadapt_flow.runtime.effects import ( # noqa: F401 Effect, EffectState, EffectVerifier, reconcile_or_escalate, ) -from openadapt_flow.runtime.effects.adapter import ( +from openadapt_flow.runtime.effects.adapter import ( # noqa: F401 _probe_adapter_connection, ) from openadapt_flow.runtime.effects.adapter import ( verifier_identity as effect_verifier_identity, ) -from openadapt_flow.runtime.effects.pipeline_safety import _pipeline_safe_verifier +from openadapt_flow.runtime.effects.pipeline_safety import _pipeline_safe_verifier # noqa: F401 from openadapt_flow.runtime.known_ids import ( lookalike_class as known_ids_lookalike_class, ) @@ -270,7 +270,7 @@ secret_env_var, secret_env_vars, ) -from openadapt_flow.verification import ( +from openadapt_flow.verification import ( # noqa: F401 EffectContractMutationError, verifier_effect_tier, verify_effect_without_mutation, @@ -343,6 +343,7 @@ effect_field_checks, identity_read_contradicts, ) +from openadapt_flow.runtime.replay.effects import EffectChecks from openadapt_flow.runtime.replay.evidence import AssetsHealingAndEvidence from openadapt_flow.runtime.replay.qualification_faults import ( QualificationFaultInjection, @@ -351,7 +352,10 @@ class Replayer( - QualificationFaultInjection, AssetsHealingAndEvidence, SettlingAndInterstitials + QualificationFaultInjection, + AssetsHealingAndEvidence, + SettlingAndInterstitials, + EffectChecks, ): """Replays a Workflow against a Backend using injected vision. @@ -3014,168 +3018,6 @@ def _settle(error: Optional[str]) -> RunReport: # -- pipelined read-back (runtime/readback_pipeline.py) ------------------ - def _may_pipeline_readback( - self, verifier: Any, step: Optional[Step] = None - ) -> bool: - """Whether this effect's read-back may run on the side thread. - - A durable run defers the record check only when the durable pause - can hold it (docs/THROUGHPUT.md): a linear run, an encrypted - checkpoint store, and the item's last step, so nothing else in the - item waits on the check. - """ - - pipeline = getattr(self, "readback_pipeline", None) - if pipeline is None: - return False - reason = None - if getattr(self, "_program_durable", None) is not None: - reason = "durable program runs verify inline" - elif self.durable and self._durable_continuation_guard is not None: - reason = "a resumed durable run verifies inline" - elif self.durable and not self.checkpoint_key: - reason = ( - "a durable run without an encrypted checkpoint store verifies " - "inline (the deferred check keeps record rows)" - ) - elif self.durable and ( - step is None or step.id != getattr(self, "_linear_final_step_id", None) - ): - reason = ( - "a durable run defers only its last step's record check; this " - "one verifies inline" - ) - elif getattr(self, "idempotency_ledger", None) is not None: - reason = "idempotency-ledger runs verify inline" - elif getattr(self, "_pipelined_readback", None) is not None: - reason = "an earlier read-back in this item is still pending" - else: - target = verifier if verifier is not None else self.effect_verifier - if not _pipeline_safe_verifier(target): - reason = ( - "only REST, FHIR, GraphQL and SQL read-backs run alongside " - "the next item; this one verifies inline" - ) - pipeline.inline_reason = reason - return reason is None - - def _defer_readback( - self, - step: Step, - before: EffectState, - result: StepResult, - *, - effects: Optional[list["Effect"]], - verifier: Any, - actuation: Literal["gui", "api"] = "gui", - ) -> None: - assert self.readback_pipeline is not None - scratch = StepResult(step_id=step.id, intent=step.intent, ok=True) - # A durable run's check starts only once the durable pause holds it, - # so a crash in between can't leave a sent save without its pause. - # Whatever waits on the check also starts it. - start = threading.Event() - if not self.durable: - start.set() - - def verify() -> Optional[str]: - start.wait() - return self._verify_effects( - step, before, scratch, effects=effects, verifier=verifier - ) - - entry = self.readback_pipeline.submit(step.id, verify) - entry.start = start # type: ignore[attr-defined] - entry.scratch = scratch # type: ignore[attr-defined] - entry.result = result # type: ignore[attr-defined] - entry.intent = step.intent # type: ignore[attr-defined] - # What a durable pause needs to re-run this check after a crash. - entry.step = step # type: ignore[attr-defined] - entry.before = before # type: ignore[attr-defined] - entry.actuation = actuation # type: ignore[attr-defined] - entry.durable_run = None # type: ignore[attr-defined] - result.effect_verified = None - result.effect_results.append("[pipelined] system-of-record read-back pending") - self._pipelined_readback = entry - - def _join_pipelined_readback(self, *, keep: bool = False) -> Optional[str]: - """Wait for a pending read-back, apply it to its step, return its error.""" - - entry = getattr(self, "_pipelined_readback", None) - if entry is None: - return None - start = getattr(entry, "start", None) - if start is not None: - start.set() - try: - error = entry.verdict.result() - except Exception as exc: # noqa: BLE001 - a raising verifier fails closed - error = f"read-back raised {type(exc).__name__}; reconciliation is required" - self._copy_pipelined_evidence(entry, error) - if not keep: - self._pipelined_readback = None - return error - - def _copy_pipelined_evidence(self, entry: Any, error: Optional[str]) -> None: - result: StepResult = entry.result - scratch: StepResult = entry.scratch - result.effect_results = [ - r for r in result.effect_results if not r.startswith("[pipelined]") - ] - result.effect_results.extend(scratch.effect_results) - result.effect_evidence.extend(scratch.effect_evidence) - result.effect_field_checks.extend(scratch.effect_field_checks) - result.effect_verified = scratch.effect_verified - if scratch.failure_category is not None: - result.failure_category = scratch.failure_category - if error is not None: - result.ok = False - result.error = error - result.safety_halt = True - if result.failure_category is None: - result.failure_category = ( - "governed_refusal" - if self.governed_authorization is not None - else "safety_halt" - ) - else: - result.safety_halt = result.safety_halt or scratch.safety_halt - - def _apply_pipelined_verdict( - self, - report: RunReport, - error: Optional[str], - *, - entry: Optional["PipelinedReadback"] = None, - ) -> None: - if error is None: - return - report.success = False - report.execution_completed = False - report.terminal_outcome = "halt" - report.results.append( - StepResult( - step_id="", - intent="program halt", - ok=False, - error=error, - safety_halt=True, - ) - ) - if entry is None: - entry = getattr(self, "_pipelined_readback", None) - report.halt = HaltObservation( - state_id=getattr(entry, "step_id", "") or "", - intent=getattr(entry, "intent", "") or "", - reason=error, - outcome="halt", - # The screen now belongs to the next item; nothing is probed. - observed_texts=[], - completed_intents=[ - r.intent for r in report.results if r.ok and not r.skipped - ], - ) - def _settle_pipelined_readback( self, report: RunReport, @@ -3213,60 +3055,6 @@ def _settle_pipelined_readback( report.save(run_dir) return report - def recheck_deferred_readback( - self, - workflow: Workflow, - deferred: Any, - *, - params: Mapping[str, RuntimeParamScalar], - run_id: str, - read_only: bool = False, - ) -> StepResult: - """Re-run a durable pause's deferred record check; send nothing. - - The check runs against the snapshot of the system of record taken - before the save, with this replayer's system-of-record verifier. - Returns the save's result with the verdict applied: ``ok`` when the - record check confirmed the save. - """ - - from openadapt_flow.policy import effects_for_actuation - from openadapt_flow.runtime.durable.approval import StateDiverged - - step = workflow.steps[deferred.step_index] - if step.id != deferred.step_id: - raise StateDiverged( - "the deferred record check names a different step than the bundle" - ) - verifier = self.effect_verifier - if verifier is None or not _pipeline_safe_verifier(verifier): - raise StateDiverged( - "re-running a deferred record check needs the run's REST, FHIR, " - "GraphQL or SQL record checker" - ) - self._run_id = run_id - effects = self._resolve_effects( - list(effects_for_actuation(step, deferred.actuation)), params - ) - before = EffectState.model_validate(deferred.before) - result = deferred.result.model_copy(deep=True) - scratch = StepResult(step_id=step.id, intent=step.intent, ok=True) - try: - error = self._verify_effects( - step, - before, - scratch, - effects=effects, - verifier=verifier, - read_only=read_only, - ) - except Exception as exc: # noqa: BLE001 - a raising verifier fails closed - error = f"read-back raised {type(exc).__name__}; reconciliation is required" - self._copy_pipelined_evidence( - SimpleNamespace(result=result, scratch=scratch), error - ) - return result - def _settle_durable_readback( self, entry: Any, error: Optional[str] ) -> Optional[str]: @@ -6664,45 +6452,6 @@ def _qualification_fault_driver_refusal(self, workflow: Workflow) -> Optional[st self._qualification_fault_public_key = trusted return None - def _apply_effect_fault_mutation( - self, - *, - gate: QualificationFaultGate, - step: Step, - actuation_path: Literal["gui", "api"], - effect_verifier: Any, - effects: tuple[Any, ...], - ) -> Any: - if self._qualification_fault_mutations: - return effect_verifier - before_sha256 = effect_verifier_input_sha256(effect_verifier, effects) - context = self._qualification_fault_context( - gate=gate, - step=step, - actuation_path=actuation_path, - before_input_sha256=before_sha256, - effect_verifier=effect_verifier, - effects=effects, - ) - if context is None: - return effect_verifier - driver = self._require_current_fault_driver_binding() - mutation = driver.mutate(context) - if mutation is None: - return effect_verifier - if not mutation.replace_effect_verifier: - raise RuntimeError("qualification_effect_fault_did_not_replace_verifier") - after_sha256 = effect_verifier_input_sha256( - mutation.effect_verifier, - effects, - ) - self._validate_fault_mutation( - context, - mutation.receipt, - after_input_sha256=after_sha256, - ) - return mutation.effect_verifier - # -- multi-surface routing (docs/MULTI_SURFACE.md) ----------------------- def _begin_surfaces( @@ -9448,536 +9197,6 @@ def _set_api_unavailable_refusal( # -- system-of-record effect verification ----------------------------------- - def _resolve_effects( - self, effects: list["Effect"], params: Mapping[str, RuntimeParamScalar] - ) -> list["Effect"]: - """Bind each effect's ``ValueExpr`` contract to THIS run's params (P0-3). - - Mirrors how an ``ApiBinding``'s ``{param}`` templates are filled at - actuation time: the effect a PARAMETERIZED workflow verifies must - describe the record IT WROTE THIS RUN, not the demonstration's. The - reserved ``__run_id__`` param exposes the stable-per-run identity so an - idempotency key can be bound per-run. A pure-literal (v1) effect is - returned value-identical -- ``resolve`` is a no-op for it. - """ - namespace = { - **{name: runtime_param_text(value) for name, value in params.items()}, - "__run_id__": self._run_id, - } - run_id_sha256 = hashlib.sha256(self._run_id.encode("utf-8")).hexdigest() - return [ - effect.resolve( - namespace, - opaque_param_sha256={"__run_id__": run_id_sha256}, - ) - for effect in effects - ] - - @staticmethod - def _capture_effect_pre_state(verifier: Any, effects: list["Effect"]) -> Any: - """Capture the pre-action baseline for resolved effect contracts. - - Multi-candidate deployments select an adapter per resolved effect. A - normal verifier keeps the established single snapshot behavior. - """ - capture_for_effects = getattr(verifier, "capture_pre_state_for_effects", None) - if callable(capture_for_effects): - return capture_for_effects(effects) - if getattr(verifier, "_openadapt_requires_preflight", False): - probe = _probe_adapter_connection(verifier) - if not probe.ok: - raise ValueError( - "the selected effect verifier failed its read-only connection " - f"preflight ({probe.substrate}: {probe.reason})" - ) - return verifier.capture_pre_state() - - def _keep_undo_prior_state( - self, - workflow: Workflow, - step: Step, - before: Any, - effects: Optional[list["Effect"]], - params: Mapping[str, Any], - ) -> None: - """Keep what a locating or restoring undo of ``step`` needs. - - Reads only the pre-action baseline already captured; never raises and - never changes the step's result (``after_stop.keep_prior_state``). - """ - run_dir = getattr(self, "_undo_prior_run_dir", None) - if run_dir is None or not workflow.undo_steps or not effects: - return - try: - state = self._effect_pre_state_for(before, effects[0]) - except Exception: # noqa: BLE001 - bookkeeping never stops a run - return - if getattr(state, "reachable", None) is not True: - return - from openadapt_flow.after_stop import keep_prior_state - - keep_prior_state( - workflow, step, list(getattr(state, "records", []) or []), params, run_dir - ) - - @staticmethod - def _effect_pre_state_for(before: Any, effect: "Effect") -> Any: - """Return one selected effect baseline, or a normal shared baseline.""" - selected = getattr(before, "for_effect", None) - if callable(selected): - return selected(effect).state - return before - - @staticmethod - def _effect_binding_for( - verifier: Any, before: Any, effect: "Effect" - ) -> tuple[Any, Any, Optional[Any], str]: - """Return the exact adapter, state, tier, and identity bound to an effect.""" - - selected = getattr(before, "for_effect", None) - if callable(selected): - binding = selected(effect) - return ( - binding.verifier, - binding.state, - binding.tier, - binding.verifier_identity, - ) - return ( - verifier, - before, - verifier_effect_tier(verifier, effect), - effect_verifier_identity(verifier), - ) - - @staticmethod - def _candidate_binding_refusal( - before: Any, effects: list["Effect"] - ) -> Optional[str]: - """Refuse a candidate whose identity or tier changed after selection.""" - - selected = getattr(before, "for_effect", None) - if not callable(selected): - return None - for effect in effects: - binding = selected(effect) - current_tier = verifier_effect_tier(binding.verifier, effect) - current_identity = effect_verifier_identity(binding.verifier) - if ( - current_tier != binding.tier - or current_identity != binding.verifier_identity - ): - return ( - "the selected effect verifier identity or evidence tier changed " - "after pre-action binding; refusing to use a different proof" - ) - return None - - @staticmethod - def _verify_current_effect( - verifier: Any, effect: "Effect", current: EffectState - ) -> Any: - """Use an adapter's current-state path without inventing a new baseline.""" - - candidate = effect.model_copy(deep=True) - original = candidate.model_dump(mode="json") - callback = getattr(verifier, "verify_current_state", None) - if callable(callback): - verdict = callback(candidate, current) - else: - from openadapt_flow.runtime.effects._common import judge_records - - # An effect whose CLAIM is a delta (``exact_new_set``) cannot be - # judged against a synthesized empty baseline: every record in - # scope would read as an addition, so the verdict would be - # fabricated rather than proved. Mark the synthetic baseline - # UNREACHABLE for those effects and let the judge return its own - # structured INDETERMINATE refusal. Every pre-existing kind keeps - # the readable empty baseline and is judged exactly as before. - needs_baseline = bool(candidate.requires_baseline) - detail: dict[str, Any] = {"current_state_readback": True} - if needs_baseline: - detail["baseline_unavailable_for_delta"] = True - baseline = EffectState( - substrate=current.substrate, - reachable=not needs_baseline, - records=[], - detail=detail, - ) - verdict = judge_records( - candidate, - baseline, - current.records if current.reachable is True else None, - substrate=current.substrate, - ) - if candidate.model_dump(mode="json") != original: - raise EffectContractMutationError( - "effect verifier changed the resolved effect contract" - ) - return verdict - - @classmethod - def _required_effect_pre_state_unreadable( - cls, verifier: Any, before: Any, effects: list["Effect"] - ) -> bool: - """Return true only when a selected effect needs, but lacks, a baseline. - - Different-path on-screen read-back proves persistence after input and - deliberately has no readable pre-action state. Delta, duplicate, and - collateral checks still require their selected verifier baseline. - """ - requirement = getattr(verifier, "requires_readable_pre_state_for", None) - selected = getattr(before, "for_effect", None) - missing_reachability = object() - for effect in effects: - if callable(selected): - required = bool(selected(effect).requires_readable_pre_state) - else: - required = ( - bool(requirement(effect)) - if callable(requirement) - else bool(effect.requires_baseline or effect.forbid_collateral_loss) - ) - state = cls._effect_pre_state_for(before, effect) - # Legacy in-process verifiers may retain an opaque pre-state for - # their own verify implementation. Their established verification - # path decides whether it is usable. If a legacy state exposes - # reachability, it must state exactly True; None, falsey values, - # and truthy non-bools are not evidence that its baseline is - # readable. Candidate deployments are stricter: their verifier - # accepts only EffectState, so a missing reachability value cannot - # bypass its pre-actuation guard. - reachable = getattr(state, "reachable", missing_reachability) - if ( - required - and reachable is not missing_reachability - and reachable is not True - ): - return True - return False - - def _profile_effect_tier_refusal( - self, - workflow: Workflow, - step: Step, - actuation_path: Literal["gui", "api"], - effects: list["Effect"], - verifier: object, - ) -> Optional[str]: - """Recheck effect strength immediately before governed actuation.""" - - authorization = self.governed_authorization - if authorization is None or authorization.execution_profile is None: - return None - from openadapt_flow.execution_profiles import required_effect_tier - from openadapt_flow.verification import VerificationTier - - minimum = ( - VerificationTier(authorization.minimum_effect_tier) - if authorization.minimum_effect_tier is not None - else required_effect_tier(workflow, authorization.execution_profile) - ) - if minimum is None: - return None - requirements = authorization.effect_requirements(step.id, actuation_path) - if requirements: - from openadapt_flow.policy import effects_for_actuation - - declared = effects_for_actuation( - step, "api" if actuation_path == "api" else "guarded_coordinate" - ) - if len(requirements) != len(declared) or len(effects) != len(declared): - return ( - "Qualified effect requirements changed after admission — " - "refusing to actuate; run aborted" - ) - for index, requirement in enumerate(requirements): - if ( - requirement.effect_index != index - or requirement.effect_contract_hash - != declared[index].contract_hash() - ): - return ( - "Qualified effect contract changed after admission — " - "refusing to actuate; run aborted" - ) - weak = [] - for index, effect in enumerate(effects): - required = ( - VerificationTier(requirements[index].minimum_tier) - if requirements - else minimum - ) - actual = verifier_effect_tier(verifier, effect) - if actual is None or not actual.satisfies(required): - weak.append("untyped" if actual is None else actual.name.lower()) - if not weak: - return None - observed = ", ".join(sorted(set(weak))) - return ( - "Effect verifier strength changed after admission: " - f"{observed} evidence cannot satisfy the required " - "qualified effect tier — refusing to actuate; run aborted" - ) - - def _all_default_readback(self, effects: list["Effect"]) -> bool: - """Whether EVERY declared effect is an auto-derived DIFFERENT-PATH - on-screen read-back that may be verified out of the box with no - connector (measured false-CONFIRM ~0). A same-surface read-back or any - structured system-of-record effect makes this False — those still - require a configured verifier (fail-safe).""" - from openadapt_flow.runtime.effects.onscreen import is_default_readback_effect - - return bool(effects) and all(is_default_readback_effect(e) for e in effects) - - def _auto_readback_verifier(self) -> Any: - """The backend-bound on-screen read-back verifier for the no-connector - default path (built once, reused across steps).""" - verifier = getattr(self, "_readback_verifier", None) - if verifier is None: - from openadapt_flow.runtime.effects.onscreen import ( - OnScreenReadbackVerifier, - ) - - verifier = OnScreenReadbackVerifier(backend=self.backend) - self._readback_verifier = verifier - return verifier - - def _server_response_mark(self) -> Optional[int]: - """Where the backend's server-answer log stands, or None when the - backend doesn't see server answers (every non-browser backend).""" - - mark = getattr(self.backend, "server_response_mark", None) - if not callable(mark): - return None - try: - return int(mark()) - except Exception: # noqa: BLE001 - evidence only, never a failure - return None - - def _collect_server_responses(self, result: StepResult, mark: int) -> None: - since = getattr(self.backend, "server_responses_since", None) - if not callable(since): - return - try: - responses = list(since(mark)) - except Exception: # noqa: BLE001 - evidence only, never a failure - return - result.server_responses = responses[:_MAX_SERVER_RESPONSES] - - @timed_span("readback") - def _verify_effects( - self, - step: Step, - before: EffectState, - result: StepResult, - effects: Optional[list["Effect"]] = None, - verifier: Any = None, - *, - read_only: bool = False, - ) -> Optional[str]: - """Verify each declared Effect against the system of record; HALT on - any non-CONFIRMED verdict. - - Runs AFTER the action and its screen postconditions (for a GUI write), - or immediately after an API actuation. For each effect the configured - verifier rules CONFIRMED / REFUTED / INDETERMINATE against the REAL - record (an API/DB read, never the screen). A CONFIRMED effect proceeds; - a non-CONFIRMED effect halts, except that an IRREVERSIBLE effect is - first routed through ``reconcile_or_escalate`` -- a duplicate the - configured compensator can undo is RECONCILED (proceed), everything else - ESCALATEs (halt). Every verdict is recorded on ``result.effect_results`` - for the audit trail. Makes ZERO model calls (the $0 runtime guarantee). - - Args: - step: The step being verified (for the audit/error text). - before: The pre-action snapshot of the system of record. - result: The step result to record verdicts on. - effects: The effects to verify; defaults to ``step.effects`` (the - GUI path). The API tier passes ``api_binding.effects`` only. - - Returns an error string (HALT) or None (all effects confirmed or - reconciled). - """ - # ``verifier`` is the configured one by default, but the caller may pass - # the auto-wired backend-bound read-back verifier (the no-connector - # default path) for a step whose effects are different-path read-backs. - if verifier is None: - verifier = self.effect_verifier - assert verifier is not None # guaranteed by the caller - if effects is None: - effects = step.effects - for effect in effects: - refusal = placeholder_effect_refusal(step, effect, result) - if refusal is not None: - return refusal - try: - verdict = verify_effect_without_mutation(verifier, effect, before) - scope = effect_endpoint_scope(verifier) - selected_pre_state = getattr(before, "for_effect", None) - if callable(selected_pre_state): - # Candidate selection and its evidence strength are pinned - # before input. Do not recompute the tier after delivery: - # a stateful plugin must not change the receipt contract. - binding = selected_pre_state(effect) - tier = binding.tier - identity = binding.verifier_identity - scope = effect_endpoint_scope(binding.verifier) - if ( - verifier_effect_tier(binding.verifier, effect) != tier - or effect_verifier_identity(binding.verifier) != identity - ): - result.effect_verified = False - result.safety_halt = True - result.failure_category = "governed_refusal" - result.effect_results.append( - "selected effect verifier identity or evidence tier " - "changed after input; HALT" - ) - return ( - f"Effect verifier binding changed after input for step " - f"'{step.id}' — refusing evidence from a different " - "adapter or tier; reconciliation is required" - ) - else: - tier = verifier_effect_tier(verifier, effect) - identity = effect_verifier_identity(verifier) - except EffectContractMutationError: - result.effect_verified = False - result.safety_halt = True - result.failure_category = "governed_refusal" - result.effect_results.append( - "effect verifier changed the resolved effect contract; HALT" - ) - return ( - f"Effect verifier changed the resolved contract for step " - f"'{step.id}' — refusing mutable verification evidence; " - "run aborted" - ) - result.effect_field_checks.extend( - effect_field_checks(effect, verdict, tier) - ) - if verdict.confirmed: - result.effect_evidence.append( - EffectVerificationEvidence( - effect_contract_hash=effect.contract_hash(), - substrate=verdict.substrate, - verifier_identity=identity, - verification_tier=(int(tier) if tier is not None else None), - initial_verdict=verdict.verdict.value, - final_verdict=verdict.verdict.value, - observed_effect=verdict.observed_effect, - endpoint_scope=scope, - read_evidence=verdict.read_evidence, - ) - ) - result.effect_results.append( - f"[{verdict.substrate}] {effect.kind.value}: CONFIRMED" - + (f" — {verdict.reason}" if verdict.reason else "") - ) - continue - - # Non-CONFIRMED: never proceed on an unverified/contradicted write. - # An irreversible effect gets one reconcile-or-escalate pass (a - # compensable duplicate is fixable; missing / partial / collateral - # loss / INDETERMINATE always escalate). A reversible effect just - # halts. Either way the run stops -- this is the same - # refuse-rather-than-guess posture as the identity gate. - if effect.risk == "irreversible" and not read_only: - comp = reconcile_or_escalate( - effect, - verdict, - verifier=verifier, - before=before, - compensator=self.effect_compensator, - ) - if comp.proceed: - final_verdict = comp.final_verdict or verdict - result.effect_evidence.append( - EffectVerificationEvidence( - effect_contract_hash=effect.contract_hash(), - substrate=final_verdict.substrate, - verifier_identity=identity, - verification_tier=(int(tier) if tier is not None else None), - initial_verdict=verdict.verdict.value, - final_verdict=final_verdict.verdict.value, - observed_effect=final_verdict.observed_effect, - endpoint_scope=scope, - read_evidence=final_verdict.read_evidence, - reconciliation_completed=True, - reconciliation_actions=comp.actions_taken, - ) - ) - result.effect_results.append( - f"[{verdict.substrate}] {effect.kind.value}: " - f"{verdict.verdict.value.upper()} → RECONCILED " - f"({comp.actions_taken} action(s)) — {comp.reason}" - ) - continue - result.effect_verified = False - final_verdict = comp.final_verdict or verdict - result.effect_evidence.append( - EffectVerificationEvidence( - effect_contract_hash=effect.contract_hash(), - substrate=final_verdict.substrate, - verifier_identity=identity, - verification_tier=(int(tier) if tier is not None else None), - initial_verdict=verdict.verdict.value, - final_verdict=final_verdict.verdict.value, - observed_effect=final_verdict.observed_effect, - endpoint_scope=scope, - read_evidence=final_verdict.read_evidence, - reconciliation_actions=comp.actions_taken, - deferred_check=verdict.deferred_check, - ) - ) - result.effect_results.append( - f"[{verdict.substrate}] {effect.kind.value}: " - f"{verdict.verdict.value.upper()} → " - f"{comp.outcome.value.upper()} — {comp.reason}" - ) - prefix, read = _effect_read_wording(tier) - return ( - f"{prefix} HALTED step " - f"'{step.id}' ({step.intent}): {effect.kind.value} " - f"{verdict.verdict.value} against the {verdict.substrate} " - f"{read} and could not be reconciled " - f"({comp.outcome.value}) — " - f"{comp.escalation or comp.reason} — run aborted" - ) - - result.effect_verified = False - result.effect_evidence.append( - EffectVerificationEvidence( - effect_contract_hash=effect.contract_hash(), - substrate=verdict.substrate, - verifier_identity=identity, - verification_tier=(int(tier) if tier is not None else None), - initial_verdict=verdict.verdict.value, - final_verdict=verdict.verdict.value, - observed_effect=verdict.observed_effect, - endpoint_scope=scope, - read_evidence=verdict.read_evidence, - deferred_check=verdict.deferred_check, - ) - ) - result.effect_results.append( - f"[{verdict.substrate}] {effect.kind.value}: " - f"{verdict.verdict.value.upper()} — {verdict.reason}" - ) - prefix, read = _effect_read_wording(tier) - return ( - f"{prefix} HALTED step " - f"'{step.id}' ({step.intent}): {effect.kind.value} " - f"{verdict.verdict.value} against the {verdict.substrate} " - f"{read} (the screen indicated completion but the " - f"declared outcome is contradicted or unverifiable) — " - f"{verdict.reason} — run aborted" - ) - - result.effect_verified = True - return None - def _identity_band_still_changing( self, step: Step, resolution: Resolution, read_png: bytes ) -> bool: @@ -17156,46 +16375,6 @@ def _selection_target_continuous( and abs(refreshed[1] - focused[1]) <= qualified_h * 0.25 ) - @staticmethod - def _mapped_selection_readback_region( - recorded_target: Region, - recorded_readback: Region, - live_target: Region, - frame_png: bytes, - ) -> Optional[Region]: - """Map the recorded readback band onto a fresh live target. - - Absolute recording coordinates never drive verification. The mapping - preserves the band's target-relative offsets while allowing the - already-qualified target geometry to translate or scale modestly, then - clamps it to the exact final frame. - """ - - from openadapt_flow.vision import imgops - - frame = imgops.decode_bgr(frame_png) - if frame is None: - return None - frame_h, frame_w = frame.shape[:2] - target_x, target_y, target_w, target_h = recorded_target - read_x, read_y, read_w, read_h = recorded_readback - live_x, live_y, live_w, live_h = live_target - if min(target_w, target_h, read_w, read_h, live_w, live_h) <= 0: - return None - scale_x = live_w / target_w - scale_y = live_h / target_h - mapped_x = round(live_x + (read_x - target_x) * scale_x) - mapped_y = round(live_y + (read_y - target_y) * scale_y) - mapped_w = max(1, round(read_w * scale_x)) - mapped_h = max(1, round(read_h * scale_y)) - left = max(0, mapped_x) - top = max(0, mapped_y) - right = min(frame_w, mapped_x + mapped_w) - bottom = min(frame_h, mapped_y + mapped_h) - if right <= left or bottom <= top: - return None - return (left, top, right - left, bottom - top) - # -- closed-loop scroll ------------------------------------------------------ @timed_span("resolve") From 4960574c771aad774b83e8fe859e2b8603bae382 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:12:07 -0500 Subject: [PATCH 3/4] test: patch the resolver in its new settling module too --- packages/flow/tests/test_replayer.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/flow/tests/test_replayer.py b/packages/flow/tests/test_replayer.py index 52405aaba7..0e9991c85a 100644 --- a/packages/flow/tests/test_replayer.py +++ b/packages/flow/tests/test_replayer.py @@ -2342,6 +2342,12 @@ def scripted_resolve(*args, **kwargs): "openadapt_flow.runtime.replayer.resolve", scripted_resolve, ) + # Interstitial handling moved to runtime/replay/settling.py and reads its + # own ``resolve``; patch it too so every resolver call stays scripted. + monkeypatch.setattr( + "openadapt_flow.runtime.replay.settling.resolve", + scripted_resolve, + ) backend = FakeBackend() workflow = Workflow(name="wf", steps=[scroll_step(), click_step()]) From d8a682b2cac361c3d5bc2f41bb9822f30ad86579 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 16:29:34 -0500 Subject: [PATCH 4/4] fix(flow): keep recheck_deferred_readback type-hint imports at runtime --- .../openadapt_flow/runtime/replay/effects.py | 20 ++++++++++--------- packages/flow/tests/test_replayer.py | 14 +++++++++++++ 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/packages/flow/openadapt_flow/runtime/replay/effects.py b/packages/flow/openadapt_flow/runtime/replay/effects.py index be4cf6310a..cc18171da5 100644 --- a/packages/flow/openadapt_flow/runtime/replay/effects.py +++ b/packages/flow/openadapt_flow/runtime/replay/effects.py @@ -12,12 +12,17 @@ import hashlib import threading from types import SimpleNamespace -from typing import TYPE_CHECKING, Any, Optional # noqa: F401 +from typing import TYPE_CHECKING, Any, Mapping, Optional # noqa: F401 from openadapt_flow.assurance import effect_read_wording as _effect_read_wording -from openadapt_flow.ir import EffectVerificationEvidence, HaltObservation, StepResult +from openadapt_flow.ir import ( + EffectVerificationEvidence, + HaltObservation, + StepResult, + Workflow, +) from openadapt_flow.qualification_faults import effect_verifier_input_sha256 -from openadapt_flow.runtime.authorization import runtime_param_text +from openadapt_flow.runtime.authorization import RuntimeParamScalar, runtime_param_text from openadapt_flow.runtime.durable.first_local_runtime import ( placeholder_effect_refusal, ) @@ -40,18 +45,15 @@ ) if TYPE_CHECKING: - from typing import Literal, Mapping + from typing import Literal from openadapt_flow.backend import Backend - from openadapt_flow.ir import Region, RunReport, Step, Workflow + from openadapt_flow.ir import Region, RunReport, Step from openadapt_flow.qualification_faults import ( FaultMutationReceipt, QualificationFaultGate, ) - from openadapt_flow.runtime.authorization import ( - GovernedRunAuthorization, - RuntimeParamScalar, - ) + from openadapt_flow.runtime.authorization import GovernedRunAuthorization from openadapt_flow.runtime.effects import Effect, EffectVerifier from openadapt_flow.runtime.readback_pipeline import ( PipelinedReadback, diff --git a/packages/flow/tests/test_replayer.py b/packages/flow/tests/test_replayer.py index 0e9991c85a..f4ca12a731 100644 --- a/packages/flow/tests/test_replayer.py +++ b/packages/flow/tests/test_replayer.py @@ -4759,3 +4759,17 @@ def test_native_selection_missing_capability_refuses_before_input(bundle, run_di ) assert not report.success assert backend.actions == [] + + +def test_recheck_deferred_readback_type_hints_resolve(): + import typing + + hints = typing.get_type_hints(Replayer.recheck_deferred_readback) + assert set(hints) >= { + "workflow", + "deferred", + "params", + "run_id", + "read_only", + "return", + }